feat: manually mirror opencoze's code from bytedance

Change-Id: I09a73aadda978ad9511264a756b2ce51f5761adf
This commit is contained in:
fanlv
2025-07-20 17:36:12 +08:00
commit 890153324f
14811 changed files with 1923430 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
/* stylelint-disable selector-class-pattern */
.auto-generate-select {
:global {
.semi-radioGroup-horizontal {
width: 100%;
}
.semi-radio-cardRadioGroup {
flex-basis: 0;
flex-grow: 1;
border: 1px solid var(--semi-color-border);
}
.semi-radio-checked.semi-radio-cardRadioGroup {
border: 1px solid var(--semi-color-primary);
}
.semi-input-number {
width: 100%;
}
}
}
.auto-generate-radio {
:global {
.semi-radio-content {
min-width: 0;
overflow-wrap: break-word;
}
}
}
.auto-generate-label {
margin: 16px 0 8px;
color: var(--semi-color-text-1);
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useEffect, useState } from 'react';
import { I18n } from '@coze-arch/i18n';
import { PluginMockDataGenerateMode } from '@coze-arch/bot-tea';
import { RadioGroup, Radio, InputNumber } from '@coze-arch/bot-semi';
// eslint-disable-next-line no-restricted-imports
import { type RadioChangeEvent } from '@douyinfe/semi-ui/lib/es/radio';
import {
getLatestAutoGenerationChoice,
setLatestAutoGenerationChoice,
} from '../../utils/auto-generate-storage';
import style from './index.module.less';
interface AutoGenerateSelectProps {
showLabel?: boolean;
enableMulti?: boolean;
defaultCount?: number;
onChange?: (mode: AutoGenerateConfig) => void;
onInit?: (mode: AutoGenerateConfig) => void;
}
export interface AutoGenerateConfig {
generateMode: PluginMockDataGenerateMode;
generateCount?: number;
}
export function AutoGenerateSelect({
showLabel,
enableMulti,
defaultCount,
onChange,
onInit,
}: AutoGenerateSelectProps) {
const [config, setConfig] = useState<AutoGenerateConfig>({
generateMode: PluginMockDataGenerateMode.MANUAL,
generateCount: defaultCount || 1,
});
const onSelectChange = (e: RadioChangeEvent) => {
const updatedConfig = { ...config, generateMode: e.target.value };
setLatestAutoGenerationChoice(e.target.value);
setConfig(updatedConfig);
onChange?.(updatedConfig);
};
const initMode = async () => {
const m = await getLatestAutoGenerationChoice();
const initConfig = { ...config, generateMode: m };
setConfig(initConfig);
onInit?.(initConfig);
};
useEffect(() => {
initMode();
}, []);
return (
<div className={style['auto-generate-select']}>
{showLabel ? (
<h4 className={style['auto-generate-label']}>
{I18n.t('plugin_creation_method')}
</h4>
) : null}
<RadioGroup
type="card"
value={config.generateMode}
onChange={onSelectChange}
>
<Radio
className={style['auto-generate-radio']}
value={PluginMockDataGenerateMode.RANDOM}
extra={I18n.t('generate_randomly_based_on_data_type_name')}
>
{I18n.t('randomlymode')}
</Radio>
<Radio
className={style['auto-generate-radio']}
value={PluginMockDataGenerateMode.LLM}
extra={I18n.t('intelligently_generated_by_large_language_model')}
>
{I18n.t('llm_mode')}
</Radio>
</RadioGroup>
{enableMulti && showLabel ? (
<h4 className={style['auto-generate-label']}>
{I18n.t('mock_data_quantity')}
</h4>
) : null}
{enableMulti ? (
<InputNumber
value={config.generateCount}
max={5}
min={1}
onChange={e => {
if (!Number.isNaN(Number(e))) {
const updatedConfig = { ...config, generateCount: Number(e) };
setConfig(updatedConfig);
onChange?.(updatedConfig);
}
}}
/>
) : null}
</div>
);
}

View File

