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,92 @@
.related-entities-option {
cursor: pointer;
margin-bottom: 2px;
padding: 0;
font-size: 14px;
line-height: 20px;
border-radius: 4px;
&:last-child {
margin-bottom: 0;
}
&:hover{
background-color: var(--coz-mg-secondary-hovered, rgba(87, 104, 161, 8%));
}
}
.related-entities-option-disabled {
cursor: not-allowed;
color: var(--Fg-COZ-fg-dim, rgba(55, 67, 106, 38%));
opacity: 0.5;
}
.related-entities-option-selected {
background-color: var(--coz-mg-primary);
}
.bot-foot-loading {
display: flex;
align-items: center;
justify-content: center;
color: #4D53E8;
background-color: white;
}
.empty-block {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
box-sizing: border-box;
width: 100%;
height: 100%;
.text {
margin-top: 10px;
font-size: 12px;
line-height: 16px;
color: rgba(52, 60, 87, 72%);
text-align: center;
}
}
.bot-panel-option {
margin-bottom: 2px;
&:last-child {
margin-bottom: 0;
}
}
.variable-panel-option {
margin-bottom: 2px;
padding: 0;
font-size: 14px;
line-height: 20px;
&:last-child {
margin-bottom: 0;
}
&:global(.semi-select-option-selected) {
background-color: var(--coz-mg-primary);
}
&:global(.semi-select-option):hover {
background-color: var(--coz-mg-secondary-hovered, rgba(87, 104, 161, 8%));
}
}
.variable-option-checked {
font-weight: 500;
color: rgba(81, 71, 255, 100%);
}

View File

@@ -0,0 +1,25 @@
/*
* 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 { EmptyVariableContent } from './variable-panel/variable-panel';
import type { BotProjectVariableSelectProps } from './types';
import BotProjectVariableSelect from './select';
export {
BotProjectVariableSelect,
EmptyVariableContent,
BotProjectVariableSelectProps,
};

View File

@@ -0,0 +1,39 @@
/*
* 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 React from 'react';
import { I18n } from '@coze-arch/i18n';
import { IconCozEmpty } from '@coze-arch/coze-design/icons';
import s from '../index.module.less';
export default function EmptyContent() {
return (
<div className={s['empty-block']}>
<IconCozEmpty
style={{ fontSize: '32px', color: 'rgba(52, 60, 87, 0.72)' }}
/>
<span className={s.text}>
{I18n.t(
'variable_binding_there_are_no_variables_in_this_project',
{},
'该智能体下暂时没有定义变量',
)}
</span>
</div>
);
}

View File

@@ -0,0 +1,103 @@
/*
* 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 React from 'react';
import cls from 'classnames';
import { IntelligenceType } from '@coze-arch/idl/intelligence_api';
import { I18n } from '@coze-arch/i18n';
import {
IconCozArrowRight,
IconCozCheckMarkFill,
} from '@coze-arch/coze-design/icons';
import { Avatar, Tag, Typography } from '@coze-arch/coze-design';
import { useHover } from '@coze-arch/hooks';
import type { IBotSelectOption } from '@/components/bot-project-select/types';
interface OptionItemProps extends IBotSelectOption {
checked?: boolean;
disabled?: boolean;
}
export default function OptionItem({
disabled,
checked,
avatar,
name,
type,
}: OptionItemProps) {
const [ref, isHover] = useHover<HTMLDivElement>();
const renderOperate = () => {
if (isHover && !disabled) {
return (
<div className={'flex items-center coz-fg-secondary flex-shrink-0'}>
<span className={'text-[12px]'}>
{I18n.t('variable_binding_continue', {}, '继续')}
</span>
<IconCozArrowRight className="text-[12px] ml-2px" />
</div>
);
}
return type === IntelligenceType.Project ? (
<Tag size="mini" color="primary" className={'flex-shrink-0'}>
{I18n.t('wf_chatflow_106')}
</Tag>
) : (
<Tag size="mini" color="primary" className={'flex-shrink-0'}>
{I18n.t('wf_chatflow_107')}
</Tag>
);
};
return (
<div
ref={ref}
className={cls('flex w-full items-center pl-8px pr-8px pt-2px pb-2px')}
>
{checked ? (
<IconCozCheckMarkFill className="text-[16px] mr-8px coz-fg-hglt flex-shrink-0" />
) : (
<div className={'w-16px h-16px mr-8px flex-shrink-0'} />
)}
<Avatar
style={{ flexShrink: 0, marginRight: 8, width: 16, height: 16 }}
shape="square"
src={avatar}
/>
<div
className="flex"
style={{ flexGrow: 1, flexShrink: 1, overflow: 'hidden' }}
>
<Typography.Text
ellipsis={{ showTooltip: true }}
style={{
fontSize: 12,
color: '#1D1C23',
fontWeight: 400,
}}
>
{name}
</Typography.Text>
</div>
{renderOperate()}
</div>
);
}

View File

@@ -0,0 +1,176 @@
/*
* 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 React from 'react';
import cls from 'classnames';
import { useService } from '@flowgram-adapter/free-layout-editor';
import { GlobalVariableService } from '@coze-workflow/variable';
import { IntelligenceType } from '@coze-arch/idl/intelligence_api';
import { I18n } from '@coze-arch/i18n';
import { Tooltip } from '@coze-arch/coze-design';
import { useRelatedBotService } from '@/hooks';
import { type RelatedEntitiesProps } from '../types';
import s from '../index.module.less';
import { isItemDisabled } from '../../utils';
import type { IBotSelectOption, DisableExtraOptions } from '../../types';
import { RenderFootLoading } from '../../bots';
import OptionItem from './option-item';
import EmptyContent from './empty-content';
interface Options extends DisableExtraOptions {
onClick: () => void;
checkedValue?: string;
}
const renderCustomOption = (
item: IBotSelectOption | undefined,
extraOptions: Options,
) => {
if (!item) {
return null;
}
const {
disableBot,
disableProject,
disableBotTooltip,
disableProjectTooltip,
onClick,
checkedValue,
} = extraOptions;
const isBot = item.type === IntelligenceType.Bot;
const disabled = isItemDisabled({ disableBot, disableProject }, item.type);
const disabledTooltip =
isBot && disableBot ? disableBotTooltip : disableProjectTooltip;
const handleClick = () => {
if (disabled) {
return;
}
onClick?.();
};
return (
<div
onClick={handleClick}
className={cls(s['related-entities-option'], {
[s['related-entities-option-disabled']]: disabled,
[s['related-entities-option-selected']]: checkedValue === item.value,
})}
>
{disabled ? (
<Tooltip
keepDOM={true}
content={disabledTooltip}
position="left"
className={'w-full'}
>
<div className={'w-full'}>
<OptionItem
{...item}
disabled={disabled}
checked={checkedValue === item.value}
/>
</div>
</Tooltip>
) : (
<OptionItem
{...item}
disabled={disabled}
checked={checkedValue === item.value}
/>
)}
</div>
);
};
export default function Panel({
relatedEntities = [],
relatedEntityValue,
disableProjectTooltip,
disableProject,
disableBotTooltip,
disableBot,
isLoadMore,
onLoadMore,
onRelatedSelect,
relatedBotPanelStyle,
}: RelatedEntitiesProps) {
const relatedBotService = useRelatedBotService();
const globalVariableService = useService<GlobalVariableService>(
GlobalVariableService,
);
return (
<>
{relatedEntities && relatedEntities?.length > 0 ? (
<div
className={
'coz-fg-secondary mt-8px mb-4px pl-28px text-[12px] font-medium leading-16px'
}
>
{I18n.t(
'variable_binding_please_bind_an_agent_or_app_first',
{},
'请先绑定智能体或应用',
)}
</div>
) : null}
<div className={'h-[292px] overflow-y-auto'} style={relatedBotPanelStyle}>
{relatedEntities?.map(item =>
renderCustomOption(item, {
disableProjectTooltip,
disableProject,
disableBotTooltip,
disableBot,
onClick: () => {
relatedBotService.updateRelatedBot({
id: item.value,
type: item.type === IntelligenceType.Bot ? 'bot' : 'project',
});
globalVariableService.loadGlobalVariables(
item.type === 1 ? 'bot' : 'project',
item.value,
);
onRelatedSelect?.(item);
},
checkedValue: relatedEntityValue?.id,
}),
)}
{isLoadMore ? (
<div className={s['bot-foot-loading']}>
<RenderFootLoading onObserver={onLoadMore} />
</div>
) : null}
{!relatedEntities || relatedEntities?.length <= 0 ? (
<EmptyContent />
) : null}
</div>
</>
);
}

View File

@@ -0,0 +1,52 @@
/*
* 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 { useQuery } from '@tanstack/react-query';
import {
IntelligenceStatus,
IntelligenceType,
} from '@coze-arch/idl/intelligence_api';
import { intelligenceApi } from '@coze-arch/bot-api';
interface QueryProps {
spaceId: string;
}
export default function useQueryBotList({ spaceId }: QueryProps) {
const { data } = useQuery({
queryKey: ['related-bot-panel', 'GetDraftIntelligenceList', spaceId],
queryFn: async () => {
const res = await intelligenceApi.GetDraftIntelligenceList({
space_id: spaceId,
name: '',
types: [IntelligenceType.Bot, IntelligenceType.Project],
size: 30,
order_by: 0,
cursor_id: undefined,
status: [
IntelligenceStatus.Using,
IntelligenceStatus.Banned,
IntelligenceStatus.MoveFailed,
],
});
return res?.data ?? {};
},
retry: false,
});
return data;
}

View File

@@ -0,0 +1,132 @@
/*
* 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { debounce } from 'lodash-es';
import { PUBLIC_SPACE_ID } from '@coze-workflow/base';
import {
type DraftIntelligenceListData,
IntelligenceStatus,
IntelligenceType,
} from '@coze-arch/idl/intelligence_api';
import { intelligenceApi } from '@coze-arch/bot-api';
import { useGlobalState } from '@/hooks';
import { type RelatedEntitiesHookProps } from '../types';
import { useExtraBotOption } from '../../use-extra-bot-option';
import { type IBotSelectOption, type IBotSelectOptions } from '../../types';
import useQueryBotList from './use-query-bot-list';
export default function useRelated({
relatedEntityValue,
}: RelatedEntitiesHookProps) {
const [baseRelatedEntities, setBaseRelatedEntities] = useState<
IBotSelectOption[]
>([]);
const [nextCursorId, setNextCursorId] = useState<string | undefined>();
const [search, setSearch] = useState<string>('');
const [isLoadMore, setIsLoadMore] = useState<boolean>(false);
const isLoadMoreDate = useRef(false);
const { spaceId, personalSpaceId } = useGlobalState();
const querySpaceId = spaceId === PUBLIC_SPACE_ID ? personalSpaceId : spaceId;
const defaultBotData = useQueryBotList({
spaceId: querySpaceId,
});
const fetchCallback = (
fetchBotData?: DraftIntelligenceListData,
isReset = false,
) => {
const { intelligences, total = 0, next_cursor_id } = fetchBotData ?? {};
const list: IBotSelectOptions = (intelligences ?? []).map(it => ({
name: it.basic_info?.name ?? '',
value: it.basic_info?.id ?? '',
avatar: it.basic_info?.icon_url ?? '',
type: it.type || IntelligenceType.Bot,
}));
const totalList = isReset ? list : [...baseRelatedEntities, ...list];
setNextCursorId(next_cursor_id);
setBaseRelatedEntities(totalList);
setIsLoadMore(totalList.length < total);
};
const fetchBotList = async (query?: string, isReset = false) => {
const res = await intelligenceApi.GetDraftIntelligenceList({
space_id: querySpaceId,
name: query ?? search,
types: [IntelligenceType.Bot, IntelligenceType.Project],
size: 30,
order_by: 0,
cursor_id: nextCursorId,
status: [
IntelligenceStatus.Using,
IntelligenceStatus.Banned,
IntelligenceStatus.MoveFailed,
],
});
fetchCallback(res?.data, isReset);
};
const onRelatedEntitiesSearch = useCallback((query: string) => {
setSearch(query);
setNextCursorId(undefined);
fetchBotList(query, true);
}, []);
const loadMore = async () => {
if (isLoadMoreDate.current) {
return;
}
isLoadMoreDate.current = true;
await fetchBotList();
isLoadMoreDate.current = false;
};
useEffect(() => {
fetchCallback(defaultBotData, true);
}, [defaultBotData]);
const isBot = relatedEntityValue?.type === IntelligenceType.Bot;
// 由于分页限制 选中的 botId 可能找不到对应的 option 需要额外添加
const extraBotOption = useExtraBotOption(
baseRelatedEntities,
relatedEntityValue?.id,
isBot,
);
const relatedEntities = useMemo<IBotSelectOption[]>(
() => [extraBotOption, ...baseRelatedEntities].filter(e => !!e),
[extraBotOption, baseRelatedEntities],
);
return {
relatedEntities,
onRelatedEntitiesSearch: debounce(onRelatedEntitiesSearch, 300),
loadMoreRelatedEntities: loadMore,
isLoadMore,
};
}

View File

@@ -0,0 +1,174 @@
/*
* 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 React, { useCallback, useRef, useState } from 'react';
import cls from 'classnames';
import { IntelligenceType } from '@coze-arch/idl/intelligence_api';
import { I18n } from '@coze-arch/i18n';
import { IconCozMagnifier } from '@coze-arch/coze-design/icons';
import { Avatar, Select } from '@coze-arch/coze-design';
import { type Select as SemiSelect } from '@coze-arch/bot-semi';
import { useRelatedBotService } from '@/hooks';
import VariablePanel from './variable-panel/variable-panel';
import { type BotProjectVariableSelectProps, type RelatedValue } from './types';
import useRelated from './related-bot-panel/use-related';
import RelatedBotPanel from './related-bot-panel/panel';
const formatRelatedBotValue = (value?: {
id: string;
type: 'bot' | 'project';
}): RelatedValue | undefined => {
if (!value) {
return value;
}
return {
id: value.id,
type:
value.type === 'bot' ? IntelligenceType.Bot : IntelligenceType.Project,
};
};
export default function BotProjectVariableSelect({
className,
variablesFormatter,
relatedEntityValue: relatedEntityValueFromProps,
disableBot,
disableProject,
disableBotTooltip,
disableProjectTooltip,
onVariableSelect,
variableValue,
variablePanelStyle,
relatedBotPanelStyle,
customVariablePanel,
}: BotProjectVariableSelectProps) {
const selectRef = useRef<SemiSelect | null>(null);
const relatedBotService = useRelatedBotService();
const getRelatedEntityValue = () =>
relatedEntityValueFromProps ||
formatRelatedBotValue(relatedBotService.getRelatedBotValue());
const relatedEntityValue = getRelatedEntityValue();
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const [showBotPanel, setShowBotPanel] = useState(!relatedEntityValue?.id);
const {
relatedEntities,
onRelatedEntitiesSearch,
isLoadMore,
loadMoreRelatedEntities,
} = useRelated({
relatedEntityValue,
});
const handleFocus = useCallback(() => {
setTimeout(() => {
setShowBotPanel(true);
}, 100);
}, []);
const handleBlur = useCallback(() => {
selectRef.current?.clearInput?.();
selectRef.current?.close?.();
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
setShowBotPanel(!getRelatedEntityValue()?.id);
}, 300);
}, []);
return (
<div className={cls(className, 'w-full flex flex-col p-4px')}>
<Select
autoClearSearchValue={true}
ref={selectRef}
filter
inputProps={{
onBlur: handleBlur,
onFocusCapture: handleFocus,
}}
value={relatedEntityValue?.id}
className={'w-full'}
size={'small'}
placeholder={I18n.t(
'variable_binding_search_project',
{},
'搜索智能体/应用',
)}
optionList={[]}
onSearch={onRelatedEntitiesSearch}
emptyContent={null}
prefix={
<IconCozMagnifier className={'text-[16px] ml-8px coz-fg-secondary'} />
}
showArrow={false}
renderSelectedItem={() => {
const item = relatedEntities.find(
e => e.value === relatedEntityValue?.id,
);
if (item) {
return (
<div className={'flex items-center'}>
<Avatar
className={'w-16px h-16px mr-8px'}
shape="square"
src={item.avatar}
/>
<span className={'text-[12px]'}>{item.name}</span>
</div>
);
}
return null;
}}
/>
<div className={'w-full coz-fg-primary'}>
{showBotPanel ? (
<RelatedBotPanel
relatedBotPanelStyle={relatedBotPanelStyle}
relatedEntityValue={relatedEntityValue}
relatedEntities={relatedEntities}
onLoadMore={loadMoreRelatedEntities}
isLoadMore={isLoadMore}
disableBot={disableBot}
disableProject={disableProject}
disableBotTooltip={disableBotTooltip}
disableProjectTooltip={disableProjectTooltip}
onRelatedSelect={() => {
setShowBotPanel(false);
}}
/>
) : (
customVariablePanel || (
<VariablePanel
variablePanelStyle={variablePanelStyle}
variableValue={variableValue}
onVariableSelect={onVariableSelect}
variablesFormatter={variablesFormatter}
/>
)
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,70 @@
/*
* 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 { type CSSProperties, type ReactNode } from 'react';
import { type IntelligenceType } from '@coze-arch/idl/intelligence_api';
import { type VariableMetaWithNode } from '@/form-extensions/typings';
import type {
DisableExtraOptions,
IBotSelectOption,
} from '@/components/bot-project-select/types';
export interface Variable extends VariableMetaWithNode {
disabled?: boolean;
value?: string;
}
export interface RelatedVariablesHookProps {
variablesFormatter?: (variables: Variable[]) => Variable[];
}
export interface RelatedEntitiesHookProps {
relatedEntityValue?: RelatedValue;
}
export interface RelatedValue {
id: string;
type: IntelligenceType;
}
export interface RelatedEntitiesProps extends DisableExtraOptions {
onLoadMore: () => Promise<void>;
isLoadMore: boolean;
relatedEntities?: IBotSelectOption[];
relatedEntityValue?: RelatedValue;
onRelatedSelect?: (item: IBotSelectOption) => void;
relatedBotPanelStyle?: CSSProperties;
}
export interface VariablesPanelProps {
onVariableSelect?: (value?: string) => void;
variableValue?: string;
variablePanelStyle?: CSSProperties;
variablesFormatter?: (variables: Variable[]) => Variable[];
}
export interface BotProjectVariableSelectProps extends DisableExtraOptions {
className?: string;
onVariableSelect?: (value?: string) => void;
variablesFormatter?: (variables: Variable[]) => Variable[];
relatedEntityValue?: RelatedValue;
variableValue?: string;
variablePanelStyle?: CSSProperties;
relatedBotPanelStyle?: CSSProperties;
customVariablePanel?: ReactNode;
}

View File

@@ -0,0 +1,43 @@
/*
* 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 { useMemo } from 'react';
import { isGlobalVariableKey } from '@coze-workflow/variable';
import { useNodeAvailableVariablesWithNode } from '@/form-extensions/hooks';
import { type RelatedVariablesHookProps } from '../types';
export default function useRelatedVariable({
variablesFormatter = v => v,
}: RelatedVariablesHookProps) {
const availableVariables = useNodeAvailableVariablesWithNode();
const globalVariables = useMemo(
() =>
variablesFormatter(
availableVariables.filter(
item => item.nodeId && isGlobalVariableKey(item.nodeId),
),
),
[availableVariables, variablesFormatter],
);
return {
globalVariables,
};
}

View File

@@ -0,0 +1,140 @@
/*
* 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 React, { useMemo } from 'react';
import cls from 'classnames';
import { useGlobalVariableServiceState } from '@coze-workflow/variable';
import { VARIABLE_TYPE_ALIAS_MAP } from '@coze-workflow/base';
import { I18n } from '@coze-arch/i18n';
import { IconCozEmpty } from '@coze-arch/coze-design/icons';
import { Select, Tag, Typography } from '@coze-arch/coze-design';
import { type Variable, type VariablesPanelProps } from '../types';
import styles from '../index.module.less';
import useRelatedVariable from './use-related-variable';
interface OptionProps extends Variable {
checked?: boolean;
onSelect?: (v?: string) => void;
}
const OptionItem = (option: OptionProps) => (
<Select.Option
selected={option.checked}
key={`${option.value}-${option.disabled}`}
value={option.value}
disabled={option.disabled}
className={styles['variable-panel-option']}
onSelect={v => option.onSelect?.(v?.value)}
>
<div
style={{
maxWidth: '100%',
}}
className={
'flex items-center justify-between pl-32px pr-8px pt-2px pb-2px'
}
>
<Typography.Text
className={cls('flex-1 leading-20px', {
[styles['variable-option-checked']]: option.checked,
})}
disabled={option.disabled}
ellipsis={{ showTooltip: true }}
style={{
fontSize: 12,
marginRight: 4,
}}
>
{option.name}
</Typography.Text>
<Tag disabled={option.disabled} size="mini" color="primary">
{VARIABLE_TYPE_ALIAS_MAP[option.type]}
</Tag>
</div>
</Select.Option>
);
interface EmptyProps {
className?: string;
}
export const EmptyVariableContent = ({ className }: EmptyProps) => {
const { type } = useGlobalVariableServiceState();
const isSelectedBotOrProject = Boolean(type);
return useMemo(() => {
const getEmptyMsg = () => {
if (isSelectedBotOrProject) {
return I18n.t(
'variable_binding_there_are_no_variables_in_this_project',
);
}
return I18n.t('variable_select_empty_library_tips');
};
return (
<div className={cls(className, styles['empty-block'])}>
<IconCozEmpty
style={{ fontSize: '32px', color: 'rgba(52, 60, 87, 0.72)' }}
/>
<span className={styles.text}>{getEmptyMsg()}</span>
</div>
);
}, [isSelectedBotOrProject]);
};
export default function VariablePanel({
onVariableSelect,
variableValue,
variablePanelStyle,
variablesFormatter,
}: VariablesPanelProps) {
const { globalVariables } = useRelatedVariable({ variablesFormatter });
return (
<>
{globalVariables.length > 0 && (
<div
className={
'coz-fg-secondary mt-8px mb-4px pl-28px text-[12px] font-medium leading-16px'
}
>
{I18n.t(
'variable_binding_please_select_a_variable',
{},
'请先选择变量',
)}
</div>
)}
<div className={'h-[292px] overflow-y-auto'} style={variablePanelStyle}>
{globalVariables.map(e => (
<OptionItem
{...e}
onSelect={onVariableSelect}
checked={variableValue === e.value}
/>
))}
{globalVariables.length <= 0 && <EmptyVariableContent />}
</div>
</>
);
}

View File

@@ -0,0 +1,65 @@
.select-wrapper {
position: relative;
:global {
// 修复bot-select在画布中因为缩放导致尺寸不正常
.semi-portal-inner {
width: 100%;
}
}
}
.dropdown {
width: 100%;
min-height: 50px;
:global {
.semi-select-option-list {
&::-webkit-scrollbar {
height: 0;
min-height: 42px;
background: transparent;
}
.semi-select-loading-wrapper {
min-height: 40px;
text-align: center;
}
.semi-select-option-selected {
.semi-icon-tick {
color: var(--light-usage-primary-color-primary, #4d53e8);
}
}
}
}
}
.bot-foot-loading {
display: flex;
align-items: center;
justify-content: center;
color: #4D53E8;
background-color: white;
}
.bot-option {
display: flex;
padding-top: 10px;
padding-bottom: 10px;
padding-left: 8px;
}
.bot-option-disabled {
cursor: not-allowed;
opacity: 0.5;
}
.loading-tag {
display: flex;
align-items: end;
font-size: 12px;
}

View File

@@ -0,0 +1,362 @@
/*
* 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 React, { useEffect, useState, useRef, useMemo } from 'react';
import { debounce } from 'lodash-es';
import classNames from 'classnames';
import { useService } from '@flowgram-adapter/free-layout-editor';
import { IconSearch } from '@douyinfe/semi-icons';
import { PUBLIC_SPACE_ID } from '@coze-workflow/base/constants';
import { concatTestId } from '@coze-workflow/base';
import {
IntelligenceStatus,
IntelligenceType,
} from '@coze-arch/idl/intelligence_api';
import { I18n } from '@coze-arch/i18n';
import { Typography, Spin, Avatar, Select } from '@coze-arch/bot-semi';
import { intelligenceApi } from '@coze-arch/bot-api';
import { Tag, Tooltip } from '@coze-arch/coze-design';
import { ChatflowService } from '@/services';
import { useGlobalState, useRelatedBotService } from '../../hooks';
import { isItemDisabled } from './utils';
import { useExtraBotOption } from './use-extra-bot-option';
import type {
IBotSelectOption,
IBotSelectOptions,
ValueType,
DisableExtraOptions,
} from './types';
import styles from './bots.module.less';
const RenderCustomOption = (
item: IBotSelectOption | undefined,
extraOptions: DisableExtraOptions,
) => {
if (!item) {
return null;
}
const {
disableBot,
disableProject,
disableBotTooltip,
disableProjectTooltip,
} = extraOptions;
const isBot = item.type === IntelligenceType.Bot;
const disabled = isItemDisabled({ disableBot, disableProject }, item.type);
const disabledTooltip =
isBot && disableBot ? disableBotTooltip : disableProjectTooltip;
const renderOptionItem = optionItem => (
<div className="flex" style={{ width: '100%', alignItems: 'center' }}>
<Avatar
size="extra-extra-small"
style={{ flexShrink: 0, marginRight: 8 }}
shape="square"
src={optionItem.avatar}
/>
<div className="flex" style={{ flexGrow: 1, flexShrink: 1, width: 0 }}>
<Typography.Text
ellipsis={{ showTooltip: true }}
style={{
fontSize: 12,
color: '#1D1C23',
fontWeight: 400,
}}
>
{optionItem.name}
</Typography.Text>
</div>
{optionItem.type === IntelligenceType.Project ? (
<Tag size="mini" color="primary">
{I18n.t('wf_chatflow_106')}
</Tag>
) : (
<Tag size="mini" color="primary">
{I18n.t('wf_chatflow_107')}
</Tag>
)}
</div>
);
return (
<Select.Option
data-testid={concatTestId(
'workflow',
'playground',
'testrun',
'bot-select',
'option',
item.value,
)}
value={item.value}
showTick={true}
key={item.value}
disabled={disabled}
className={classNames(
styles['bot-option'],
disabled ? styles['bot-option-disabled'] : '',
)}
>
{disabled ? (
<Tooltip content={disabledTooltip} position="left">
{renderOptionItem(item)}
</Tooltip>
) : (
renderOptionItem(item)
)}
</Select.Option>
);
};
export const RenderFootLoading = ({
onObserver,
}: {
onObserver: () => Promise<void>;
}) => {
const indicatorRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const callback = entries => {
if (entries[0].isIntersecting) {
onObserver?.();
}
};
const loadingObserver = new IntersectionObserver(callback);
indicatorRef.current && loadingObserver.observe(indicatorRef.current);
return () => loadingObserver.disconnect();
}, []);
return (
<div className={styles['loading-tag']} ref={indicatorRef}>
<Spin style={{ marginRight: 10 }} size="small" />
<span>{I18n.t('workflow_add_common_loading')}</span>
</div>
);
};
interface BotsProps {
isBot: boolean;
value?: ValueType;
onChange?: (value?: ValueType) => void;
}
export const Bots: React.FC<BotsProps & DisableExtraOptions> = ({
isBot,
value,
onChange,
disableBot = false,
disableProject = false,
disableBotTooltip = '',
disableProjectTooltip = '',
...props
}) => {
const idValue = value?.id;
const globalState = useGlobalState();
const DebounceTime = 500;
const chatflowService = useService<ChatflowService>(ChatflowService);
const relatedBotService = useRelatedBotService();
const isLoadMoreDate = useRef(false);
const [selectList = [], setSelectList] = useState<IBotSelectOptions>([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isShowFoot, setIsShowFoot] = useState<boolean>(false);
const [search, setSearch] = useState<string>('');
const [searchTotal, setTotal] = useState(0);
const containerRef = useRef<HTMLDivElement>(null);
const nextCursorRef = useRef<string | undefined>();
const useNewGlobalVariableCache = !globalState.isInIDE;
const handleChange = (botInfo?: IBotSelectOption, _value?: ValueType) => {
chatflowService.setSelectItem(botInfo);
onChange?.(_value);
};
// 由于分页限制 选中的 botId 可能找不到对应的 option 需要额外添加
const extraBotOption = useExtraBotOption(
selectList,
idValue,
isBot,
handleChange,
);
// 接口得到的总数并非真实的总数,前端可能会拼接 options
const listMaxHeight = useMemo(() => {
const realTotal = extraBotOption ? searchTotal + 1 : searchTotal;
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
return realTotal < 7 ? realTotal * 32 : 208;
}, [searchTotal, extraBotOption]);
useEffect(() => {
fetchBotList();
}, []);
useEffect(() => {
const findItem = selectList?.find(item => item.value === value?.id);
const disabled = isItemDisabled(
{ disableBot, disableProject },
findItem?.type,
);
// 禁用状态下清空选中值
if (value && findItem?.type && disabled) {
onChange?.(undefined);
}
if (value?.id !== chatflowService.selectItem?.value) {
if (!value) {
chatflowService.setSelectItem(undefined);
return;
}
if (findItem) {
chatflowService.setSelectItem(findItem);
}
}
}, [value, selectList]);
const fetchBotList = async (query?: string, isReset = false) => {
if (query) {
setIsLoading(true);
}
if (isReset) {
// 如果是重新搜索,需要清空上一次的游标
nextCursorRef.current = undefined;
}
// project 内部使用新接口查询列表
const res = await intelligenceApi.GetDraftIntelligenceList({
space_id:
globalState.spaceId === PUBLIC_SPACE_ID
? globalState.personalSpaceId
: globalState.spaceId,
name: query ?? search,
types: [IntelligenceType.Bot, IntelligenceType.Project],
size: 30,
order_by: 0,
cursor_id: nextCursorRef.current,
status: [
IntelligenceStatus.Using,
IntelligenceStatus.Banned,
IntelligenceStatus.MoveFailed,
],
});
const { intelligences, total = 0, next_cursor_id } = res?.data ?? {};
const list: IBotSelectOptions = (intelligences ?? []).map(it => ({
name: it.basic_info?.name ?? '',
value: it.basic_info?.id ?? '',
avatar: it.basic_info?.icon_url ?? '',
type: it.type || IntelligenceType.Bot,
}));
const totalList = isReset ? list : [...selectList, ...list];
setTotal(total);
nextCursorRef.current = next_cursor_id;
setSelectList(totalList);
setIsShowFoot(totalList.length < total);
setIsLoading(false);
};
const loadMoreData = async () => {
if (isLoadMoreDate.current) {
return;
}
isLoadMoreDate.current = true;
await fetchBotList();
isLoadMoreDate.current = false;
};
const handleSearch = query => {
setSearch(query);
fetchBotList(query, true);
};
return (
<div className={styles['select-wrapper']} ref={containerRef}>
<Select
value={idValue}
data-testid={concatTestId(
'workflow',
'playground',
'testerun',
'bot-select',
)}
dropdownClassName={styles.dropdown}
filter
remote
placeholder={I18n.t('wf_chatflow_73')}
emptyContent={I18n.t('agentflow_addbot_select_empty_no_bot')}
onSearch={debounce(handleSearch, DebounceTime)}
prefix={<IconSearch />}
loading={isLoading}
style={{ width: '100%' }}
virtualize={{
height: listMaxHeight,
width: '100%',
itemSize: 32,
}}
onChange={newValue => {
// 设置选中项类型bot / project
const findItem = selectList.find(item => item.value === newValue);
if (useNewGlobalVariableCache && findItem?.type) {
relatedBotService.updateRelatedBot({
id: newValue as string,
type: findItem?.type === IntelligenceType.Bot ? 'bot' : 'project',
});
}
handleChange(
findItem,
findItem
? {
id: newValue as string,
type: findItem.type,
}
: undefined,
);
}}
{...props}
>
{[extraBotOption, ...selectList]
.filter(item => item)
.map(item =>
RenderCustomOption(item, {
disableBot,
disableProject,
disableBotTooltip,
disableProjectTooltip,
}),
)}
{isShowFoot ? (
<Select.Option
value={new Date().getTime()}
key={new Date().getTime()}
className={styles['bot-foot-loading']}
disabled
>
<RenderFootLoading onObserver={loadMoreData} />
</Select.Option>
) : null}
</Select>
</div>
);
};

View File

@@ -0,0 +1,31 @@
.json-viewer {
max-height: unset;
padding: 0 6px;
background-color: unset;
border: unset;
:global {
// .flow-test-run-line {
// width: 38px;
// // &::before {}
// &::after {
// width: 30px;
// border-bottom-left-radius: 2px;
// }
// }
.field-icon {
color: var(--Light-usage-text---color-text-1, rgba(29, 28, 35, 80%));
}
.field-key {
color: var(--Light-usage-text---color-text-1, rgba(28, 31, 35, 80%));
}
.field-value {
color: var(--Light-usage-text---color-text-1, rgba(28, 31, 35, 80%));
}
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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 { type FC } from 'react';
import { JsonViewer } from '@coze-common/json-viewer';
import styles from './chat-history.module.less';
interface Props {
data: object | null;
}
export const ChatHistory: FC<Props> = ({ data }) => (
<JsonViewer data={data} className={styles['json-viewer']} />
);

View File

@@ -0,0 +1,6 @@
.container {
margin-top: 16px;
padding: 12px;
background: var(--Light-color-grey---grey-1, #F0F0F5);
border-radius: 8px;
}

View File

@@ -0,0 +1,216 @@
/*
* 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 complexity */
import React from 'react';
import { useMount } from 'ahooks';
import { IntelligenceType } from '@coze-arch/idl/intelligence_api';
import { I18n } from '@coze-arch/i18n';
import { withField } from '@coze-arch/bot-semi';
import { Variables } from './variables';
import { useVariables } from './use-variables';
import { useTableInfo } from './use-table-info';
import { useProjectVariables } from './use-project-variables';
import { useLTMInfo } from './use-ltm-info';
import { useChatHistory } from './use-chat-history';
import { type ValueType } from './types';
import { TableInfo } from './table-info';
import { Item } from './item';
import { ChatHistory } from './chat-history';
import { Bots } from './bots';
import styles from './index.module.less';
interface BotSelectProps {
value?: ValueType;
onChange?: (value?: ValueType) => void;
hideLabel?: boolean;
hideVariblesForce?: boolean;
hasVariableNode?: boolean;
hasVariableAssignNode?: boolean;
hasDatabaseNode?: boolean;
hasLTMNode?: boolean;
hasChatHistoryEnabledLLM?: boolean;
disableBot?: boolean;
disableBotTooltip?: string;
disableProject?: boolean;
disableProjectTooltip?: string;
}
/**
* copy from bot-select
*/
export const BotProjectSelect: React.FC<BotSelectProps> = ({
value: originValue,
onChange,
hideLabel = false,
hideVariblesForce = false,
hasVariableNode = false,
hasVariableAssignNode = false,
hasDatabaseNode = false,
hasChatHistoryEnabledLLM = false,
hasLTMNode = false,
...props
}) => {
let value = originValue;
// 兼容历史数据
if (typeof originValue === 'string') {
value = {
id: originValue,
type: IntelligenceType.Bot,
};
}
const valueId = value?.id;
const isBot = value?.type === IntelligenceType.Bot;
const { tableInfo, isLoading: isTableInfoLoading } = useTableInfo(
isBot ? valueId : undefined,
);
const { variables, isLoading: isVariablesLoading } = useVariables(
isBot ? valueId : undefined,
);
const { variables: projectVariables, isLoading: isProjectVariablesLoading } =
useProjectVariables(!isBot ? valueId : undefined);
const {
chatHistory,
// conversationId,
// sectionId,
} = useChatHistory(isBot ? valueId : undefined);
const { ltmEnabled, isLoading: isLTMInfoLoading } = useLTMInfo(
isBot ? valueId : undefined,
);
const botSelected = !!valueId;
const hasVariables = variables && variables.length > 0;
const hasTableInfo = tableInfo && tableInfo.length > 0;
const hasProjectVariables = projectVariables && projectVariables?.length > 0;
const hasChatHistory = !!chatHistory;
const showTableInfo = botSelected && !isTableInfoLoading && hasDatabaseNode;
const showVariables =
botSelected &&
!isVariablesLoading &&
(hasVariableNode || hasVariableAssignNode) &&
!hideVariblesForce;
// 试运行都是临时搞了一个会话,这里把 bot 聊天历史展示可能会误导,先隐藏
const showChatHistory = false;
// const showChatHistory =
// botSelected && !isChatHistoryLoading && hasChatHistoryEnabledLLM;
const showLTMInfo = botSelected && hasLTMNode && !isLTMInfoLoading;
const showProjectVariables =
botSelected &&
(hasVariableNode || hasVariableAssignNode) &&
!isProjectVariablesLoading &&
!isBot;
useMount(() => {
const sourceBotId = new URLSearchParams(window.location.search).get(
'bot_id',
);
if (!valueId && sourceBotId) {
onChange?.({
id: sourceBotId,
type: IntelligenceType.Bot,
});
}
});
return (
<>
<Item hideLabel={hideLabel} label={I18n.t('workflow_240218_02')}>
<Bots isBot={isBot} value={value} onChange={onChange} {...props} />
</Item>
{showProjectVariables ? (
<div className={styles.container}>
<Item
label={I18n.t('wf_chatflow_126')}
defaultText={I18n.t('wf_chatflow_127')}
>
{hasProjectVariables ? (
<Variables variables={projectVariables} />
) : null}
</Item>
</div>
) : null}
{isBot ? (
<div
className={styles.container}
style={{
display:
showVariables || showTableInfo || showChatHistory || showLTMInfo
? 'block'
: 'none',
}}
>
{showVariables ? (
<Item
label={I18n.t('workflow_detail_testrun_variable_node_field')}
defaultText={I18n.t(
'workflow_detail_testrun_variable_node_nofield',
)}
>
{hasVariables ? <Variables variables={variables} /> : null}
</Item>
) : null}
{showTableInfo ? (
<Item
label={I18n.t('workflow_240218_05')}
defaultText={I18n.t('workflow_240218_04')}
>
{hasTableInfo ? <TableInfo data={tableInfo} /> : null}
</Item>
) : null}
{showChatHistory ? (
<Item
label={I18n.t('workflow_chathistory_testrun_title')}
defaultText={I18n.t('workflow_chathistory_testrun_nocontent')}
>
{hasChatHistory ? <ChatHistory data={chatHistory} /> : null}
</Item>
) : null}
{showLTMInfo ? (
<Item label={I18n.t('ltm_240617_02')}>
<div className="text-[12px]">
{I18n.t('timecapsule_1228_001')}:{' '}
{ltmEnabled
? I18n.t('timecapsule_0124_001')
: I18n.t('timecapsule_0124_002')}
</div>
</Item>
) : null}
</div>
) : null}
</>
);
};
export const BotProjectSelectWithField = withField(BotProjectSelect, {
valueKey: 'value',
onKeyChangeFnName: 'onChange',
});
BotProjectSelectWithField.defaultProps = {
fieldStyle: { overflow: 'visible' },
};