@@ -0,0 +1,125 @@
.select-container {
max-width: 100%;
display: inline-block;
background-color: transparent;
border: none;
padding: 4px 6px;
border-radius: 6px;
&.switch-disabled {
* {
/* stylelint-disable-next-line declaration-no-important */
color: #1D1C23CC !important;
}
}
div {
span {
&[aria-label="small_triangle_down"] {
color: #1D1C23CC;
}
}
}
}
.option-list {
max-width: 336px;
min-width: 234px;
padding: 4px;
font-size: 12px;
:global {
.semi-typography {
color: #1D1C23;
}
.semi-select-option-list {
min-height: 40px;
}
.semi-select-loading-wrapper {
display: flex;
justify-content: center;
}
}
}
.item-selected {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
font-size: 12px;
font-weight: 400;
height: 16px;
line-height: 16px;
}
.select-label {
svg {
>path {
/* stylelint-disable-next-line declaration-no-important */
fill: currentcolor !important;
fill-opacity: 1;
}
}
}
.custom-option-render-focused {
background-color: rgb(46 46 56 / 8%);
cursor: pointer;
}
.custom-option-render-selected {
font-weight: 600;
}
.custom-option-render-disabled {
cursor: not-allowed;
:global {
.semi-typography {
color: #1D1C2359;
}
}
}
.select-option-container {
display: flex;
align-items: center;
height: 32px;
padding: 8px 8px 8px 16px;
border-radius: 4px;
}
.divider {
height: 1px;
background: var(--semi-color-border);
margin: 4px 0;
}
.create-container {
padding: 0 16px;
color: #4D53E8;
height: 32px;
display: flex;
align-items: center;
cursor: pointer;
}
.load-more {
color: #4D53E8;
display: flex;
align-items: center;
justify-content: center;
.spin-icon {
margin-right: 8px;
}
}

View File

@@ -0,0 +1,602 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable @coze-arch/max-line-per-function -- 迁移代码 */
/* eslint-disable @typescript-eslint/no-explicit-any -- 迁移代码 */
/* eslint-disable max-lines -- 迁移代码 */
/* eslint-disable max-lines-per-function -- 迁移代码 */
import {
useState,
useEffect,
useRef,
forwardRef,
type ForwardedRef,
useImperativeHandle,
} from 'react';
import classNames from 'classnames';
import {
useInViewport,
useInfiniteScroll,
useRequest,
useUnmount,
} from 'ahooks';
import { userStoreService } from '@coze-studio/user-store';
import { logger } from '@coze-arch/logger';
import { I18n } from '@coze-arch/i18n';
import {
PluginMockDataGenerateMode,
sendTeaEvent,
type ParamsTypeDefine,
EVENT_NAMES,
} from '@coze-arch/bot-tea';
import { useSpaceStore } from '@coze-arch/bot-studio-store';
// eslint-disable-next-line @coze-arch/no-pkg-dir-import
import { type SemiSelectActions } from '@coze-arch/bot-semi/src/components/ui-select';
import {
Spin,
UIToast,
Tooltip,
UIButton,
UISelect,
} from '@coze-arch/bot-semi';
import { IconAdd } from '@coze-arch/bot-icons';
import { SceneType, usePageJumpService } from '@coze-arch/bot-hooks';
import { SpaceType } from '@coze-arch/bot-api/developer_api';
import {
TrafficScene,
infra,
type BizCtx,
type MockSet,
} from '@coze-arch/bot-api/debugger_api';
import { debuggerApi } from '@coze-arch/bot-api';
import { IconTick, IconUploadError } from '@douyinfe/semi-icons';
import { MockSetEditModal } from '../mockset-edit-modal';
import { MockSetDeleteModal } from '../mockset-delete-modal';
import { type AutoGenerateConfig } from '../auto-generate-select';
import {
getEnvironment,
getMockSubjectInfo,
getPluginInfo,
getUsedScene,
isCurrent,
isRealData,
} from '../../utils';
import {
type MockSelectOptionProps,
type MockSelectRenderOptionProps,
type MockSetSelectProps,
MockSetStatus,
} from '../../interface';
import { useInitialGetEnabledMockSet } from '../../hooks/use-get-mockset';
import {
CONNECTOR_ID,
DELAY_TIME,
MOCK_OPTION_LIST,
POLLING_INTERVAL,
REAL_DATA_ID,
REAL_DATA_MOCKSET,
} from '../../const';
import { MockSetItem } from './option-item';
import styles from './index.module.less';
export function getMockSetOption(mockSet: MockSet): MockSelectOptionProps {
const isInValid =
!isRealData(mockSet) &&
(mockSet?.schemaIncompatible || !mockSet?.mockRuleQuantity);
return {
value: mockSet?.id || '',
label: (
<Tooltip
key={mockSet?.id}
content={I18n.t('mockset_invaild_tip', { MockSetName: mockSet.name })}
style={{ display: isInValid ? 'block' : 'none' }}
>
<span
className={classNames(
'flex items-center w-[100%] min-w-0',
styles['select-label'],
)}
>
{isInValid ? (
<IconUploadError
style={{
verticalAlign: 'middle',
marginRight: 2,
color: '#FF8500',
}}
/>
) : null}
<span
className={classNames(
'flex-1 min-w-0 overflow-hidden text-ellipsis',
isInValid ? 'text-[#1D1C2359]' : 'text-[#1D1C23CC]',
)}
>
{mockSet?.name || ''}
</span>
</span>
</Tooltip>
),
disabled: isInValid,
detail: mockSet,
};
}
export function getMockSetOptionList(
mockSets: MockSet[],
): Array<MockSelectOptionProps> {
return mockSets.map(mockSet => getMockSetOption(mockSet));
}
export interface MockSetSelectActions {
handleParentNodeDelete: () => void;
}
const MockSetSelectComp = (
{
bindSubjectInfo: mockSubjectInfo,
bizCtx: bizSceneCtx,
className,
style: baseStyle,
readonly,
}: MockSetSelectProps,
ref: ForwardedRef<MockSetSelectActions>,
) => {
const { detail: subjectDetail, ...bindSubjectInfo } = mockSubjectInfo;
const { spaceID, toolID, pluginID } = getPluginInfo(
bizSceneCtx,
bindSubjectInfo,
);
const uid = userStoreService.useUserInfo()?.user_id_str;
const spaceType = useSpaceStore(s => s.space.space_type);
const isPersonal = spaceType === SpaceType.Personal;
const bizCtx: BizCtx = {
...bizSceneCtx,
connectorUID: uid,
connectorID: CONNECTOR_ID, // 业务线为Coze
};
const { jump } = usePageJumpService();
const [selectedMockSet, setSelectedMockSet] =
useState<MockSet>(REAL_DATA_MOCKSET);
const selectedValue = getMockSetOption(selectedMockSet);
const [optionList, setOptionList] = useState<Array<MockSelectOptionProps>>(
getMockSetOptionList(MOCK_OPTION_LIST),
);
const [showCreateModal, setShowCreateModal] = useState(false);
const [deleteMockSet, setDeleteMockSet] = useState<MockSet | undefined>();
const preSelectionRef = useRef<MockSet>(REAL_DATA_MOCKSET);
const selectionDomRef = useRef<HTMLDivElement>(null);
const selectionRef = useRef<SemiSelectActions>(null);
const [inViewPort] = useInViewport(selectionDomRef);
const {
data: enabledMockSetInfo,
addMockComp,
removeMockComp,
start,
cancel,
setRestartTimer,
} = useInitialGetEnabledMockSet({
bizCtx,
pollingInterval: POLLING_INTERVAL,
});
const { runAsync: changeMockSet, loading: changeMockSetLoading } = useRequest(
async (mockSet: MockSet, isBinding = true) => {
const basicParams: ParamsTypeDefine[EVENT_NAMES.use_mockset_front] = {
environment: getEnvironment(),
workspace_id: spaceID || '',
workspace_type: isPersonal ? 'personal_workspace' : 'team_workspace',
tool_id: toolID || '',
status: 1,
mock_set_id: (mockSet.id as string) || '',
where: getUsedScene(bizCtx.trafficScene),
};
try {
await debuggerApi.BindMockSet({
mockSetID: isBinding ? mockSet.id : '0',
bizCtx,
mockSubject: bindSubjectInfo,
});
isBinding &&
sendTeaEvent(EVENT_NAMES.use_mockset_front, {
...basicParams,
status: 0,
});
} catch (e) {
setSelectedMockSet(preSelectionRef.current);
logger.error({ error: e as Error, eventName: 'change_mockset_fail' });
isBinding &&
sendTeaEvent(EVENT_NAMES.use_mockset_front, {
...basicParams,
status: 1,
error: (e as Error | undefined)?.message as string,
});
}
},
{
manual: true,
},
);
const handleChange = async (obj?: MockSelectOptionProps) => {
cancel();
preSelectionRef.current = selectedMockSet;
setSelectedMockSet((obj as MockSelectOptionProps)?.detail || {});
await changeMockSet((obj as MockSelectOptionProps)?.detail || {});
const restartTimerId = setTimeout(() => {
start();
}, DELAY_TIME);
setRestartTimer(restartTimerId);
};
const {
reload: fetchOptionList,
loadMore,
loading,
loadingMore,
data: optionListData,
} = useInfiniteScroll(
async d => {
try {
const res = await debuggerApi.MGetMockSet({
bizCtx,
mockSubject: getMockSubjectInfo(bizCtx, mockSubjectInfo),
pageToken: d?.pageToken,
orderBy: infra.OrderBy.UpdateTime,
desc: true,
});
const mockSetList = getMockSetOptionList(res?.mockSets || []);
return {
list: mockSetList || [],
pageToken: res?.pageToken,
hasMore: res?.hasMore ?? true,
schema: res?.schema,
count: res?.count,
};
} catch (e) {
logger.error({
error: e as Error,
eventName: 'mockset_list_fetch_fail',
});
return {
list: [],
pageToken: d?.pageToken,
hasMore: d?.hasMore,
};
}
},
{
manual: true,
},
);
useImperativeHandle(ref, () => ({
handleParentNodeDelete: () => {
changeMockSet(selectedMockSet, false);
},
}));
useEffect(() => {
const newOptionList = [
getMockSetOption(REAL_DATA_MOCKSET),
...(optionListData?.list || []),
];
setOptionList(newOptionList);
}, [optionListData]);
useEffect(() => {
const mockSetInfo = enabledMockSetInfo.find(mockInfo =>
isCurrent(
{
bizCtx: mockInfo?.mockSetBinding?.bizCtx || {},
bindSubjectInfo: mockInfo?.mockSetBinding?.mockSubject || {},
},
{
bizCtx,
bindSubjectInfo,
},
),
);
if (changeMockSetLoading) {
return;
}
if (mockSetInfo?.mockSetDetail) {
setSelectedMockSet(mockSetInfo?.mockSetDetail);
} else {
setSelectedMockSet(REAL_DATA_MOCKSET);
}
}, [enabledMockSetInfo]);
useUnmount(() => {
const length = removeMockComp({ bizCtx, bindSubjectInfo });
if (!length) {
cancel();
}
});
useEffect(() => {
if (inViewPort) {
const length = addMockComp({ bizCtx, bindSubjectInfo });
if (length === 1) {
start();
}
} else {
const length = removeMockComp({ bizCtx, bindSubjectInfo });
if (!length) {
cancel();
}
}
}, [inViewPort]);
const closePanel = () => {
selectionRef?.current?.close();
};
const handleView = (
record?: MockSet,
autoGenerateConfig?: AutoGenerateConfig,
) => {
const { trafficScene } = bizCtx || {};
const { id } = record || {};
if (spaceID && pluginID && toolID && id) {
jump(
trafficScene === TrafficScene.CozeWorkflowDebug
? SceneType.WORKFLOW__TO__PLUGIN_MOCK_DATA
: SceneType.BOT__TO__PLUGIN_MOCK_DATA,
{
spaceId: spaceID,
pluginId: pluginID,
toolId: toolID,
toolName: subjectDetail?.name,
mockSetId: String(id),
mockSetName: record?.name,
bizCtx: JSON.stringify(bizCtx),
bindSubjectInfo: JSON.stringify(bindSubjectInfo),
generationMode: autoGenerateConfig?.generateMode,
},
);
}
};
const renderCreateMockSet = () => (
<>
<div className={styles.divider}></div>
<div
onClick={() => {
setShowCreateModal(true);
closePanel();
}}
className={styles['create-container']}
>
<IconAdd
className="mr-[10px]"
style={{ fontSize: 14, color: '#4D53E8' }}
/>
<span>{I18n.t('create_mockset')}</span>
</div>
</>
);
const renderLoadMore = () =>
loading ||
(optionListData?.list?.length || 0) >=
(optionListData?.count || 0) ? null : (
<div
className={classNames(
styles['select-option-container'],
styles['load-more'],
)}
>
{loadingMore ? (
<>
<Spin wrapperClassName={styles['spin-icon']} />
<span>{I18n.t('Loading')}</span>
</>
) : (
<UIButton
onClick={loadMore}
theme="borderless"
style={{ fontSize: 12 }}
>
{I18n.t('Load More' as any)}
</UIButton>
)}
</div>
);
const renderOptionItem = (renderProps: MockSelectRenderOptionProps) => {
const {
disabled,
selected,
value,
focused,
style,
onMouseEnter,
onClick,
detail,
} = renderProps;
const getTooltipInfo = () => {
if (detail?.schemaIncompatible) {
return I18n.t('tool_updated_check_mockset_compatibility');
} else if ((detail?.mockRuleQuantity || 0) <= 0) {
return I18n.t('mockset_is_empty_add_data_before_use');
}
return '';
};
return (
<Tooltip
zIndex={110}
content={getTooltipInfo()}
visible={disabled && focused}
position="left"
style={{ display: disabled ? 'block' : 'none' }} // visible disabled不生效
>
<div
style={style}
className={classNames(
styles['select-option-container'],
focused && styles['custom-option-render-focused'],
disabled && styles['custom-option-render-disabled'],
selected && styles['custom-option-render-selected'],
)}
onClick={onClick}
onMouseEnter={onMouseEnter}
>
<div className="w-[16px] h-[16px] mr-[8px]">
{selected ? (
<IconTick style={{ fontSize: 14 }} className="text-[#4D53E8]" />
) : (
<div className="w-[16px]"></div>
)}
</div>
{value === REAL_DATA_ID ? (
<span>{I18n.t('real_data')}</span>
) : (
<MockSetItem
status={
detail?.schemaIncompatible
? MockSetStatus.Incompatible
: MockSetStatus.Normal
}
name={detail?.name || ''}
onDelete={() => {
closePanel();
setDeleteMockSet(detail);
}}
onView={() => {
handleView(detail);
}}
disableCreator={isPersonal}
viewOnly={uid !== detail?.creator?.ID}
creatorName={detail?.creator?.name}
className="flex-1 min-w-0"
></MockSetItem>
)}
</div>
</Tooltip>
);
};
return (
<div ref={selectionDomRef} style={baseStyle} className={className}>
<UISelect
stopPropagation
disabled={readonly || changeMockSetLoading}
className={classNames(
styles['select-container'],
changeMockSetLoading && styles['switch-disabled'],
)}
ref={selectionRef}
selectedClassname={styles['item-selected']}
optionList={optionList}
dropdownClassName={styles['option-list']}
outerBottomSlot={renderCreateMockSet()}
innerBottomSlot={renderLoadMore()}
onDropdownVisibleChange={(visible: boolean) => {
if (visible) {
fetchOptionList();
} else {
setOptionList([getMockSetOption(REAL_DATA_MOCKSET)]);
}
}}
loading={loading}
renderOptionItem={renderOptionItem}
value={selectedValue}
onChangeWithObject
onChange={async obj => {
await handleChange(obj as unknown as MockSelectOptionProps);
}}
/>
{showCreateModal ? (
<MockSetEditModal
zIndex={9999}
visible={showCreateModal}
onCancel={() => setShowCreateModal(false)}
onSuccess={(info, autoGenerateConfig) => {
const { id } = info || {};
setShowCreateModal(false);
const msgMap = {
[PluginMockDataGenerateMode.LLM]: I18n.t(
'created_mockset_please_add_mock_data_llm_generation',
),
[PluginMockDataGenerateMode.RANDOM]: I18n.t(
'created_mockset_please_add_mock_data_random_generation',
),
[PluginMockDataGenerateMode.MANUAL]: I18n.t(
'created_mockset_please_add_mock_data',
),
};
UIToast.success(
msgMap[
autoGenerateConfig?.generateMode ||
PluginMockDataGenerateMode.MANUAL
],
);
handleView({ id }, autoGenerateConfig);
}}
initialInfo={{
bizCtx,
bindSubjectInfo,
name: subjectDetail?.name,
}}
needResetPopoverContainer={
bizCtx.trafficScene === TrafficScene.CozeWorkflowDebug
}
/>
) : null}
{deleteMockSet ? (
<MockSetDeleteModal
zIndex={9999}
visible={!!deleteMockSet}
mockSetInfo={{
detail: deleteMockSet,
ctx: { bizCtx, mockSubjectInfo: bindSubjectInfo },
}}
onSuccess={() => {
deleteMockSet.id === selectedMockSet.id &&
setSelectedMockSet(REAL_DATA_MOCKSET);
setDeleteMockSet(undefined);
cancel();
start();
}}
onCancel={() => setDeleteMockSet(undefined)}
needResetPopoverContainer={
bizCtx.trafficScene === TrafficScene.CozeWorkflowDebug
}
/>
) : null}
</div>
);
};
export const MockSetSelect = forwardRef(MockSetSelectComp);