View File

@@ -0,0 +1,24 @@
.container {
margin-top: 24px;
&:first-child {
margin-top: 0;
}
}
.label,
.default-text {
font-size: 12px;
font-weight: 400;
font-style: normal;
line-height: 16px;
}
.label {
margin-bottom: 8px;
color: var(--Light-color-grey---grey-3, #A7A7B0);
}
.default-text {
color: var(--Light-color-grey---grey-3, #A7A7B0);
}

View File

@@ -0,0 +1,46 @@
/*
* 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 React, { type PropsWithChildren } from 'react';
import styles from './item.module.less';
interface ItemProps {
label: string;
defaultText?: string;
hideLabel?: boolean;
}
export const Item: React.FC<PropsWithChildren<ItemProps>> = ({
children,
label,
defaultText,
hideLabel = false,
}) => {
const haveChildren = !!children;
const showDefaultText = !haveChildren && !!defaultText;
const showLabel = !hideLabel && !showDefaultText;
return (
<div className={styles.container}>
{showLabel ? <div className={styles.label}>{label}</div> : null}
{showDefaultText ? (
<div className={styles['default-text']}>{defaultText}</div>
) : null}
{children}
</div>
);
};

View File

@@ -0,0 +1,56 @@
// 修改后禁用 stylelint
/* stylelint-disable no-descending-specificity */
/* stylelint-disable declaration-no-important */
.table {
:global {
table {
border: 1px solid rgba(46, 46, 56, 8%);
border-radius: 8px;
thead {
th {
font-weight: 600 !important;
color: var(--Light-usage-text---color-text-1, rgba(29, 28, 35, 80%)) !important;
border-bottom: 1px solid rgba(46, 47, 56, 9%) !important;
}
}
th,
td {
overflow: hidden;
font-size: 12px;
font-weight: 600;
font-style: normal;
line-height: 16px;
color: var(--Light-usage-text---color-text-1, rgba(29, 28, 35, 80%));
text-overflow: ellipsis;
white-space: nowrap;
}
td {
border-bottom: 0 !important;
&:first-child {
width: 114px;
}
}
}
.semi-table-tbody>.semi-table-row>.semi-table-row-cell,
.semi-table-thead>.semi-table-row>.semi-table-row-head {
padding: 8px 0;
&:first-child {
padding-right: 20px;
padding-left: 20px;
}
&:last-child {
padding-right: 14px;
}
}
}
}

View File

@@ -0,0 +1,64 @@
/*
* 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 { I18n } from '@coze-arch/i18n';
import { Table } from '@coze-arch/bot-semi';
import { type BotTable } from '@coze-arch/bot-api/memory';
import { TagList } from '../tag-list';
import styles from './table-info.module.less';
interface TableInfoProps {
data?: BotTable[];
}
export const TableInfo: React.FC<TableInfoProps> = ({
data = [{ table_name: 'none' }],
}) => {
const columns = [
{
title: I18n.t('db_add_table_name'),
dataIndex: 'table_name',
render: (text: string) => <span>{text}</span>,
},
{
title: I18n.t('db_add_table_field_name'),
dataIndex: 'field_list',
render: (fieldList: BotTable['field_list']) => {
if (fieldList && fieldList.length > 0) {
return (
<TagList
tags={(fieldList ?? []).map(({ name }) => name || '')}
max={3}
/>
);
}
return 'none';
},
},
];
return (
<Table
className={styles.table}
columns={columns}
dataSource={data}
pagination={false}
/>
);
};

View File

@@ -0,0 +1,45 @@
/*
* 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.
*/
//后端无定义 根据 bot_info 中的 workflow_info.profile_memory 推导而来
import { type IntelligenceType } from '@coze-arch/idl/intelligence_api';
export interface Variable {
key: string;
description?: string;
default_value?: string;
}
export interface IBotSelectOption {
name: string;
avatar: string;
value: string;
type: IntelligenceType;
}
export interface ValueType {
id?: string;
type?: IntelligenceType;
}
export type IBotSelectOptions = IBotSelectOption[];
export interface DisableExtraOptions {
disableBot?: boolean;
disableProject?: boolean;
disableBotTooltip?: string;
disableProjectTooltip?: string;
}

View File

@@ -0,0 +1,71 @@
/*
* 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 { useQuery } from '@tanstack/react-query';
import { IntelligenceType } from '@coze-arch/idl/intelligence_api';
import {
type GetDraftBotInfoAgwData,
type ModelInfo,
} from '@coze-arch/bot-api/playground_api';
import { type BotTable } from '@coze-arch/bot-api/memory';
import { PlaygroundApi } from '@coze-arch/bot-api';
import { type IBotSelectOption } from './types';
export const useBotInfo = (botId?: string) => {
const { isLoading, data: botInfo } = useQuery({
queryKey: ['bot_info', botId || ''],
queryFn: async () => {
if (!botId) {
return undefined;
}
const { data } = await PlaygroundApi.GetDraftBotInfoAgw({
bot_id: botId,
});
return data;
},
});
return { isLoading, botInfo };
};
// 为 wf 使用 bot 信息做数据转换
export const transformBotInfo = {
// 模型数据
model: (data?: GetDraftBotInfoAgwData): ModelInfo =>
data?.bot_info?.model_info ?? {},
// 基本信息数据
basicInfo: (
botInfo?: GetDraftBotInfoAgwData,
): IBotSelectOption | undefined => {
if (!botInfo) {
return undefined;
}
return {
name: botInfo?.bot_info?.name ?? '',
avatar: botInfo?.bot_info?.icon_url ?? '',
value: botInfo?.bot_info?.bot_id ?? '',
type: IntelligenceType.Bot,
};
},
// 数据库信息
database: (botInfo?: GetDraftBotInfoAgwData): BotTable[] | undefined =>
botInfo?.bot_info?.database_list,
// 变量信息
variable: (botInfo?: GetDraftBotInfoAgwData) =>
botInfo?.bot_info?.variable_list,
};

View File

@@ -0,0 +1,100 @@
/*
* 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 { useQuery } from '@tanstack/react-query';
import { Scene } from '@coze-arch/bot-api/developer_api';
import { DeveloperApi } from '@coze-arch/bot-api';
import { transformBotInfo, useBotInfo } from './use-bot-info';
const MAX_ROUND_COUNT = 20;
const getMessageList = async ({
botId,
botCount,
}: {
botId: string;
botCount: number;
}) => {
const totalRound = Math.ceil(botCount / MAX_ROUND_COUNT);
let cursor = '0';
let round = 0;
let conversationId = '';
let sectionId = '';
let messageList: { role: string; content: string }[] = [];
while (round < totalRound) {
const res = await DeveloperApi.GetMessageList({
bot_id: botId,
draft_mode: true,
scene: Scene.Playground,
cursor,
count: Math.min(botCount - round * MAX_ROUND_COUNT, MAX_ROUND_COUNT),
});
messageList = [
...messageList,
...res.message_list
.filter(item => item.type === 'question' || item.type === 'answer')
.map(item => ({
role: item?.role as string,
content: item?.content as string,
})),
];
conversationId = res?.connector_conversation_id || '';
sectionId = res?.last_section_id || '';
cursor = res?.cursor;
round += 1;
if (!res.hasmore) {
break;
}
}
return { messageList, conversationId, sectionId };
};
export const useChatHistory = (botId?: string) => {
const { botInfo, isLoading: isBotInfoLoading } = useBotInfo(botId);
const botCount =
transformBotInfo.model(botInfo)?.short_memory_policy?.history_round ?? 0;
const { isLoading: isMessageLoading, data } = useQuery({
queryKey: ['bot_info', botId, botCount],
queryFn: () =>
getMessageList({
botId: botId as string,
botCount,
}),
enabled: botCount !== undefined,
});
const { messageList, conversationId, sectionId } = data || {};
return {
chatHistory: messageList?.length
? {
chatHistory: messageList,
}
: null,
isLoading: isBotInfoLoading || isMessageLoading,
conversationId,
sectionId,
};
};

View File

@@ -0,0 +1,79 @@
/*
* 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 { useMemo } from 'react';
import { IntelligenceType } from '@coze-arch/idl/intelligence_api';
import { useProjectItemInfo } from './use-project-info';
import { transformBotInfo, useBotInfo } from './use-bot-info';
import type { IBotSelectOption, ValueType } from './types';
export const useExtraBotOption = (
botOptionList: IBotSelectOption[],
currentBotValue?: string,
isBot?: boolean,
handleChange?: (botInfo?: IBotSelectOption, _value?: ValueType) => void,
// eslint-disable-next-line max-params
): IBotSelectOption | undefined => {
const { botInfo } = useBotInfo(isBot ? currentBotValue : undefined);
const { projectItemInfo } = useProjectItemInfo(
!isBot ? currentBotValue : undefined,
);
const botValue = useMemo(() => {
const botFinded = botOptionList.find(
({ value }) => value === currentBotValue,
);
if (!botFinded) {
const botItem = transformBotInfo.basicInfo(botInfo);
if (botItem) {
handleChange?.(botItem, {
id: botItem.value,
type: botItem.type,
});
}
return botItem;
}
return undefined;
}, [botOptionList, botInfo, currentBotValue]);
const projectValue = useMemo(() => {
const projectFinded = botOptionList.find(
({ value }) => value === currentBotValue,
);
if (projectFinded) {
return undefined;
}
let projectItem;
if (projectItemInfo) {
projectItem = {
name: projectItemInfo?.basic_info?.name || '',
value: projectItemInfo?.basic_info?.id || '',
avatar: projectItemInfo?.basic_info?.icon_url || '',
type: IntelligenceType.Project,
};
handleChange?.(projectItem, {
id: projectItem.value,
type: projectItem.type,
});
}
return projectItem;
}, [projectItemInfo, botOptionList, currentBotValue]);
return isBot ? botValue : projectValue;
};

View File

@@ -0,0 +1,35 @@
/*
* 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 get from 'lodash-es/get';
import { TimeCapsuleMode } from '@coze-arch/idl/playground_api';
import { useBotInfo } from './use-bot-info';
export const useLTMInfo = (botId?: string) => {
const { isLoading, botInfo } = useBotInfo(botId);
const timeCapsuleMode = get(
botInfo,
['bot_info', 'bot_tag_info', 'time_capsule_info', 'time_capsule_mode'],
TimeCapsuleMode.Off,
);
return {
// 是否开启长期记忆
ltmEnabled: timeCapsuleMode === TimeCapsuleMode.On,
isLoading,
};
};

View File

@@ -0,0 +1,61 @@
/*
* 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 { useQuery } from '@tanstack/react-query';
import { IntelligenceType } from '@coze-arch/idl/intelligence_api';
import { intelligenceApi, MemoryApi } from '@coze-arch/bot-api';
export const useProjectInfo = (projectId?: string) => {
const { isLoading, data: variableList } = useQuery({
queryKey: ['project_info', projectId || ''],
queryFn: async () => {
if (!projectId) {
return undefined;
}
const { VariableList } = await MemoryApi.GetProjectVariableList({
ProjectID: projectId,
});
return (
VariableList?.filter?.(v => v.Enable)?.map(variable => ({
key: variable.Keyword,
})) || []
);
},
});
return { isLoading, variableList };
};
export const useProjectItemInfo = (projectId?: string) => {
const { isLoading, data: projectItemInfo } = useQuery({
queryKey: ['project_item_info', projectId || ''],
queryFn: async () => {
if (!projectId) {
return undefined;
}
const { data } = await intelligenceApi.GetDraftIntelligenceInfo({
intelligence_id: projectId,
intelligence_type: IntelligenceType.Project,
});
return data;
},
});
return { isLoading, projectItemInfo };
};

View File

@@ -0,0 +1,26 @@
/*
* 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 { useProjectInfo } from './use-project-info';
export const useProjectVariables = (projectID?: string) => {
const { variableList, isLoading } = useProjectInfo(projectID);
return {
variables: variableList,
isLoading,
};
};

View File

@@ -0,0 +1,53 @@
/*
* 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 { type BotTable, BotTableRWMode } from '@coze-arch/bot-api/memory';
import { transformBotInfo, useBotInfo } from './use-bot-info';
// 多人模式下产品希望前端展示uuid & id 目前这两个字段会被后端过滤 先由前端补充这两个字段 后端充分评估过再移除过滤逻辑
function addUidAndIdToBotFieldsIfIsUnlimitedReadWriteMode(
tableInfo: BotTable[],
): BotTable[] {
tableInfo.forEach(bot => {
if (
bot.rw_mode === BotTableRWMode.UnlimitedReadWrite &&
(bot?.field_list?.length as number) > 0
) {
['id', 'uuid'].forEach(name => {
const fieldExisted = !!bot.field_list?.find(
field => field.name === name,
);
if (!fieldExisted) {
bot.field_list?.unshift({ name });
}
});
}
});
return tableInfo;
}
export const useTableInfo = (botID?: string) => {
const { isLoading, botInfo } = useBotInfo(botID);
let tableInfo: BotTable[] | undefined;
tableInfo = transformBotInfo.database(botInfo);
if (tableInfo) {
tableInfo = addUidAndIdToBotFieldsIfIsUnlimitedReadWriteMode(tableInfo);
}
return { tableInfo, isLoading };
};

View File

@@ -0,0 +1,29 @@
/*
* 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 { type Variable } from '@coze-arch/bot-api/playground_api';
import { transformBotInfo, useBotInfo } from './use-bot-info';
export const useVariables = (botID?: string) => {
const { botInfo, isLoading } = useBotInfo(botID);
const variables: Variable[] | undefined = transformBotInfo.variable(botInfo);
return {
variables,
isLoading,
};
};

View File

@@ -0,0 +1,28 @@
/*
* 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 { IntelligenceType } from '@coze-arch/idl/intelligence_api';
export const isItemDisabled = (
{ disableBot, disableProject },
type?: IntelligenceType,
) => {
const isBot = type === IntelligenceType.Bot;
const isProject = type === IntelligenceType.Project;
const disabled = (isBot && disableBot) || (isProject && disableProject);
return disabled || !type;
};

View File

@@ -0,0 +1,29 @@
/*
* 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 { type Variable } from '@coze-arch/bot-api/playground_api';
import { TagList } from '../tag-list';
interface VariablesProps {
variables: Variable[];
}
export const Variables: React.FC<VariablesProps> = ({ variables }) => {
const tagList = variables.map(({ key }) => key ?? '');
return <TagList tags={tagList} max={5} />;
};