View File

@@ -0,0 +1,45 @@
.mock-select-item {
display: flex;
align-items: center;
justify-content: space-between;
width: '100%';
}
.mock-main-info {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
.status-icon {
margin-right: 4px;
color: #FF8500;
}
.mock-name {
font-size: 12px;
}
}
.mock-extra-info {
width: 64px;
margin-left: 16px;
display: flex;
align-items: center;
justify-content: flex-end;
.creator-name {
color: #1D1C2359;
font-size: 12px;
}
.operation-icon {
font-size: 14px;
color: #1D1C2399;
width: 40px;
display: flex;
align-items: center;
justify-content: flex-end;
cursor: pointer;
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useState, type CSSProperties } from 'react';
import classNames from 'classnames';
import { Typography, UIIconButton } from '@coze-arch/bot-semi';
import { IconDeleteOutline, IconEdit } from '@coze-arch/bot-icons';
import { IconEyeOpened, IconUploadError } from '@douyinfe/semi-icons';
import { MockSetStatus } from '../../interface';
import styles from './option-item.module.less';
export interface MockSetItemProps {
name: string;
onDelete?: () => void;
onView?: () => void;
status?: MockSetStatus;
creatorName?: string;
viewOnly?: boolean;
disableCreator?: boolean;
className?: string;
style?: CSSProperties;
}
export const MockSetItem = ({
name,
onDelete,
onView,
status = MockSetStatus.Normal,
creatorName,
viewOnly,
disableCreator,
className,
style,
}: MockSetItemProps) => {
const [isHover, setIsHover] = useState(false);
const renderExtraInfo = () => {
if (isHover) {
return (
<div
className={styles['operation-icon']}
onClick={e => e.stopPropagation()}
>
{viewOnly ? (
<UIIconButton onClick={onView} icon={<IconEyeOpened />} />
) : (
<>
<UIIconButton
onClick={onView}
icon={<IconEdit />}
wrapperClass="mr-[4px]"
/>
<UIIconButton onClick={onDelete} icon={<IconDeleteOutline />} />
</>
)}
</div>
);
}
return disableCreator ? null : (
<Typography.Text
ellipsis={{
showTooltip: {
opts: { content: creatorName },
},
}}
className={styles['creator-name']}
>
{creatorName}
</Typography.Text>
);
};
return (
<div
className={classNames(styles['mock-select-item'], className)}
style={style}
onMouseEnter={() => {
setIsHover(true);
}}
onMouseLeave={() => setIsHover(false)}
>
<span className={styles['mock-main-info']}>
{status !== MockSetStatus.Normal && (
<IconUploadError className={styles['status-icon']} />
)}
<Typography.Text ellipsis={{}} className={styles['mock-name']}>
{name}
</Typography.Text>
</span>
<div className={styles['mock-extra-info']}>{renderExtraInfo()}</div>
</div>
);
};

View File

@@ -0,0 +1,162 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useEffect, useState } from 'react';
import { useRequest } from 'ahooks';
import { logger } from '@coze-arch/logger';
import { I18n } from '@coze-arch/i18n';
import {
EVENT_NAMES,
sendTeaEvent,
type ParamsTypeDefine,
} from '@coze-arch/bot-tea';
import { useSpaceStore } from '@coze-arch/bot-studio-store';
import { UIModal } from '@coze-arch/bot-semi';
import { SpaceType } from '@coze-arch/bot-api/developer_api';
import {
type BizCtx,
type MockSet,
type ComponentSubject,
} from '@coze-arch/bot-api/debugger_api';
import { debuggerApi } from '@coze-arch/bot-api';
import { IconAlertCircle } from '@douyinfe/semi-icons';
import { getEnvironment, getPluginInfo } from '../../utils';
export interface MockSetInfo {
detail: MockSet;
ctx?: {
mockSubjectInfo?: ComponentSubject;
bizCtx?: BizCtx;
};
}
export interface MockSetEditModalProps {
visible: boolean;
zIndex?: number;
mockSetInfo: MockSetInfo;
onSuccess?: () => void;
onCancel?: () => void;
needResetPopoverContainer?: boolean;
}
function isValidRefCount(refCount: number) {
return refCount >= 0;
}
export const MockSetDeleteModal = ({
visible,
mockSetInfo,
onSuccess,
onCancel,
zIndex,
needResetPopoverContainer,
}: MockSetEditModalProps) => {
const {
detail: { id },
ctx,
} = mockSetInfo || {};
const [mockSetRefCount, setMockSetRefCount] = useState(-1);
// space信息
const spaceType = useSpaceStore(s => s.space.space_type);
const isPersonal = spaceType === SpaceType.Personal;
const { run: fetchRefInfo } = useRequest(
async () => {
const { spaceID } = getPluginInfo(
ctx?.bizCtx || {},
ctx?.mockSubjectInfo || {},
);
try {
const { usersUsageCount } = await debuggerApi.GetMockSetUsageInfo({
mockSetID: id,
spaceID,
});
setMockSetRefCount(Number(usersUsageCount ?? 0));
} catch (e) {
logger.error({
error: e as Error,
eventName: 'fetch_mockset_ref_fail',
});
setMockSetRefCount(0);
}
},
{
manual: true,
},
);
useEffect(() => {
fetchRefInfo();
}, [mockSetInfo]);
const renderTitle =
mockSetRefCount > 0
? I18n.t('people_using_mockset_delete', { num: mockSetRefCount })
: I18n.t('delete_the_mockset');
const handleOk = async () => {
const { toolID, spaceID } = getPluginInfo(
ctx?.bizCtx || {},
ctx?.mockSubjectInfo || {},
);
const basicParams: ParamsTypeDefine[EVENT_NAMES.del_mockset_front] = {
environment: getEnvironment(),
workspace_id: spaceID || '',
workspace_type: isPersonal ? 'personal_workspace' : 'team_workspace',
tool_id: toolID || '',
mock_set_id: String(id) || '',
status: 1,
};
try {
id && (await debuggerApi.DeleteMockSet({ id, bizCtx: ctx?.bizCtx }));
onSuccess?.();
sendTeaEvent(EVENT_NAMES.del_mockset_front, {
...basicParams,
status: 0,
});
} catch (e) {
sendTeaEvent(EVENT_NAMES.del_mockset_front, {
...basicParams,
status: 1,
error: (e as Error | undefined)?.message as string,
});
}
};
return (
<UIModal
type="info"
zIndex={zIndex}
icon={
<IconAlertCircle
size="extra-large"
className="inline-flex text-[#FF2710]"
/>
}
title={renderTitle}
visible={isValidRefCount(mockSetRefCount) && visible}
onCancel={onCancel}
onOk={handleOk}
getPopupContainer={
needResetPopoverContainer ? () => document.body : undefined
}
okType="danger"
>
{I18n.t('operation_cannot_be_reversed')}
</UIModal>
);
};

View File

@@ -0,0 +1,15 @@
.mockset-create-form {
font-size: 14px;
:global {
.semi-checkbox-addon {
font-weight: 600;
color: var(--semi-color-text-0);
font-size: 14px;
}
.semi-form-field {
padding-top: 0;
}
}
}

View File

@@ -0,0 +1,301 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable @coze-arch/max-line-per-function -- 迁移代码 */
import { useRef } from 'react';
import { I18n } from '@coze-arch/i18n';
import { PluginMockDataGenerateMode } from '@coze-arch/bot-tea';
import {
EVENT_NAMES,
sendTeaEvent,
type ParamsTypeDefine,
} from '@coze-arch/bot-tea';
import { useSpaceStore } from '@coze-arch/bot-studio-store';
import { type FormApi } from '@coze-arch/bot-semi/Form';
import { Form, UIFormTextArea, UIModal, UIToast } from '@coze-arch/bot-semi';
import { type ApiError, isApiError } from '@coze-arch/bot-http';
import { useFlags } from '@coze-arch/bot-flags';
import { SpaceType } from '@coze-arch/bot-api/developer_api';
import { type MockSet } from '@coze-arch/bot-api/debugger_api';
import { debuggerApi } from '@coze-arch/bot-api';
import {
type AutoGenerateConfig,
AutoGenerateSelect,
} from '../auto-generate-select';
import { getEnvironment, getMockSubjectInfo, getPluginInfo } from '../../utils';
import { type BasicMockSetInfo } from '../../interface';
import { MOCK_SET_ERR_CODE, mockSetInfoRules } from '../../const';
import styles from './index.module.less';
export interface EditMockSetInfo
extends BasicMockSetInfo,
Partial<AutoGenerateConfig> {
id?: string;
name?: string;
desc?: string;
autoGenerate?: boolean;
}
export interface MockSetEditModalProps {
visible?: boolean;
zIndex?: number;
disabled?: boolean;
initialInfo: EditMockSetInfo;
onSuccess?: (
mockSetInfo?: MockSet,
autoGenerateConfig?: AutoGenerateConfig,
) => void;
onCancel?: () => void;
needResetPopoverContainer?: boolean;
}
function getRandomName(toolName?: string): string | undefined {
if (!toolName) {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const num = Math.floor(Math.random() * 90 + 10);
return `${toolName} mockset${num}`;
}
export const MockSetEditModal = ({
visible,
zIndex,
disabled,
initialInfo,
onSuccess,
onCancel,
needResetPopoverContainer,
}: MockSetEditModalProps) => {
const formApiRef = useRef<FormApi<EditMockSetInfo>>();
const [FLAGS] = useFlags();
// 根据是否传入 id 判断是否为创建场景
const isCreate = !initialInfo.id;
// space信息
const spaceType = useSpaceStore(s => s.space.space_type);
const isPersonal = spaceType === SpaceType.Personal;
const handleAutoGenerateSelect = (config: AutoGenerateConfig) => {
formApiRef.current?.setValue?.('generateMode', String(config.generateMode));
formApiRef.current?.setValue?.(
'generateCount',
String(config.generateCount),
);
};
const handleSubmit = async (formValues: EditMockSetInfo) => {
const {
id: existingId,
name,
desc,
bindSubjectInfo,
bizCtx,
autoGenerate,
generateMode,
generateCount,
} = formValues;
const { toolID, spaceID } = getPluginInfo(bizCtx, bindSubjectInfo);
const basicParams: ParamsTypeDefine[EVENT_NAMES.create_mockset_front] = {
environment: getEnvironment(),
workspace_id: spaceID || '',
workspace_type: isPersonal ? 'personal_workspace' : 'team_workspace',
tool_id: toolID || '',
status: 1,
mock_set_id: '',
auto_gen_mode: !autoGenerate
? PluginMockDataGenerateMode.MANUAL
: Number(generateMode) || PluginMockDataGenerateMode.RANDOM,
mock_counts: 1,
};
try {
const { id } = await debuggerApi.SaveMockSet(
{
name,
description: desc,
mockSubject: getMockSubjectInfo(bizCtx, bindSubjectInfo),
bizCtx,
id: existingId || '0',
},
{ __disableErrorToast: true },
);
onSuccess?.(
{ id, name, description: desc },
autoGenerate
? {
generateMode: Number(generateMode),
generateCount: Number(generateCount),
}
: undefined,
);
sendTeaEvent(EVENT_NAMES.create_mockset_front, {
...basicParams,
status: 0,
mock_set_id: String(id) || '',
});
} catch (e) {
const { message } = (e as Error | undefined) || {};
const reportParams: ParamsTypeDefine[EVENT_NAMES.create_mockset_front] = {
...basicParams,
status: 1,
error: message,
error_type: 'unknown',
};
if (isApiError(e)) {
const { code } = (e as ApiError) || {};
if (Number(code) === MOCK_SET_ERR_CODE.REPEAT_NAME) {
formApiRef.current?.setError('name', I18n.t('name_already_taken'));
sendTeaEvent(EVENT_NAMES.create_mockset_front, {
...reportParams,
error_type: 'repeat_name',
});
return;
}
}
if (message) {
UIToast.error(message);
}
sendTeaEvent(EVENT_NAMES.create_mockset_front, {
...reportParams,
error_type: 'unknown',
});
}
};
const handleOk = async () => {
await formApiRef.current?.submitForm();
};
return (
<UIModal
type="action-small"
zIndex={zIndex}
title={`${isCreate ? I18n.t('create_mockset') : I18n.t('edit_mockset')}`}
visible={visible}
getPopupContainer={
needResetPopoverContainer ? () => document.body : undefined
}
onCancel={onCancel}
okButtonProps={{
onClick: handleOk,
disabled,
}}
>
<Form<EditMockSetInfo>
getFormApi={api => (formApiRef.current = api)}
showValidateIcon={false}
initValues={
isCreate
? { ...initialInfo, name: getRandomName(initialInfo.name) }
: initialInfo
}
onSubmit={values => handleSubmit(values)}
className={styles['mockset-create-form']}
>
{({ formState }) => (
<>
{/* mockSet名称 */}
{disabled ? (
<Form.Slot
label={{
text: I18n.t('mockset_name'),
required: true,
}}
>
<div>{initialInfo?.name}</div>
</Form.Slot>
) : (
<UIFormTextArea
field="name"
label={I18n.t('mockset_name')}
placeholder={I18n.t('good_mockset_name_descriptive_concise')}
trigger={['blur', 'change']}
maxCount={50}
maxLength={50}
rows={1}
onBlur={() => {
formApiRef.current?.setValue(
'name',
formApiRef.current?.getValue('name')?.trim(),
);
}}
rules={mockSetInfoRules.name}
/>
)}
{/* mockSet描述 */}
{disabled ? (
<Form.Slot
label={{
text: I18n.t('mockset_description'),
}}
>
<div>{initialInfo?.desc}</div>
</Form.Slot>
) : (
<UIFormTextArea
field="desc"
label={{
text: I18n.t('mockset_description'),
}}
trigger={['blur', 'change']}
placeholder={I18n.t('describe_use_scenarios_of_mockset')}
rows={2}
maxCount={2000}
maxLength={2000}
rules={mockSetInfoRules.desc}
onBlur={() => {
formApiRef.current?.setValue(
'desc',
formApiRef.current?.getValue('desc')?.trim(),
);
}}
/>
)}
{/* 二期支持autoGenerate*/}
{/* 社区版暂不支持该功能 */}
{isCreate && FLAGS['bot.devops.mockset_auto_generate'] ? (
<>
<Form.Checkbox
field="autoGenerate"
noLabel
disabled={disabled}
className={styles['auto-generate-checkbox']}
>
{I18n.t('auto_generate')}
</Form.Checkbox>
{formState.values.autoGenerate ? (
<AutoGenerateSelect
onInit={handleAutoGenerateSelect}
onChange={handleAutoGenerateSelect}
/>
) : null}
</>
) : null}
</>
)}
</Form>
</UIModal>
);
};