Merge pull request #585 from SuanmoSuanyangTechnology/feature/app_features_zy

feat(web): app support features
This commit is contained in:
yingzhao
2026-03-17 15:56:19 +08:00
committed by GitHub
26 changed files with 1106 additions and 1146 deletions

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-06 21:11:51 * @Date: 2026-02-06 21:11:51
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-13 17:11:14 * @Last Modified time: 2026-03-16 18:06:00
*/ */
import { type FC, useRef, useState } from 'react' import { type FC, useRef, useState } from 'react'
import RecordRTC from 'recordrtc' import RecordRTC from 'recordrtc'
@@ -19,13 +19,15 @@ interface AudioRecorderProps {
action?: string; action?: string;
/** Additional config passed to the upload request */ /** Additional config passed to the upload request */
requestConfig?: Record<string, any>; requestConfig?: Record<string, any>;
disabled?: boolean;
} }
const AudioRecorder: FC<AudioRecorderProps> = ({ const AudioRecorder: FC<AudioRecorderProps> = ({
onRecordingComplete, onRecordingComplete,
className = '', className = '',
action = fileUploadUrlWithoutApiPrefix, action = fileUploadUrlWithoutApiPrefix,
requestConfig = {} requestConfig = {},
disabled = false
}) => { }) => {
// Whether the recorder is currently capturing audio // Whether the recorder is currently capturing audio
const [isRecording, setIsRecording] = useState(false) const [isRecording, setIsRecording] = useState(false)
@@ -34,6 +36,7 @@ const AudioRecorder: FC<AudioRecorderProps> = ({
/** Request microphone access and start recording */ /** Request microphone access and start recording */
const startRecording = async () => { const startRecording = async () => {
if (disabled) return
try { try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true }) const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
recorderRef.current = new RecordRTC(stream, { recorderRef.current = new RecordRTC(stream, {
@@ -49,6 +52,7 @@ const AudioRecorder: FC<AudioRecorderProps> = ({
/** Stop recording, upload the audio blob, then invoke the completion callback */ /** Stop recording, upload the audio blob, then invoke the completion callback */
const stopRecording = () => { const stopRecording = () => {
if (disabled) return
if (recorderRef.current) { if (recorderRef.current) {
recorderRef.current.stopRecording(() => { recorderRef.current.stopRecording(() => {
const blob = recorderRef.current!.getBlob() const blob = recorderRef.current!.getBlob()
@@ -76,7 +80,7 @@ const AudioRecorder: FC<AudioRecorderProps> = ({
// swap background image to reflect current state // swap background image to reflect current state
return ( return (
<div <div
className={`rb:size-5.5 rb:cursor-pointer rb:bg-cover ${className} ${ className={`rb:size-5.5 rb:bg-cover ${disabled ? 'rb:opacity-65 rb:cursor-not-allowed' : 'rb:cursor-pointer'} ${className} ${
isRecording isRecording
? `rb:bg-[url('@/assets/images/conversation/audio_ing.gif')]` ? `rb:bg-[url('@/assets/images/conversation/audio_ing.gif')]`
: `rb:bg-[url('@/assets/images/conversation/audio.svg')]` : `rb:bg-[url('@/assets/images/conversation/audio.svg')]`

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-02 15:01:59 * @Date: 2026-02-02 15:01:59
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-12 14:59:38 * @Last Modified time: 2026-03-17 15:35:34
*/ */
/** /**
@@ -63,9 +63,9 @@ const ButtonCheckbox: FC<ButtonCheckboxProps> = ({
align="center" align="center"
justify={cicle ? 'center' : 'start'} justify={cicle ? 'center' : 'start'}
gap={4} gap={4}
className={clsx("rb:flex rb:items-center rb:cursor-pointer rb:border rb:hover:bg-[#F6F6F6]", { className={clsx("rb:flex rb:items-center rb:cursor-pointer rb:px-2! rb:border rb:hover:bg-[#F6F6F6]", {
'rb:size-7 rb:rounded-[14px] rb:border-[0.5px] rb:border-[#EBEBEB]': cicle, 'rb:size-7 rb:rounded-[14px] rb:border-[0.5px] rb:border-[#EBEBEB]': cicle,
'rb:rounded-lg rb:px-2 rb:text-[12px] rb:h-6': !cicle, 'rb:rounded-lg rb:text-[12px] rb:h-6': !cicle,
// Checked state: blue background and border // Checked state: blue background and border
"rb:bg-[rgba(21,94,239,0.06)] rb:border-[rgba(21,94,239,0.25)] rb:hover:bg-[rgba(21,94,239,0.06)] rb:text-[#155EEF]": checked, "rb:bg-[rgba(21,94,239,0.06)] rb:border-[rgba(21,94,239,0.25)] rb:hover:bg-[rgba(21,94,239,0.06)] rb:text-[#155EEF]": checked,
// Unchecked state: gray border and dark text // Unchecked state: gray border and dark text

View File

@@ -2,13 +2,14 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2025-12-10 16:46:17 * @Date: 2025-12-10 16:46:17
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-02-06 21:05:52 * @Last Modified time: 2026-03-17 14:11:24
*/ */
import { type FC, useRef, useEffect } from 'react' import { type FC, useRef, useEffect, useState } from 'react'
import clsx from 'clsx' import clsx from 'clsx'
import Markdown from '@/components/Markdown' import Markdown from '@/components/Markdown'
import type { ChatContentProps } from './types' import type { ChatContentProps } from './types'
import { Spin } from 'antd' import { Spin, Divider, Space } from 'antd'
import { SoundOutlined } from '@ant-design/icons'
/** /**
* Chat Content Display Component * Chat Content Display Component
@@ -28,7 +29,25 @@ const ChatContent: FC<ChatContentProps> = ({
// Scroll container reference for controlling auto-scroll to bottom // Scroll container reference for controlling auto-scroll to bottom
const scrollContainerRef = useRef<(HTMLDivElement | null)>(null) const scrollContainerRef = useRef<(HTMLDivElement | null)>(null)
const prevDataLengthRef = useRef(data.length); const prevDataLengthRef = useRef(data.length);
const isScrolledToBottomRef = useRef(true); // Track if user is scrolled to bottom const isScrolledToBottomRef = useRef(true);
const audioRef = useRef<HTMLAudioElement | null>(null)
const [playingIndex, setPlayingIndex] = useState<number | null>(null)
const handlePlay = (index: number, audioUrl: string) => {
if (playingIndex === index) {
audioRef.current?.pause()
setPlayingIndex(null)
return
}
if (audioRef.current) {
audioRef.current.pause()
}
const audio = new Audio(audioUrl)
audioRef.current = audio
audio.play()
setPlayingIndex(index)
audio.onended = () => setPlayingIndex(null)
}
// Track scroll position to determine if user is at bottom // Track scroll position to determine if user is at bottom
useEffect(() => { useEffect(() => {
@@ -101,6 +120,19 @@ const ChatContent: FC<ChatContentProps> = ({
{item.subContent && renderRuntime && renderRuntime(item, index)} {item.subContent && renderRuntime && renderRuntime(item, index)}
{/* Render message content using Markdown component */} {/* Render message content using Markdown component */}
<Markdown content={renderRuntime ? item.content ?? '' : item.content ?? errorDesc ?? ''} /> <Markdown content={renderRuntime ? item.content ?? '' : item.content ?? errorDesc ?? ''} />
{item.audioUrl && <>
<Divider className="rb:my-3!" />
<Space size={12} className="rb:pb-2 rb:pl-1">
{playingIndex !== index
? <SoundOutlined className="rb:cursor-pointer rb:hover:text-[#155EEF]! rb:size-5.5" onClick={() => handlePlay(index, item.audioUrl!)} />
: <div
className="rb:size-5.5 rb:cursor-pointer rb:bg-cover rb:bg-[url('@/assets/images/conversation/audio_ing.gif')]"
onClick={() => handlePlay(index, item.audioUrl!)}
/>
}
</Space>
</>}
</div> </div>
{/* Bottom label (such as timestamp, username, etc.) */} {/* Bottom label (such as timestamp, username, etc.) */}
{labelPosition === 'bottom' && {labelPosition === 'bottom' &&

View File

@@ -0,0 +1,205 @@
/*
* @Author: ZhaoYing
* @Date: 2026-03-17 14:22:25
* @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-17 14:22:25
*/
// Toolbar component for chat input area, supporting file upload, audio recording, and variable configuration
import { useRef, forwardRef, useImperativeHandle, type ReactNode, useEffect } from 'react'
import { Flex, Dropdown, Divider, App, Form, type MenuProps } from 'antd'
import { SettingOutlined } from '@ant-design/icons'
import { useTranslation } from 'react-i18next'
import clsx from 'clsx'
import AudioRecorder from '@/components/AudioRecorder'
import UploadFiles from '@/views/Conversation/components/FileUpload'
import UploadFileListModal from '@/views/Conversation/components/UploadFileListModal'
import VariableConfigModal from '@/views/Workflow/components/Chat/VariableConfigModal'
import type { FeaturesConfigForm } from '@/views/ApplicationConfig/types'
import type { UploadFileListModalRef } from '@/views/Conversation/types'
import type { VariableConfigModalRef } from '@/views/Workflow/types'
import type { Variable } from '@/views/Workflow/components/Properties/VariableList/types'
// Exposed methods via ref for parent components to access/set form state
export interface ChatToolbarRef {
getFiles: () => any[]
getVariables: () => Variable[]
setFiles: (files: any[]) => void
setVariables: (variables: Variable[]) => void
}
// Props for configuring toolbar features, upload settings, and event callbacks
export interface ChatToolbarProps {
features: FeaturesConfigForm
extra?: ReactNode
uploadAction?: string
uploadRequestConfig?: {
data?: Record<string, string | number | boolean>
headers?: Record<string, string>
}
onFilesChange?: (files: any[]) => void
onVariablesChange?: (variables: Variable[]) => void
onRecordingComplete?: (file: any) => void;
defaultValue?: { memory: boolean }
}
interface FormValues {
files: any[]
variables: Variable[];
memory?: boolean;
}
const ChatToolbar = forwardRef<ChatToolbarRef, ChatToolbarProps>(({
features,
extra,
uploadAction,
uploadRequestConfig,
onFilesChange,
onVariablesChange,
onRecordingComplete,
defaultValue,
}, ref) => {
const { t } = useTranslation()
const { message: messageApi } = App.useApp()
const uploadFileListModalRef = useRef<UploadFileListModalRef>(null)
const variableConfigModalRef = useRef<VariableConfigModalRef>(null)
const [form] = Form.useForm<FormValues>()
const queryValues = Form.useWatch([], form)
useEffect(() => {
if (!defaultValue) return
form.setFieldsValue(defaultValue)
}, [defaultValue])
useImperativeHandle(ref, () => ({
getFiles: () => form.getFieldValue('files') || [],
getVariables: () => form.getFieldValue('variables') || [],
setFiles: (files) => form.setFieldValue('files', files),
setVariables: (variables) => {
console.log('variables', variables)
form.setFieldValue('variables', variables)
},
}))
const { file_upload } = features || {}
// Append newly uploaded file to the file list when upload is complete
const fileChange = (file?: any) => {
if (file?.status !== 'done') return
const files = [...(queryValues?.files || []), file]
form.setFieldValue('files', files)
onFilesChange?.(files)
}
// Append recorded audio file to the file list and notify parent
const handleRecordingComplete = (file: any) => {
const files = [...(queryValues?.files || []), file]
form.setFieldValue('files', files)
onFilesChange?.(files)
onRecordingComplete?.(file)
}
// Merge a batch of files (e.g. from remote URL modal) into the file list
const addFileList = (list?: any[]) => {
if (!list?.length) return
const files = [...(queryValues?.files || []), ...list]
form.setFieldValue('files', files)
onFilesChange?.(files)
}
// Persist variable values from the config modal and notify parent
const handleVariablesSave = (values: Variable[]) => {
form.setFieldValue('variables', values)
onVariablesChange?.(values)
}
// True when any required variable is missing a value, used to highlight the config button
const isNeedVariableConfig = queryValues?.variables?.some(
vo => vo.required && (vo.value === null || vo.value === undefined || vo.value === '')
)
// Build dropdown menu items based on allowed transfer methods
const fileMenus: MenuProps['items'] = []
if (file_upload?.allowed_transfer_methods?.includes('remote_url')) {
fileMenus.push({
key: 'url',
label: t('memoryConversation.addRemoteFile'),
onClick: () => {
if ((queryValues?.files?.length || 0) >= file_upload.max_file_count) {
messageApi.warning(t('common.fileNumTip', { num: file_upload.max_file_count }))
return
}
uploadFileListModalRef.current?.handleOpen()
}
})
}
const enabledTypes = ['image', 'document', 'video', 'audio'].filter(
type => file_upload?.[`${type}_enabled` as keyof FeaturesConfigForm['file_upload']]
)
if (file_upload?.allowed_transfer_methods?.includes('local_file') && enabledTypes.length > 0) {
fileMenus.push({
key: 'upload',
label: (
<UploadFiles
action={uploadAction}
onChange={fileChange}
requestConfig={uploadRequestConfig}
featureConfig={file_upload}
disabled={(queryValues?.files?.length || 0) >= file_upload.max_file_count}
/>
)
})
}
console.log('queryValues', queryValues)
return (
<Form form={form} initialValues={{ files: [], variables: [] }}>
<Flex justify="space-between" className="rb:flex-1">
<Flex gap={8} align="center">
<Form.Item name="files" noStyle hidden={!file_upload?.enabled}>
<Dropdown menu={{ items: fileMenus }}>
<div className="rb:size-6 rb:cursor-pointer rb:bg-cover rb:bg-[url('@/assets/images/conversation/link.svg')] rb:hover:bg-[url('@/assets/images/conversation/link_hover.svg')]" />
</Dropdown>
</Form.Item>
{extra}
<Form.Item name="variables" className="rb:mb-0!" hidden={queryValues?.variables?.length < 1}>
<div
className={clsx('rb:flex rb:items-center rb:border rb:rounded-lg rb:px-2 rb:text-[12px] rb:h-6 rb:cursor-pointer rb:hover:bg-[#F0F3F8] rb:text-[#212332]', {
'rb:border-[#FF5D34] rb:text-[#FF5D34]': isNeedVariableConfig,
'rb:border-[#DFE4ED]': !isNeedVariableConfig,
})}
onClick={() => variableConfigModalRef.current?.handleOpen(queryValues.variables)}
>
<SettingOutlined className="rb:mr-1" />
{t('memoryConversation.variableConfig')}
</div>
</Form.Item>
</Flex>
{file_upload?.audio_enabled && file_upload?.allowed_transfer_methods?.includes('local_file') && (
<Flex align="center">
<AudioRecorder
disabled={(queryValues?.files?.length || 0) >= file_upload.max_file_count}
action={uploadAction}
requestConfig={uploadRequestConfig}
onRecordingComplete={handleRecordingComplete}
/>
<Divider type="vertical" className="rb:ml-1.5! rb:mr-3!" />
</Flex>
)}
</Flex>
<UploadFileListModal
ref={uploadFileListModalRef}
refresh={addFileList}
featureConfig={file_upload}
/>
<VariableConfigModal
ref={variableConfigModalRef}
refresh={handleVariablesSave}
/>
</Form>
)
})
export default ChatToolbar

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2025-12-10 16:45:54 * @Date: 2025-12-10 16:45:54
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-12 13:57:51 * @Last Modified time: 2026-03-17 13:46:24
*/ */
import { type ReactNode } from 'react' import { type ReactNode } from 'react'
@@ -24,6 +24,7 @@ export interface ChatItem {
subContent?: Record<string, any>[]; subContent?: Record<string, any>[];
files?: any[]; files?: any[];
error?: string; error?: string;
audioUrl?: string;
} }
/** /**

View File

@@ -449,6 +449,7 @@ export const en = {
fileSizeTip: 'File size cannot exceed {{size}}MB', fileSizeTip: 'File size cannot exceed {{size}}MB',
fileAcceptTip: 'Unsupported file type:', fileAcceptTip: 'Unsupported file type:',
fileNumTip: 'File count cannot exceed {{num}}',
nextStep: 'Next Step', nextStep: 'Next Step',
prevStep: 'Previous Step', prevStep: 'Previous Step',
exportSuccess: 'Export successful', exportSuccess: 'Export successful',
@@ -1373,9 +1374,9 @@ export const en = {
dify: 'Dify', dify: 'Dify',
pleaseUploadFile: 'Please upload file', pleaseUploadFile: 'Please upload file',
setting: 'Settings', setting: 'Settings',
funConfig: 'Features', features: 'Conversation Features',
fileUpload: 'File Upload', file_upload: 'File Upload',
fileUploadDesc: 'The chat input box supports file uploads. Types include images, documents, and other types', file_upload_desc: 'The chat input box supports file uploads. Types include images, documents, and other types',
settings: 'File Upload Settings', settings: 'File Upload Settings',
uploadType: 'Upload Type', uploadType: 'Upload Type',
local: 'Local Upload', local: 'Local Upload',
@@ -1392,8 +1393,8 @@ export const en = {
maxCount: 'Max Files', maxCount: 'Max Files',
singleMaxSize: 'Max Size', singleMaxSize: 'Max Size',
unix: 'items', unix: 'items',
textTranfer: 'Text to Speech', text_to_speech: 'Text to Speech',
textTranferDesc: 'Text can be converted to speech', text_to_speech_desc: 'Text can be converted to speech',
apps: 'My Apps', apps: 'My Apps',
sharing: 'Sharing', sharing: 'Sharing',
@@ -1779,6 +1780,8 @@ Memory Bear: After the rebellion, regional warlordism intensified for several re
fileUrl: 'File URL', fileUrl: 'File URL',
addRemoteFile: 'Add Remote File', addRemoteFile: 'Add Remote File',
variableConfig: 'Variable Configuration', variableConfig: 'Variable Configuration',
memoryCancelTipTitle: 'Are you sure you want to disable conversation memory? Conversations will no longer be saved to the memory store.',
memoryTipTitle: 'Are you sure you want to enable conversation memory? Conversations will be saved to the memory store.',
}, },
login: { login: {
title: 'Red Bear Memory Science', title: 'Red Bear Memory Science',

View File

@@ -756,9 +756,9 @@ export const zh = {
dify: 'Dify', dify: 'Dify',
pleaseUploadFile: '请上传文件', pleaseUploadFile: '请上传文件',
setting: '设置', setting: '设置',
funConfig: '功能', features: '对话功能',
fileUpload: '文件上传', file_upload: '文件上传',
fileUploadDesc: '聊天输入框支持上传文件。类型包括图片、文档以及其它类型', file_upload_desc: '聊天输入框支持上传文件。类型包括图片、文档以及其它类型',
settings: '文件上传设置', settings: '文件上传设置',
uploadType: '上传类型', uploadType: '上传类型',
local: '本地上传', local: '本地上传',
@@ -775,8 +775,8 @@ export const zh = {
maxCount: '最大文件数', maxCount: '最大文件数',
singleMaxSize: '单文件最大大小', singleMaxSize: '单文件最大大小',
unix: '个', unix: '个',
textTranfer: '文字转语音', text_to_speech: '文字转语音',
textTranferDesc: '文本可以转换成语言', text_to_speech_desc: '文本可以转换成语言',
apps: '我的应用', apps: '我的应用',
sharing: '共享', sharing: '共享',
@@ -1082,6 +1082,7 @@ export const zh = {
fileSizeTip: '文件大小不能超过 {{size}}MB', fileSizeTip: '文件大小不能超过 {{size}}MB',
fileAcceptTip: '不支持的文件类型:', fileAcceptTip: '不支持的文件类型:',
fileNumTip: '文件数量不能超过{{num}}个',
nextStep: '下一步', nextStep: '下一步',
prevStep: '上一步', prevStep: '上一步',
exportSuccess: '导出成功', exportSuccess: '导出成功',
@@ -1775,6 +1776,8 @@ export const zh = {
fileUrl: '文件链接', fileUrl: '文件链接',
addRemoteFile: '添加远程文件', addRemoteFile: '添加远程文件',
variableConfig: '变量配置', variableConfig: '变量配置',
memoryCancelTipTitle: '确定关闭对话记忆功能吗?关闭后对话将不会保存到记忆库中',
memoryTipTitle: '确定打开对话记忆功能吗?打开后对话将会保存到记忆库中',
}, },
login: { login: {
title: '红熊记忆科学', title: '红熊记忆科学',

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-03 16:29:21 * @Date: 2026-02-03 16:29:21
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-13 16:58:15 * @Last Modified time: 2026-03-17 14:24:29
*/ */
import { type FC, type ReactNode, useEffect, useRef, useState, forwardRef, useImperativeHandle } from 'react'; import { type FC, type ReactNode, useEffect, useRef, useState, forwardRef, useImperativeHandle } from 'react';
import clsx from 'clsx' import clsx from 'clsx'
@@ -24,7 +24,7 @@ import type {
AiPromptModalRef, AiPromptModalRef,
Source, Source,
ChatVariableConfigModalRef, ChatVariableConfigModalRef,
FunConfigForm FeaturesConfigForm
} from './types' } from './types'
import type { Variable } from './components/VariableList/types' import type { Variable } from './components/VariableList/types'
import type { KnowledgeConfig } from './components/Knowledge/types' import type { KnowledgeConfig } from './components/Knowledge/types'
@@ -42,7 +42,7 @@ import ToolList from './components/ToolList/ToolList'
import SkillList from './components/Skill' import SkillList from './components/Skill'
import ChatVariableConfigModal from './components/ChatVariableConfigModal'; import ChatVariableConfigModal from './components/ChatVariableConfigModal';
import type { Skill } from '@/views/Skills/types' import type { Skill } from '@/views/Skills/types'
import FunConfig from './components/FunConfig' import FeaturesConfig from './components/FeaturesConfig'
/** /**
* Description wrapper component * Description wrapper component
@@ -356,7 +356,7 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
handleSave, handleSave,
funConfig: values?.funConfig features: values?.features
})) }))
const aiPromptModalRef = useRef<AiPromptModalRef>(null) const aiPromptModalRef = useRef<AiPromptModalRef>(null)
@@ -411,8 +411,8 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
setChatVariables(values?.variables || []) setChatVariables(values?.variables || [])
}, [values?.variables]) }, [values?.variables])
const handleSaveFunConfig = (value: FunConfigForm) => { const handleSaveFeaturesConfig = (value: FeaturesConfigForm) => {
form.setFieldValue('funConfig', value) form.setFieldValue('features', value)
} }
console.log('agent', values) console.log('agent', values)
return ( return (
@@ -426,7 +426,7 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
{defaultModel?.name ? <div className="rb:w-4 rb:h-4 rb:bg-[url('@/assets/images/application/model.svg')] rb:group-hover:bg-[url('@/assets/images/application/model_hover.svg')]"></div> : null} {defaultModel?.name ? <div className="rb:w-4 rb:h-4 rb:bg-[url('@/assets/images/application/model.svg')] rb:group-hover:bg-[url('@/assets/images/application/model_hover.svg')]"></div> : null}
{defaultModel?.name || t('application.chooseModel')} {defaultModel?.name || t('application.chooseModel')}
</Button> </Button>
{/* <FunConfig value={values?.funConfig as FunConfigForm} refresh={handleSaveFunConfig} /> */} <FeaturesConfig value={values?.features as FeaturesConfigForm} refresh={handleSaveFeaturesConfig} />
<Button type="primary" onClick={() => handleSave()}> <Button type="primary" onClick={() => handleSave()}>
{t('common.save')} {t('common.save')}
</Button> </Button>
@@ -435,7 +435,7 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
<Form form={form}> <Form form={form}>
<Form.Item name="default_model_config_id" hidden noStyle></Form.Item> <Form.Item name="default_model_config_id" hidden noStyle></Form.Item>
<Form.Item name="model_parameters" hidden noStyle></Form.Item> <Form.Item name="model_parameters" hidden noStyle></Form.Item>
<Form.Item name="funConfig" hidden noStyle></Form.Item> <Form.Item name="features" hidden noStyle></Form.Item>
<Space size={16} direction="vertical" style={{ width: '100%' }}> <Space size={16} direction="vertical" style={{ width: '100%' }}>
<Card title={t('application.promptConfiguration')}> <Card title={t('application.promptConfiguration')}>
<div className="rb:flex rb:items-center rb:justify-between rb:mb-2.75"> <div className="rb:flex rb:items-center rb:justify-between rb:mb-2.75">
@@ -512,7 +512,7 @@ const Agent = forwardRef<AgentRef>((_props, ref) => {
</div> </div>
<RbCard height="calc(100vh - 160px)" bodyClassName="rb:p-[0]! rb:h-full rb:overflow-hidden"> <RbCard height="calc(100vh - 160px)" bodyClassName="rb:p-[0]! rb:h-full rb:overflow-hidden">
<Chat <Chat
data={data as Config} data={values as Config}
chatList={chatList} chatList={chatList}
updateChatList={setChatList} updateChatList={setChatList}
handleSave={handleSave} handleSave={handleSave}

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-03 16:29:33 * @Date: 2026-02-03 16:29:33
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-05 13:47:23 * @Last Modified time: 2026-03-17 14:48:57
*/ */
import { useEffect, useState, useRef, forwardRef, useImperativeHandle } from 'react' import { useEffect, useState, useRef, forwardRef, useImperativeHandle } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
@@ -19,7 +19,8 @@ import type {
ChatData, ChatData,
SubAgentItem, SubAgentItem,
ClusterRef, ClusterRef,
ModelConfigModalRef ModelConfigModalRef,
FeaturesConfigForm
} from './types' } from './types'
import Chat from './components/Chat' import Chat from './components/Chat'
import RbCard from '@/components/RbCard/Card' import RbCard from '@/components/RbCard/Card'
@@ -29,7 +30,7 @@ import RadioGroupCard from '@/components/RadioGroupCard'
import { getModelListUrl } from '@/api/models' import { getModelListUrl } from '@/api/models'
import ModelConfigModal from './components/ModelConfigModal' import ModelConfigModal from './components/ModelConfigModal'
import type { Application } from '@/views/ApplicationManagement/types' import type { Application } from '@/views/ApplicationManagement/types'
import FeaturesConfig from './components/FeaturesConfig'
const tagColors = ['processing', 'warning', 'default'] const tagColors = ['processing', 'warning', 'default']
const MAX_LENGTH = 5; const MAX_LENGTH = 5;
@@ -166,7 +167,7 @@ const Cluster = forwardRef<ClusterRef>((_props, ref) => {
} }
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
handleSave, handleSave,
funConfig: data?.funConfig features: data?.features
})) }))
const modelConfigModalRef = useRef<ModelConfigModalRef>(null) const modelConfigModalRef = useRef<ModelConfigModalRef>(null)
@@ -185,16 +186,21 @@ const Cluster = forwardRef<ClusterRef>((_props, ref) => {
model_parameters: values model_parameters: values
}) })
} }
const handleSaveFeaturesConfig = (value: FeaturesConfigForm) => {
form.setFieldValue('features', value)
}
return ( return (
<Row className="rb:h-[calc(100vh-64px)]"> <Row className="rb:h-[calc(100vh-64px)]">
<Col span={12} className="rb:h-full rb:overflow-x-auto rb:border-r rb:border-[#DFE4ED] rb:p-[20px_16px_24px_16px]"> <Col span={12} className="rb:h-full rb:overflow-x-auto rb:border-r rb:border-[#DFE4ED] rb:p-[20px_16px_24px_16px]">
<div className="rb:flex rb:items-center rb:justify-end rb:mb-5"> <Flex gap={10} justify="end" align="center" className="rb:mb-5!">
<FeaturesConfig value={values?.features as FeaturesConfigForm} refresh={handleSaveFeaturesConfig} />
<Button type="primary" onClick={() => handleSave()}> <Button type="primary" onClick={() => handleSave()}>
{t('common.save')} {t('common.save')}
</Button> </Button>
</div> </Flex>
<Form form={form} layout="vertical"> <Form form={form} layout="vertical">
<Form.Item name="features" hidden noStyle></Form.Item>
<Space size={20} direction="vertical" style={{width: '100%'}}> <Space size={20} direction="vertical" style={{width: '100%'}}>
<Card title={t('application.collaboration')}> <Card title={t('application.collaboration')}>
<Form.Item <Form.Item

View File

@@ -1,36 +1,25 @@
import { type FC, useState, useRef, useEffect, useMemo } from 'react' import { type FC, useState, useRef, useEffect } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { App, Flex, Dropdown, type MenuProps, Divider, Form, Space } from 'antd' import { App } from 'antd'
import { SettingOutlined } from '@ant-design/icons'
import clsx from 'clsx' import clsx from 'clsx'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import ChatIcon from '@/assets/images/application/chat.png' import ChatIcon from '@/assets/images/application/chat.png'
import { draftRun } from '@/api/application'
import VariableConfigModal from '@/views/Workflow/components/Chat/VariableConfigModal'
import { draftRun } from '@/api/application';
import Empty from '@/components/Empty' import Empty from '@/components/Empty'
import Chat from '@/components/Chat' import Chat from '@/components/Chat'
import AudioRecorder from '@/components/AudioRecorder'
import RbCard from '@/components/RbCard/Card' import RbCard from '@/components/RbCard/Card'
import UploadFiles from '@/views/Conversation/components/FileUpload' import ChatToolbar, { type ChatToolbarRef } from '@/components/Chat/ChatToolbar'
import UploadFileListModal from '@/views/Conversation/components/UploadFileListModal' import Runtime from '@/views/Workflow/components/Chat/Runtime'
import Runtime from '@/views/Workflow/components/Chat/Runtime';
import { nodeLibrary } from '@/views/Workflow/constant' import { nodeLibrary } from '@/views/Workflow/constant'
// import ButtonCheckbox from '@/components/ButtonCheckbox';
// import MemoryFunctionIcon from '@/assets/images/conversation/memoryFunction.svg'
// import OnlineIcon from '@/assets/images/conversation/online.svg'
// import OnlineCheckedIcon from '@/assets/images/conversation/onlineChecked.svg'
// import MemoryFunctionCheckedIcon from '@/assets/images/conversation/memoryFunctionChecked.svg'
import type { ChatItem } from '@/components/Chat/types' import type { ChatItem } from '@/components/Chat/types'
import type { VariableConfigModalRef, WorkflowConfig } from '@/views/Workflow/types' import type { WorkflowConfig } from '@/views/Workflow/types'
import type { Variable } from '@/views/Workflow/components/Properties/VariableList/types' import type { Variable } from '@/views/Workflow/components/Properties/VariableList/types'
import type { TestChatProps } from './type'; import type { TestChatProps } from './type'
import type { UploadFileListModalRef } from '@/views/Conversation/types'
import type { SSEMessage } from '@/utils/stream' import type { SSEMessage } from '@/utils/stream'
import type { FeaturesConfigForm } from '@/views/ApplicationConfig/types'
const formatParams = (message: string, conversation_id: string | null, files: any[] = [], variables: Record<string, any>) => { const formatParams = (message: string, conversation_id: string | null, files: any[] = [], variables: Record<string, any>) => {
return { return {
@@ -65,29 +54,25 @@ interface NodeData {
elapsed_time?: string; elapsed_time?: string;
error?: any; error?: any;
state: Record<string, any>; state: Record<string, any>;
status?: 'completed' | 'failed' status?: 'completed' | 'failed';
audio_url?: string;
} }
interface FormData {
files: any[];
variables: Variable[]
}
const TestChat: FC<TestChatProps> = ({ const TestChat: FC<TestChatProps> = ({
application, application,
config config
}) => { }) => {
const { t } = useTranslation() const { t } = useTranslation()
const { message: messageApi } = App.useApp() const { message: messageApi } = App.useApp()
const variableConfigModalRef = useRef<VariableConfigModalRef>(null) const toolbarRef = useRef<ChatToolbarRef>(null)
const uploadFileListModalRef = useRef<UploadFileListModalRef>(null)
const [loading, setLoading] = useState(false) // Send button loading state const [loading, setLoading] = useState(false)
const [chatList, setChatList] = useState<ChatItem[]>([]) // Chat message history const [chatList, setChatList] = useState<ChatItem[]>([])
const [streamLoading, setStreamLoading] = useState(false) // SSE streaming state const [streamLoading, setStreamLoading] = useState(false)
const [conversationId, setConversationId] = useState<string | null>(null) // Current conversation ID const [conversationId, setConversationId] = useState<string | null>(null)
const [message, setMessage] = useState<string | undefined>(undefined) // Current input message const [message, setMessage] = useState<string | undefined>(undefined)
const [form] = Form.useForm<FormData>() const [fileList, setFileList] = useState<any[]>([])
const queryValues = Form.useWatch([], form) const [features, setFeatures] = useState<FeaturesConfigForm>({} as FeaturesConfigForm)
useEffect(() => { useEffect(() => {
getVariables() getVariables()
@@ -96,6 +81,8 @@ const TestChat: FC<TestChatProps> = ({
const getVariables = () => { const getVariables = () => {
if (!application || !config) return if (!application || !config) return
setFeatures(config?.features || {} as FeaturesConfigForm)
let initVariables: Variable[] = [] let initVariables: Variable[] = []
switch (application.type) { switch (application.type) {
@@ -104,85 +91,35 @@ const TestChat: FC<TestChatProps> = ({
const startNodes = nodes.filter(vo => vo.type === 'start') const startNodes = nodes.filter(vo => vo.type === 'start')
if (startNodes.length) { if (startNodes.length) {
const curVariables = startNodes[0].config.variables as Variable[] const curVariables = startNodes[0].config.variables as Variable[]
curVariables.forEach((vo) => {
curVariables.forEach((vo) => { if (typeof vo.default !== 'undefined') {
if (typeof vo.default !== 'undefined') { vo.value = vo.default
vo.value = vo.default }
} const lastVo = curVariables.find(item => item.name === vo.name)
const lastVo = curVariables.find(item => item.name === vo.name) if (lastVo?.value) {
if (lastVo?.value) { vo.value = lastVo.value
vo.value = lastVo.value }
} })
}) initVariables = curVariables
initVariables = curVariables }
}
break break
case 'agent': case 'agent':
initVariables = config.variables as Variable[] initVariables = config.variables as Variable[]
break break
} }
form.setFieldValue('variables', [...initVariables]) toolbarRef.current?.setVariables([...initVariables])
} }
/**
* Opens the variable configuration modal
*/
const handleEditVariables = () => {
variableConfigModalRef.current?.handleOpen(queryValues.variables)
}
/**
* Saves updated variable values from the modal
*/
const handleSave = (values: Variable[]) => {
form.setFieldValue('variables', [...values])
}
/**
* Handles file upload from local device
*/
const fileChange = (file?: any) => {
form.setFieldValue('files', [...(queryValues.files || []), file])
}
const handleRecordingComplete = async (file: any) => {
form.setFieldValue('files', [...(queryValues.files || []), file])
}
/**
* Handles dropdown menu actions for file upload
*/
const handleShowUpload: MenuProps['onClick'] = ({ key }) => {
switch(key) {
case 'define':
uploadFileListModalRef.current?.handleOpen()
break
}
}
/**
* Adds files from remote URL modal
*/
const addFileList = (list?: any[]) => {
if (!list || list.length <= 0) return
form.setFieldValue('files', [...(queryValues.files || []), ...(list || [])])
}
/**
* Updates the entire file list (used when removing files)
*/
const updateFileList = (list?: any[]) => {
form.setFieldValue('files', [...list || []])
}
const isNeedVariableConfig = useMemo(() => {
return queryValues?.variables.some(vo => vo.required && (vo.value === null || vo.value === undefined || vo.value === ''))
}, [queryValues?.variables])
const addUserMessage = (message: string, files: any[]) => { const addUserMessage = (message: string, files: any[]) => {
const newUserMessage: ChatItem = { setChatList(prev => [...prev, {
role: 'user', role: 'user',
content: message, content: message,
created_at: Date.now(), created_at: Date.now(),
files files
}; }])
setChatList(prev => [...prev, newUserMessage])
} }
const addAssistantMessage = () => { const addAssistantMessage = () => {
const { type } = application || {} const { type } = application || {}
setChatList(prev => [...prev, { setChatList(prev => [...prev, {
@@ -193,20 +130,22 @@ const TestChat: FC<TestChatProps> = ({
}]) }])
} }
const updateAssistantMessage = (content: string) => { const updateAssistantMessage = (content: string, audio_url?: string) => {
setChatList(prev => { setChatList(prev => {
let newList = [...prev] const newList = [...prev]
const lastMsg = newList[newList.length - 1] const lastMsg = newList[newList.length - 1]
if (lastMsg.role === 'assistant') { if (lastMsg.role === 'assistant') {
lastMsg.content += content lastMsg.content += content;
lastMsg.audioUrl = audio_url
} }
return newList return newList
}) })
} }
const updateErrorAssistantMessage = (message_length: number) => { const updateErrorAssistantMessage = (message_length: number) => {
if (message_length > 0) return if (message_length > 0) return
setChatList(prev => { setChatList(prev => {
let newList = [...prev] const newList = [...prev]
const lastMsg = newList[newList.length - 1] const lastMsg = newList[newList.length - 1]
if (lastMsg.role === 'assistant') { if (lastMsg.role === 'assistant') {
lastMsg.content = null lastMsg.content = null
@@ -214,34 +153,37 @@ const TestChat: FC<TestChatProps> = ({
return newList return newList
}) })
} }
const handleSend = () => {
if (loading || !application || !message || !message?.trim()) return const buildVariableParams = (variables: Variable[]) => {
// Validate required variables before sending
const { variables, files } = queryValues;
let isCanSend = true let isCanSend = true
const params: Record<string, any> = {} const params: Record<string, any> = {}
if (variables && variables.length > 0) { if (variables?.length > 0) {
const needRequired: string[] = [] const needRequired: string[] = []
variables.forEach(vo => { variables.forEach(vo => {
params[vo.name] = vo.value params[vo.name] = vo.value ?? vo.defaultValue
if (vo.required && (params[vo.name] === null || params[vo.name] === undefined || params[vo.name] === '')) { if (vo.required && (params[vo.name] === null || params[vo.name] === undefined || params[vo.name] === '')) {
isCanSend = false isCanSend = false
needRequired.push(vo.name) needRequired.push(vo.name)
} }
}) })
if (needRequired.length) { if (needRequired.length) {
messageApi.error(`${needRequired.join(',')} ${t('workflow.variableRequired')}`) messageApi.error(`${needRequired.join(',')} ${t('workflow.variableRequired')}`)
} }
} }
if (!isCanSend) { return { isCanSend, params }
setLoading(false) }
return
} const handleSend = () => {
if (loading || !application || !message || !message?.trim()) return
const files = toolbarRef.current?.getFiles() || []
const variables = toolbarRef.current?.getVariables() || []
const { isCanSend, params } = buildVariableParams(variables)
if (!isCanSend) return
addUserMessage(message, files) addUserMessage(message, files)
setMessage(undefined) setMessage(undefined)
form.setFieldValue('files', []) toolbarRef.current?.setFiles([])
setFileList([])
addAssistantMessage() addAssistantMessage()
setStreamLoading(true) setStreamLoading(true)
setLoading(true) setLoading(true)
@@ -251,113 +193,82 @@ const TestChat: FC<TestChatProps> = ({
formatParams(message, conversationId, files, params), formatParams(message, conversationId, files, params),
handleStreamMessage handleStreamMessage
) )
.catch(() => { .catch(() => setLoading(false))
setLoading(false)
})
.finally(() => { .finally(() => {
setLoading(false) setLoading(false)
setStreamLoading(false) setStreamLoading(false)
}) })
} }
const handleStreamMessage = (data: SSEMessage[]) => { const handleStreamMessage = (data: SSEMessage[]) => {
data.map(item => { data.map(item => {
const { conversation_id, content, message_length } = item.data as { conversation_id: string, content: string, message_length: number }; const { conversation_id, content, message_length, audio_url } = item.data as { conversation_id: string, content: string, message_length: number; audio_url?: string; };
switch (item.event) { switch (item.event) {
case 'start': case 'start':
if (conversation_id && conversationId !== conversation_id) { if (conversation_id && conversationId !== conversation_id) setConversationId(conversation_id)
setConversationId(conversation_id);
}
break break
case 'message': case 'message':
updateAssistantMessage(content) updateAssistantMessage(content)
if (conversation_id && conversationId !== conversation_id) { if (conversation_id && conversationId !== conversation_id) setConversationId(conversation_id)
setConversationId(conversation_id); break
}
break;
case 'end': case 'end':
if (audio_url) {
updateAssistantMessage(content, audio_url)
}
updateErrorAssistantMessage(message_length) updateErrorAssistantMessage(message_length)
setStreamLoading(false) setStreamLoading(false)
break; break
} }
}) })
}; }
const handleWorkflowSend = () => { const handleWorkflowSend = () => {
if (loading || !application || !message || !message?.trim()) return if (loading || !application || !message || !message?.trim()) return
const files = toolbarRef.current?.getFiles() || []
// Validate required variables before sending const variables = toolbarRef.current?.getVariables() || []
const { variables, files } = queryValues; const { isCanSend, params } = buildVariableParams(variables)
let isCanSend = true if (!isCanSend) return
const params: Record<string, any> = {}
if (variables.length > 0) {
const needRequired: string[] = []
variables.forEach(vo => {
params[vo.name] = vo.value ?? vo.defaultValue
if (vo.required && (params[vo.name] === null || params[vo.name] === undefined || params[vo.name] === '')) {
isCanSend = false
needRequired.push(vo.name)
}
})
if (needRequired.length) {
messageApi.error(`${needRequired.join(',')} ${t('workflow.variableRequired')}`)
}
}
if (!isCanSend) {
return
}
setLoading(true) setLoading(true)
addUserMessage(message, files) addUserMessage(message, files)
addAssistantMessage() addAssistantMessage()
form.setFieldsValue({ toolbarRef.current?.setFiles([])
files: [], setFileList([])
})
setMessage(undefined) setMessage(undefined)
setStreamLoading(true) setStreamLoading(true)
draftRun( draftRun(
application.id, application.id,
formatParams(message, conversationId, files, params), formatParams(message, conversationId, files, params),
handleWorkflowStreamMessage handleWorkflowStreamMessage
) )
.catch((error) => { .catch((error) => {
console.log('draftRun error', error)
setChatList(prev => { setChatList(prev => {
const newList = [...prev] const newList = [...prev]
const lastIndex = newList.length - 1 const lastIndex = newList.length - 1
if (lastIndex >= 0) { if (lastIndex >= 0) {
newList[lastIndex] = { newList[lastIndex] = { ...newList[lastIndex], status: 'failed', content: null, subContent: error.error }
...newList[lastIndex],
status: 'failed',
content: null,
subContent: error.error
}
} }
return newList return newList
}) })
}).finally(() => { })
.finally(() => {
setLoading(false) setLoading(false)
setStreamLoading(false) setStreamLoading(false)
}) })
} }
const handleWorkflowStreamMessage = (data: SSEMessage[]) => { const handleWorkflowStreamMessage = (data: SSEMessage[]) => {
data.forEach(item => { data.forEach(item => {
const { content, conversation_id } = item.data as NodeData; const { content, conversation_id } = item.data as NodeData;
switch (item.event) { switch (item.event) {
// Append streaming text chunks to assistant message // Append streaming text chunks to assistant message
case 'message': case 'message':
setChatList(prev => { setChatList(prev => {
const newList = [...prev] const newList = [...prev]
const lastIndex = newList.length - 1 const lastIndex = newList.length - 1
if (lastIndex >= 0) { if (lastIndex >= 0) {
newList[lastIndex] = { newList[lastIndex] = { ...newList[lastIndex], content: newList[lastIndex].content + content }
...newList[lastIndex],
content: newList[lastIndex].content + content
}
} }
return newList return newList
}) })
@@ -388,10 +299,10 @@ const TestChat: FC<TestChatProps> = ({
} }
}) })
} }
const addWorkflowNodeStartMessage = (data: NodeData) => { const addWorkflowNodeStartMessage = (data: NodeData) => {
const { node_id } = data; const { node_id } = data;
const { nodes } = config as WorkflowConfig const { nodes } = config as WorkflowConfig
const node = nodes.find(n => n.id === node_id); const node = nodes.find(n => n.id === node_id);
const { name, type } = node || {} const { name, type } = node || {}
const icon = nodeLibrary.flatMap(g => g.nodes).find(n => n.type === type)?.icon const icon = nodeLibrary.flatMap(g => g.nodes).find(n => n.type === type)?.icon
@@ -428,6 +339,7 @@ const TestChat: FC<TestChatProps> = ({
return newList return newList
}) })
} }
const updateWorkflowNodeEndMessage = (data: NodeData) => { const updateWorkflowNodeEndMessage = (data: NodeData) => {
const { node_id, input, output, error, elapsed_time, status } = data; const { node_id, input, output, error, elapsed_time, status } = data;
setChatList(prev => { setChatList(prev => {
@@ -456,10 +368,10 @@ const TestChat: FC<TestChatProps> = ({
return newList return newList
}) })
} }
const updateWorkflowCycleMessage = (data: NodeData) => { const updateWorkflowCycleMessage = (data: NodeData) => {
const { node_id, cycle_id, cycle_idx, input, output, error, elapsed_time, status } = data; const { node_id, cycle_id, cycle_idx, input, output, error, elapsed_time, status } = data;
const { nodes } = config as WorkflowConfig const { nodes } = config as WorkflowConfig
const node = nodes.find(n => n.id === node_id); const node = nodes.find(n => n.id === node_id);
const { name, type } = node || {} const { name, type } = node || {}
const icon = nodeLibrary.flatMap(g => g.nodes).find(n => n.type === type)?.icon const icon = nodeLibrary.flatMap(g => g.nodes).find(n => n.type === type)?.icon
@@ -500,22 +412,9 @@ const TestChat: FC<TestChatProps> = ({
return newList return newList
}) })
} }
const updateWorkflowEndMessage = (data: NodeData) => { const updateWorkflowEndMessage = (data: NodeData) => {
const { error, status } = data as { const { error, status, audio_url } = data;
content: string;
conversation_id: string | null;
cycle_id: string;
cycle_idx: number;
node_id: string;
node_name?: string;
node_type?: string;
input?: any;
output?: any;
elapsed_time?: string;
error?: any;
state: Record<string, any>;
status?: 'completed' | 'failed'
};
setChatList(prev => { setChatList(prev => {
const newList = [...prev] const newList = [...prev]
const lastIndex = newList.length - 1 const lastIndex = newList.length - 1
@@ -525,13 +424,13 @@ const TestChat: FC<TestChatProps> = ({
status, status,
error, error,
content: newList[lastIndex].content === '' ? null : newList[lastIndex].content, content: newList[lastIndex].content === '' ? null : newList[lastIndex].content,
audioUrl: audio_url
} }
} }
return newList return newList
}) })
} }
console.log('queryValues', queryValues)
return ( return (
<div className="rb:w-250 rb:p-3 rb:mx-auto"> <div className="rb:w-250 rb:p-3 rb:mx-auto">
<RbCard <RbCard
@@ -543,97 +442,29 @@ const TestChat: FC<TestChatProps> = ({
<Chat <Chat
empty={<Empty url={ChatIcon} title={t('application.testChatEmpty')} isNeedSubTitle={false} size={[240, 200]} />} empty={<Empty url={ChatIcon} title={t('application.testChatEmpty')} isNeedSubTitle={false} size={[240, 200]} />}
contentClassName={clsx(`rb:mx-[16px] rb:pt-[24px]`, { contentClassName={clsx(`rb:mx-[16px] rb:pt-[24px]`, {
'rb:h-[calc(100%-140px)]': !queryValues?.files?.length, 'rb:h-[calc(100%-140px)]': !fileList.length,
'rb:h-[calc(100%-208px)]': !!queryValues?.files?.length, 'rb:h-[calc(100%-208px)]': !!fileList.length,
})} })}
data={chatList} data={chatList}
streamLoading={streamLoading} streamLoading={streamLoading}
loading={loading} loading={loading}
onChange={setMessage} onChange={setMessage}
onSend={application?.type === 'workflow' ? handleWorkflowSend : handleSend} onSend={application?.type === 'workflow' ? handleWorkflowSend : handleSend}
fileList={queryValues?.files || []} fileList={fileList}
fileChange={updateFileList} fileChange={(list) => {
setFileList(list || [])
toolbarRef.current?.setFiles(list || [])
}}
labelFormat={(item) => item.role === 'user' ? t('application.you') : dayjs(item.created_at).locale('en').format('MMMM D, YYYY [at] h:mm A')} labelFormat={(item) => item.role === 'user' ? t('application.you') : dayjs(item.created_at).locale('en').format('MMMM D, YYYY [at] h:mm A')}
errorDesc={t('application.ReplyException')} errorDesc={t('application.ReplyException')}
renderRuntime={application?.type === 'workflow' ? (item, index) => { renderRuntime={application?.type === 'workflow' ? (item, index) => <Runtime item={item} index={index} /> : undefined}
return <Runtime item={item} index={index} />
} : undefined}
> >
<Form form={form}> <ChatToolbar
<Flex justify="space-between" className="rb:flex-1"> ref={toolbarRef}
<Space size={8} align="center"> features={features}
<Form.Item name="files" noStyle> onFilesChange={setFileList}
<Dropdown />
menu={{
items: [
{ key: 'define', label: t('memoryConversation.addRemoteFile') },
{
key: 'upload', label: (
<UploadFiles
onChange={fileChange}
/>
)
},
],
onClick: handleShowUpload
}}
>
<Flex align="center" justify="center" className="rb:size-7 rb:cursor-pointer rb:rounded-[14px] rb:border rb:border-[#EBEBEB] rb:hover:bg-[#F6F6F6]">
<div
className="rb:size-4 rb:bg-cover rb:bg-[url('@/assets/images/conversation/link.svg')]"
></div>
</Flex>
</Dropdown>
</Form.Item>
{/* <Form.Item name="web_search" valuePropName="checked" className="rb:mb-0!">
<ButtonCheckbox
icon={OnlineIcon}
checkedIcon={OnlineCheckedIcon}
>
{t(`memoryConversation.web_search`)}
</ButtonCheckbox>
</Form.Item>
<Tooltip title={t(`memoryConversation.memory`)}></Tooltip>
<Form.Item name="memory" valuePropName="checked" className="rb:mb-0!">
<ButtonCheckbox
icon={MemoryFunctionIcon}
checkedIcon={MemoryFunctionCheckedIcon}
cicle={true}
>
</ButtonCheckbox>
</Form.Item> */}
<Form.Item name="variables" className="rb:mb-0!" hidden={!queryValues?.variables?.length}>
<div
className={clsx("rb:flex rb:items-center rb:border rb:rounded-lg rb:px-2 rb:text-[12px] rb:h-6 rb:cursor-pointer rb:hover:bg-[#F0F3F8] rb:text-[#212332]", {
'rb:border-[#FF5D34] rb:text-[#FF5D34]': isNeedVariableConfig,
'rb:border-[#DFE4ED]': !isNeedVariableConfig,
})}
onClick={handleEditVariables}
>
<SettingOutlined className="rb:mr-1" />
{t(`memoryConversation.variableConfig`)}
</div>
</Form.Item>
</Space>
<Space size={8} align="center">
<AudioRecorder
onRecordingComplete={handleRecordingComplete}
/>
<Divider type="vertical" className="rb:ml-0! rb:mr-2!" />
</Space>
</Flex>
</Form>
</Chat> </Chat>
<VariableConfigModal
ref={variableConfigModalRef}
refresh={handleSave}
/>
<UploadFileListModal
ref={uploadFileListModalRef}
refresh={addFileList}
/>
</RbCard> </RbCard>
</div> </div>
) )

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-03 16:27:39 * @Date: 2026-02-03 16:27:39
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-13 15:20:32 * @Last Modified time: 2026-03-17 15:27:57
*/ */
/** /**
* Chat debugging component for application testing * Chat debugging component for application testing
@@ -12,25 +12,25 @@
import { type FC, useEffect, useState, useRef } from 'react'; import { type FC, useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom'
import clsx from 'clsx' import clsx from 'clsx'
import { Flex, Dropdown, type MenuProps, App, Divider } from 'antd'; import { App } from 'antd';
import { SettingOutlined } from '@ant-design/icons' import { SettingOutlined } from '@ant-design/icons'
import ChatIcon from '@/assets/images/application/chat.png' import ChatIcon from '@/assets/images/application/chat.png'
import DebuggingEmpty from '@/assets/images/application/debuggingEmpty.png' import DebuggingEmpty from '@/assets/images/application/debuggingEmpty.png'
import type { ChatData, Config } from '../types' import type { ChatData, Config, FeaturesConfigForm } from '../types'
import { runCompare, draftRun } from '@/api/application' import { runCompare, draftRun } from '@/api/application'
import Empty from '@/components/Empty' import Empty from '@/components/Empty'
import ChatContent from '@/components/Chat/ChatContent' import ChatContent from '@/components/Chat/ChatContent'
import type { ChatItem } from '@/components/Chat/types' import type { ChatItem } from '@/components/Chat/types'
import { type SSEMessage } from '@/utils/stream' import { type SSEMessage } from '@/utils/stream'
import ChatInput from '@/components/Chat/ChatInput' import ChatInput from '@/components/Chat/ChatInput'
import UploadFiles from '@/views/Conversation/components/FileUpload' import ChatToolbar from '@/components/Chat/ChatToolbar'
import AudioRecorder from '@/components/AudioRecorder' import type { ChatToolbarRef } from '@/components/Chat/ChatToolbar'
import UploadFileListModal from '@/views/Conversation/components/UploadFileListModal'
import type { UploadFileListModalRef } from '@/views/Conversation/types'
import type { Variable } from './VariableList/types' import type { Variable } from './VariableList/types'
/** /**
* Component props * Component props
*/ */
@@ -45,10 +45,12 @@ interface ChatProps {
handleSave: (flag?: boolean) => Promise<unknown>; handleSave: (flag?: boolean) => Promise<unknown>;
/** Source type: multi-agent cluster or single agent */ /** Source type: multi-agent cluster or single agent */
source?: 'multi_agent' | 'agent'; source?: 'multi_agent' | 'agent';
chatVariables?: Variable[]; // Add chatVariables prop /** chatVariables prop */
chatVariables?: Variable[];
handleEditVariables?: () => void; handleEditVariables?: () => void;
} }
/** /**
* Chat debugging component * Chat debugging component
* Allows testing application with different model configurations side-by-side * Allows testing application with different model configurations side-by-side
@@ -58,18 +60,29 @@ const Chat: FC<ChatProps> = ({
handleEditVariables handleEditVariables
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { id } = useParams()
const { message: messageApi } = App.useApp() const { message: messageApi } = App.useApp()
const toolbarRef = useRef<ChatToolbarRef>(null)
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [isCluster, setIsCluster] = useState(source === 'multi_agent') const [isCluster, setIsCluster] = useState(source === 'multi_agent')
const [conversationId, setConversationId] = useState<string | null>(null) const [conversationId, setConversationId] = useState<string | null>(null)
const [compareLoading, setCompareLoading] = useState(false) const [compareLoading, setCompareLoading] = useState(false)
const [fileList, setFileList] = useState<any[]>([]) const [fileList, setFileList] = useState<any[]>([])
const [message, setMessage] = useState<string | undefined>(undefined) const [message, setMessage] = useState<string | undefined>(undefined)
const uploadFileListModalRef = useRef<UploadFileListModalRef>(null) const [features, setFeatures] = useState<FeaturesConfigForm>({} as FeaturesConfigForm)
useEffect(() => {
setCompareLoading(false)
setLoading(false)
}, [chatList.map(item => item.label).join(',')])
useEffect(() => {
if (data?.features) setFeatures(data.features)
}, [data?.features])
useEffect(() => { useEffect(() => {
setIsCluster(source === 'multi_agent') setIsCluster(source === 'multi_agent')
setFileList([]) toolbarRef.current?.setFiles([])
setMessage(undefined) setMessage(undefined)
}, [source]) }, [source])
@@ -111,8 +124,8 @@ const Chat: FC<ChatProps> = ({
} }
} }
/** Update assistant message with streaming content */ /** Update assistant message with streaming content */
const updateAssistantMessage = (content?: string, model_config_id?: string, conversation_id?: string) => { const updateAssistantMessage = (content?: string, model_config_id?: string, conversation_id?: string, audio_url?: string) => {
if (!content || !model_config_id) return if ((!content && !audio_url) || !model_config_id) return
updateChatList(prev => { updateChatList(prev => {
const targetIndex = prev.findIndex(item => item.model_config_id === model_config_id); const targetIndex = prev.findIndex(item => item.model_config_id === model_config_id);
if (targetIndex !== -1) { if (targetIndex !== -1) {
@@ -123,12 +136,13 @@ const Chat: FC<ChatProps> = ({
if (lastMsg && lastMsg.role === 'assistant') { if (lastMsg && lastMsg.role === 'assistant') {
modelChatList[targetIndex] = { modelChatList[targetIndex] = {
...modelChatList[targetIndex], ...modelChatList[targetIndex],
conversation_id: conversation_id, conversation_id,
list: [ list: [
...curChatMsgList.slice(0, curChatMsgList.length - 1), ...curChatMsgList.slice(0, curChatMsgList.length - 1),
{ {
...lastMsg, ...lastMsg,
content: lastMsg.content + content content: lastMsg.content + (content || ''),
audioUrl: audio_url
} }
] ]
} }
@@ -146,8 +160,7 @@ const Chat: FC<ChatProps> = ({
const targetIndex = prev.findIndex(item => item.model_config_id === model_config_id); const targetIndex = prev.findIndex(item => item.model_config_id === model_config_id);
if (targetIndex > -1) { if (targetIndex > -1) {
const modelChatList = [...prev] const modelChatList = [...prev]
const curModelChat = modelChatList[targetIndex] const curChatMsgList = modelChatList[targetIndex].list || []
const curChatMsgList = curModelChat.list || []
const lastMsg = curChatMsgList[curChatMsgList.length - 1] const lastMsg = curChatMsgList[curChatMsgList.length - 1]
if (lastMsg.role === 'assistant') { if (lastMsg.role === 'assistant') {
modelChatList[targetIndex] = { modelChatList[targetIndex] = {
@@ -169,13 +182,14 @@ const Chat: FC<ChatProps> = ({
} }
/** Send message for agent comparison mode */ /** Send message for agent comparison mode */
const handleSend = (msg?: string) => { const handleSend = (msg?: string) => {
if (loading) return if (loading || !id) return
setLoading(true) setLoading(true)
setCompareLoading(true) setCompareLoading(true)
handleSave(false) handleSave(false)
.then(() => { .then(() => {
const message = msg const message = msg
if (!message?.trim()) return if (!message?.trim()) return
const files = toolbarRef.current?.getFiles() || []
// Validate required variables before sending // Validate required variables before sending
let isCanSend = true let isCanSend = true
const params: Record<string, any> = {} const params: Record<string, any> = {}
@@ -200,8 +214,9 @@ const Chat: FC<ChatProps> = ({
return return
} }
addUserMessage(message, fileList) addUserMessage(message, files)
setMessage(message) setMessage(message)
toolbarRef.current?.setFiles([])
setFileList([]) setFileList([])
addAssistantMessage() addAssistantMessage()
@@ -209,13 +224,16 @@ const Chat: FC<ChatProps> = ({
setCompareLoading(false) setCompareLoading(false)
data.map(item => { data.map(item => {
const { model_config_id, conversation_id, content, message_length } = item.data as { model_config_id: string; conversation_id: string; content: string; message_length: number }; const { model_config_id, conversation_id, content, message_length, audio_url } = item.data as { model_config_id: string; conversation_id: string; content: string; message_length: number; audio_url: string };
switch (item.event) { switch (item.event) {
case 'model_message': case 'model_message':
updateAssistantMessage(content, model_config_id, conversation_id) updateAssistantMessage(content, model_config_id, conversation_id, audio_url)
break; break;
case 'model_end': case 'model_end':
if (audio_url) {
updateAssistantMessage(content, model_config_id, conversation_id, audio_url)
}
updateErrorAssistantMessage(message_length, model_config_id) updateErrorAssistantMessage(message_length, model_config_id)
break; break;
case 'compare_end': case 'compare_end':
@@ -226,9 +244,9 @@ const Chat: FC<ChatProps> = ({
}; };
setTimeout(() => { setTimeout(() => {
runCompare(data.app_id, { runCompare(id, {
message, message,
files: fileList.map(file => { files: files.map(file => {
if (file.url) { if (file.url) {
return file return file
} else { } else {
@@ -246,9 +264,9 @@ const Chat: FC<ChatProps> = ({
conversation_id: item.conversation_id conversation_id: item.conversation_id
})), })),
variables: params, variables: params,
"parallel": true, parallel: true,
"stream": true, stream: true,
"timeout": 60, timeout: 60,
}, handleStreamMessage) }, handleStreamMessage)
.catch(() => { .catch(() => {
setLoading(false) setLoading(false)
@@ -272,7 +290,7 @@ const Chat: FC<ChatProps> = ({
const assistantMessage: ChatItem = { const assistantMessage: ChatItem = {
role: 'assistant', role: 'assistant',
content: '', content: '',
created_at: Date.now(), created_at: Date.now()
}; };
updateChatList(prev => prev.map(item => ({ updateChatList(prev => prev.map(item => ({
...item, ...item,
@@ -284,8 +302,7 @@ const Chat: FC<ChatProps> = ({
if (!content) return if (!content) return
updateChatList(prev => { updateChatList(prev => {
const modelChatList = [...prev] const modelChatList = [...prev]
const curModelChat = modelChatList[0] const curChatMsgList = modelChatList[0].list || []
const curChatMsgList = curModelChat.list || []
const lastMsg = curChatMsgList[curChatMsgList.length - 1] const lastMsg = curChatMsgList[curChatMsgList.length - 1]
if (lastMsg.role === 'assistant') { if (lastMsg.role === 'assistant') {
modelChatList[0] = { modelChatList[0] = {
@@ -305,11 +322,9 @@ const Chat: FC<ChatProps> = ({
/** Update cluster message when error occurs */ /** Update cluster message when error occurs */
const updateClusterErrorAssistantMessage = (message_length: number) => { const updateClusterErrorAssistantMessage = (message_length: number) => {
if (message_length > 0) return if (message_length > 0) return
updateChatList(prev => { updateChatList(prev => {
const modelChatList = [...prev] const modelChatList = [...prev]
const curModelChat = modelChatList[0] const curChatMsgList = modelChatList[0].list || []
const curChatMsgList = curModelChat.list || []
const lastMsg = curChatMsgList[curChatMsgList.length - 1] const lastMsg = curChatMsgList[curChatMsgList.length - 1]
if (lastMsg.role === 'assistant') { if (lastMsg.role === 'assistant') {
modelChatList[0] = { modelChatList[0] = {
@@ -326,17 +341,19 @@ const Chat: FC<ChatProps> = ({
return [...modelChatList] return [...modelChatList]
}) })
} }
/** Send message for cluster mode */
const handleClusterSend = (msg?: string) => { const handleClusterSend = (msg?: string) => {
if (loading) return if (loading || !id) return
setLoading(true) setLoading(true)
setCompareLoading(true) setCompareLoading(true)
handleSave(false) handleSave(false)
.then(() => { .then(() => {
const message = msg const message = msg
if (!message || message.trim() === '') return if (!message || message.trim() === '') return
addUserMessage(message, fileList) const files = toolbarRef.current?.getFiles() || []
addUserMessage(message, files)
setMessage(undefined) setMessage(undefined)
toolbarRef.current?.setFiles([])
setFileList([]) setFileList([])
addClusterAssistantMessage() addClusterAssistantMessage()
@@ -345,7 +362,7 @@ const Chat: FC<ChatProps> = ({
data.map(item => { data.map(item => {
const { conversation_id, content, message_length } = item.data as { conversation_id: string, content: string, message_length: number }; const { conversation_id, content, message_length } = item.data as { conversation_id: string, content: string, message_length: number };
switch (item.event) { switch (item.event) {
case 'start': case 'start':
if (conversation_id && conversationId !== conversation_id) { if (conversation_id && conversationId !== conversation_id) {
@@ -369,13 +386,12 @@ const Chat: FC<ChatProps> = ({
}; };
setTimeout(() => { setTimeout(() => {
draftRun( draftRun(id,
data.app_id,
{ {
message, message,
conversation_id: conversationId, conversation_id: conversationId,
stream: true, stream: true,
files: fileList.map(file => { files: files.map(file => {
if (file.url) { if (file.url) {
return file return file
} else { } else {
@@ -410,36 +426,6 @@ const Chat: FC<ChatProps> = ({
const handleDelete = (index: number) => { const handleDelete = (index: number) => {
updateChatList(chatList.filter((_, voIndex) => voIndex !== index)) updateChatList(chatList.filter((_, voIndex) => voIndex !== index))
} }
const handleMessageChange = (message: string) => {
setMessage(message)
}
const fileChange = (file?: any) => {
setFileList([...fileList, file])
}
const handleRecordingComplete = async (file: any) => {
setFileList([...fileList, {
uid: file.file_id,
response: { data: file },
thumbUrl: file.url,
type: file.type
}])
}
const handleShowUpload: MenuProps['onClick'] = ({ key }) => {
switch (key) {
case 'define':
uploadFileListModalRef.current?.handleOpen()
break
}
}
const addFileList = (list?: any[]) => {
if (!list || list.length <= 0) return
setFileList([...fileList, ...(list || [])])
}
const updateFileList = (list?: any[]) => {
setFileList([...list || []])
}
const isNeedVariableConfig = chatVariables?.some(vo => vo.required && (vo.value === null || vo.value === undefined || vo.value === ''))
return ( return (
<div className="rb:relative rb:h-full rb:flex rb:flex-col"> <div className="rb:relative rb:h-full rb:flex rb:flex-col">
@@ -458,13 +444,10 @@ const Chat: FC<ChatProps> = ({
"rb:border-r rb:border-[#DFE4ED]": index !== chatList.length - 1 && chatList.length > 1, "rb:border-r rb:border-[#DFE4ED]": index !== chatList.length - 1 && chatList.length > 1,
})}> })}>
{chat.label && {chat.label &&
<div className={clsx( <div className={clsx("rb:grid rb:bg-[#F0F3F8] rb:text-center rb:flex-[0_0_auto]", {
"rb:grid rb:bg-[#F0F3F8] rb:text-center rb:flex-[0_0_auto]", 'rb:rounded-tr-xl': index === chatList.length - 1,
{ 'rb:rounded-tl-xl': index === 0,
'rb:rounded-tr-xl': index === chatList.length - 1, })}>
'rb:rounded-tl-xl': index === 0,
}
)}>
<div className='rb:relative rb:p-[10px_12px] rb:overflow-hidden'> <div className='rb:relative rb:p-[10px_12px] rb:overflow-hidden'>
<div className="rb:text-ellipsis rb:overflow-hidden rb:whitespace-nowrap rb:w-[calc(100%-24px)]">{chat.label}</div> <div className="rb:text-ellipsis rb:overflow-hidden rb:whitespace-nowrap rb:w-[calc(100%-24px)]">{chat.label}</div>
<div <div
@@ -501,59 +484,37 @@ const Chat: FC<ChatProps> = ({
message={message} message={message}
className="rb:relative!" className="rb:relative!"
loading={loading} loading={loading}
fileChange={updateFileList} fileChange={(list) => {
setFileList(list || [])
toolbarRef.current?.setFiles(list || [])
}}
fileList={fileList} fileList={fileList}
onSend={isCluster ? handleClusterSend : handleSend} onSend={isCluster ? handleClusterSend : handleSend}
onChange={handleMessageChange} onChange={setMessage}
> >
<Flex justify="space-between" className="rb:flex-1"> <ChatToolbar
<Flex gap={8} align="center"> ref={toolbarRef}
<Dropdown features={features}
menu={{ onFilesChange={setFileList}
items: [ extra={
{ key: 'define', label: t('memoryConversation.addRemoteFile') }, chatVariables && chatVariables.length > 0 ? (
{
key: 'upload', label: (
<UploadFiles
onChange={fileChange}
/>
)
},
],
onClick: handleShowUpload
}}
>
<div <div
className="rb:size-6 rb:cursor-pointer rb:bg-cover rb:bg-[url('@/assets/images/conversation/link.svg')] rb:hover:bg-[url('@/assets/images/conversation/link_hover.svg')]" className={clsx('rb:flex rb:items-center rb:border rb:rounded-lg rb:px-2 rb:text-[12px] rb:h-6 rb:cursor-pointer rb:hover:bg-[#F0F3F8] rb:text-[#212332]', {
></div> 'rb:border-[#FF5D34] rb:text-[#FF5D34]': chatVariables.some(vo => vo.required && !vo.value),
</Dropdown> 'rb:border-[#DFE4ED]': !chatVariables.some(vo => vo.required && !vo.value),
{chatVariables && chatVariables.length > 0 && (
<div
className={clsx("rb:flex rb:items-center rb:border rb:rounded-lg rb:px-2 rb:text-[12px] rb:h-6 rb:cursor-pointer rb:hover:bg-[#F0F3F8] rb:text-[#212332]", {
'rb:border-[#FF5D34] rb:text-[#FF5D34]': isNeedVariableConfig,
'rb:border-[#DFE4ED]': !isNeedVariableConfig,
})} })}
onClick={handleEditVariables} onClick={handleEditVariables}
> >
<SettingOutlined className="rb:mr-1" /> <SettingOutlined className="rb:mr-1" />
{t(`memoryConversation.variableConfig`)} {t('memoryConversation.variableConfig')}
</div> </div>
)} ) : null
</Flex> }
<Flex align="center"> />
<AudioRecorder onRecordingComplete={handleRecordingComplete} />
<Divider type="vertical" className="rb:ml-1.5! rb:mr-3!" />
</Flex>
</Flex>
</ChatInput> </ChatInput>
</div> </div>
</> </>
} }
<UploadFileListModal
ref={uploadFileListModalRef}
refresh={addFileList}
/>
</div> </div>
) )
} }

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-03 16:27:52 * @Date: 2026-02-03 16:27:52
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-16 15:58:10 * @Last Modified time: 2026-03-16 17:04:56
*/ */
import { type FC, useRef, useMemo, useCallback } from 'react'; import { type FC, useRef, useMemo, useCallback } from 'react';
import { useNavigate, useParams } from 'react-router-dom'; import { useNavigate, useParams } from 'react-router-dom';
@@ -18,10 +18,10 @@ import exportIcon from '@/assets/images/export_hover.svg'
import deleteIcon from '@/assets/images/delete_hover.svg' import deleteIcon from '@/assets/images/delete_hover.svg'
import type { Application, ApplicationModalRef } from '@/views/ApplicationManagement/types'; import type { Application, ApplicationModalRef } from '@/views/ApplicationManagement/types';
import ApplicationModal from '@/views/ApplicationManagement/components/ApplicationModal' import ApplicationModal from '@/views/ApplicationManagement/components/ApplicationModal'
import type { CopyModalRef, AgentRef, ClusterRef, WorkflowRef, FunConfigForm } from '../types' import type { CopyModalRef, AgentRef, ClusterRef, WorkflowRef, FeaturesConfigForm } from '../types'
import { deleteApplication, appExport } from '@/api/application' import { deleteApplication, appExport } from '@/api/application'
import CopyModal from './CopyModal' import CopyModal from './CopyModal'
import FunConfig from './FunConfig' import FeaturesConfig from './FeaturesConfig'
const { Header } = Layout; const { Header } = Layout;
@@ -173,11 +173,11 @@ const ConfigHeader: FC<ConfigHeaderProps> = ({
return items return items
}, [t, handleClick, application]) }, [t, handleClick, application])
const funConfig = useMemo(() => { const features = useMemo(() => {
return (appRef?.current?.funConfig || { file_type: [] }) as FunConfigForm return (appRef?.current?.features || { file_type: [] }) as FeaturesConfigForm
}, [appRef]) }, [appRef])
const handleSaveFunConfig = useCallback((value: FunConfigForm) => { const handleSaveFeaturesConfig = useCallback((value: FeaturesConfigForm) => {
appRef?.current?.handleSaveFunConfig?.(value) appRef?.current?.handleSaveFeaturesConfig?.(value)
}, [appRef]) }, [appRef])
console.log('formatMenuItems', formatMenuItems) console.log('formatMenuItems', formatMenuItems)
@@ -211,7 +211,7 @@ const ConfigHeader: FC<ConfigHeaderProps> = ({
</div> </div>
{application?.type === 'workflow' {application?.type === 'workflow'
? <div className="rb:h-8 rb:flex rb:items-center rb:justify-end rb:gap-2.5"> ? <div className="rb:h-8 rb:flex rb:items-center rb:justify-end rb:gap-2.5">
{/* <FunConfig value={funConfig} refresh={handleSaveFunConfig} /> */} <FeaturesConfig value={features} refresh={handleSaveFeaturesConfig} />
<Button onClick={clear}>{t('workflow.clear')}</Button> <Button onClick={clear}>{t('workflow.clear')}</Button>
<Button onClick={addvariable}>{t('workflow.addvariable')}</Button> <Button onClick={addvariable}>{t('workflow.addvariable')}</Button>
<Button onClick={run}>{t('workflow.run')}</Button> <Button onClick={run}>{t('workflow.run')}</Button>

View File

@@ -0,0 +1,151 @@
/*
* @Author: ZhaoYing
* @Date: 2026-02-03 16:27:56
* @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-16 18:31:58
*/
/**
* Copy Application Modal
* Allows users to duplicate an existing application with a new name
*/
import { forwardRef, useImperativeHandle, useState, useRef } from 'react';
import { Form, Button, Flex } from 'antd';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx'
import type { FeaturesConfigModalRef, FeaturesConfigForm } from '../../types'
import RbModal from '@/components/RbModal'
import SwitchFormItem from '@/components/FormItem/SwitchFormItem'
import FileUploadSettingModal from './FileUploadSettingModal'
interface FeaturesConfigModalProps {
refresh: (value: FeaturesConfigForm) => void;
}
/**
* Modal for copying applications
*/
const FeaturesConfigModal = forwardRef<FeaturesConfigModalRef, FeaturesConfigModalProps>(({
refresh,
}, ref) => {
const { t } = useTranslation();
const [visible, setVisible] = useState(false);
const [form] = Form.useForm<FeaturesConfigForm>();
const values = Form.useWatch([], form)
const fileUploadSettingModalRef = useRef<any>(null)
/** Close modal and reset form */
const handleClose = () => {
setVisible(false);
form.resetFields();
};
/** Open modal */
const handleOpen = (initValue: FeaturesConfigForm) => {
setVisible(true);
form.setFieldsValue(initValue)
};
/** Copy application with new name */
const handleSave = () => {
setVisible(false);
refresh(form.getFieldsValue())
}
const handleOpenSettings = () => {
fileUploadSettingModalRef.current?.handleOpen(values?.file_upload)
}
const handleSaveSettings = (settings: FeaturesConfigForm['file_upload']) => {
form.setFieldValue('file_upload', { ...settings, enabled: values?.file_upload?.enabled ?? false })
}
/** Expose methods to parent component */
useImperativeHandle(ref, () => ({
handleOpen,
handleClose
}));
console.log('settings values', values)
return (
<>
<RbModal
title={t('application.features')}
open={visible}
onCancel={handleClose}
okText={t('common.confirm')}
onOk={handleSave}
>
<Form
form={form}
layout="vertical"
>
<Flex vertical gap={12}>
<div className="rb:relative rb:border rb:border-[#DFE4ED] rb:p-3 rb:rounded-lg rb:bg-[#f5f7fc]">
<SwitchFormItem
title={t(`memoryConversation.web_search`)}
name={['web_search', "enabled"]}
/>
</div>
<div className="rb:relative rb:border rb:border-[#DFE4ED] rb:p-3 rb:rounded-lg rb:bg-[#f5f7fc]">
<SwitchFormItem
title={t('application.text_to_speech')}
name={['text_to_speech', "enabled"]}
desc={t('application.text_to_speech_desc')}
/>
</div>
<div className="rb:relative rb:border rb:border-[#DFE4ED] rb:p-3 rb:rounded-lg rb:bg-[#f5f7fc]">
<SwitchFormItem
title={t('application.file_upload')}
name={['file_upload', "enabled"]}
desc={values?.file_upload?.enabled ? undefined : t('application.file_upload_desc')}
/>
{values?.file_upload?.enabled && (() => {
const fu = values.file_upload
const types = [
{ type: 'image', enabled: fu.image_enabled, maxSize: fu.image_max_size_mb },
{ type: 'audio', enabled: fu.audio_enabled, maxSize: fu.audio_max_size_mb },
{ type: 'document', enabled: fu.document_enabled, maxSize: fu.document_max_size_mb },
{ type: 'video', enabled: fu.video_enabled, maxSize: fu.video_max_size_mb },
].filter(item => item.enabled)
return types.length > 0 ? <>
<Flex gap={12} className="rb:py-2!">
<div className="rb:flex-1 rb:border rb:border-[#DFE4ED] rb:rounded-lg rb:bg-white rb:text-[12px]">
<div className="rb:grid rb:grid-cols-2 rb:gap-2 rb:text-[12px] rb:text-[#5B6167] rb:border-b rb:border-b-[#DFE4ED]">
<div className="rb:px-3 rb:py-1">{t(`application.supportedTypes`)}</div>
<div className="rb:px-3 rb:py-1">{t('application.singleMaxSize')}</div>
</div>
{types.map((item, index) => (
<div key={item.type} className={clsx('rb:grid rb:grid-cols-2 rb:gap-2', {
'rb:border-b rb:border-b-[#DFE4ED]': index !== types.length - 1
})}>
<div className="rb:px-3 rb:py-1">{t(`application.${item.type}`)}</div>
<div className="rb:px-3 rb:py-1">{item.maxSize} MB</div>
</div>
))}
</div>
<div>
<div className="rb:text-[12px] rb:text-[#5B6167] rb:py-1">{t('application.maxCount')}</div>
{fu.max_file_count} {t('application.unix')}
</div>
</Flex>
<Button block onClick={handleOpenSettings}>{t('application.setting')}</Button>
</> : <Button block onClick={handleOpenSettings}>{t('application.setting')}</Button>
})()}
<Form.Item name="file_upload" hidden />
</div>
</Flex>
</Form>
</RbModal>
<FileUploadSettingModal
ref={fileUploadSettingModalRef}
onSave={handleSaveSettings}
/>
</>
);
});
export default FeaturesConfigModal;

View File

@@ -0,0 +1,180 @@
/*
* @Author: ZhaoYing
* @Date: 2026-03-05
* @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-16 18:36:09
*/
import { forwardRef, useImperativeHandle, useState } from 'react';
import { Form, InputNumber, Flex, Switch, Row, Col, Radio } from 'antd';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import RbModal from '@/components/RbModal';
import type { FeaturesConfigForm } from '../../types'
type FileUpload = Omit<FeaturesConfigForm['file_upload'], 'settings'>
interface FileUploadSettingModalRef {
handleOpen: (values?: FileUpload) => void;
handleClose: () => void;
}
interface FileUploadSettingModalProps {
onSave: (values: FileUpload) => void;
}
const fileTypeOptions = [
{
type: 'document',
icon: <div className="rb:size-9 rb:bg-cover rb:bg-[url('@/assets/images/file/txt.svg')]"></div>,
formats: 'TXT, MD, MDX, MARKDOWN, PDF, DOC, DOCX',
},
{
type: 'image',
icon: <div className="rb:size-9 rb:bg-cover rb:bg-[url('@/assets/images/file/image.svg')]"></div>,
formats: 'JPG, JPEG, PNG, GIF, WEBP, SVG',
},
{
type: 'audio',
icon: <div className="rb:size-9 rb:bg-cover rb:bg-[url('@/assets/images/file/audio.svg')]"></div>,
formats: 'MP3, M4A, WAV, AMR, MPGA',
},
{
type: 'video',
icon: <div className="rb:size-9 rb:bg-cover rb:bg-[url('@/assets/images/file/video.svg')]"></div>,
formats: 'MP4, MOV, MPEG, WEBM',
},
];
const defaultValues: FileUpload = {
enabled: false,
image_enabled: false,
image_max_size_mb: 20,
image_allowed_extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'],
audio_enabled: false,
audio_max_size_mb: 50,
audio_allowed_extensions: ['mp3', 'wav', 'm4a', 'ogg', 'flac'],
document_enabled: false,
document_max_size_mb: 100,
document_allowed_extensions: ['pdf', 'docx', 'xlsx', 'txt', 'csv', 'json'],
video_enabled: false,
video_max_size_mb: 500,
video_allowed_extensions: ['mp4', 'mov', 'avi', 'webm'],
max_file_count: 5,
allowed_transfer_methods: 'both'
}
const FileUploadSettingModal = forwardRef<FileUploadSettingModalRef, FileUploadSettingModalProps>(({
onSave,
}, ref) => {
const { t } = useTranslation();
const [visible, setVisible] = useState(false);
const [form] = Form.useForm<FileUpload>();
const values = Form.useWatch([], form)
const handleClose = () => {
setVisible(false);
form.resetFields();
};
const handleOpen = (values?: FileUpload) => {
setVisible(true);
if (values) {
const methods = values.allowed_transfer_methods
const transferMethod = Array.isArray(methods)
? methods.length === 2 ? 'both' : methods[0]
: methods
form.setFieldsValue({ ...values, allowed_transfer_methods: transferMethod as any })
} else {
form.setFieldsValue(defaultValues)
}
};
const handleSave = async () => {
const vals = await form.validateFields();
const methodMap: Record<string, string[]> = {
local_file: ['local_file'],
remote_url: ['remote_url'],
both: ['local_file', 'remote_url'],
}
onSave({ ...vals, allowed_transfer_methods: methodMap[vals.allowed_transfer_methods as unknown as string] ?? [] });
handleClose();
};
useImperativeHandle(ref, () => ({
handleOpen,
handleClose
}));
return (
<RbModal
title={t('application.settings')}
open={visible}
onCancel={handleClose}
onOk={handleSave}
width={600}
>
<Form form={form} layout="vertical" initialValues={defaultValues}>
<Form.Item
label={t('application.uploadType')}
name="allowed_transfer_methods"
>
<Radio.Group block buttonStyle="solid">
<Radio.Button value="local_file">{t('application.local')}</Radio.Button>
<Radio.Button value="remote_url">URL</Radio.Button>
<Radio.Button value="both">{t('application.both')}</Radio.Button>
</Radio.Group>
</Form.Item>
<div className="rb:text-[12px] rb:text-[#5B6167] rb:mb-1">{t('application.maxCount')}</div>
<Form.Item label={t('application.maxCount')} name="max_file_count">
<InputNumber min={1} max={100} className="rb:w-full!" placeholder={t('common.pleaseEnter')} />
</Form.Item>
<Form.Item label={t('application.supportedTypes')}>
<Flex vertical gap={12}>
{fileTypeOptions.map((option) => {
const enabledKey = `${option.type}_enabled` as keyof FileUpload
const sizeKey = `${option.type}_max_size_mb` as keyof FileUpload
const isEnabled = values?.[enabledKey]
return (
<div
key={option.type}
className={clsx('rb:border rb:border-[#DFE4ED] rb:rounded-lg rb:p-3', {
'rb:bg-[#f5f7fc]': isEnabled
})}
>
<Row gutter={12}>
<Col flex="36px" className="rb:self-center">{option.icon}</Col>
<Col flex="1">
<Flex align="center" justify="space-between">
<Flex vertical>
<div className="rb:font-medium">{t(`application.${option.type}`)}</div>
<div className="rb:text-[12px] rb:text-[#5B6167]">{option.formats}</div>
</Flex>
<Form.Item name={enabledKey} valuePropName="checked" noStyle>
<Switch />
</Form.Item>
</Flex>
</Col>
</Row>
{isEnabled && (
<Flex align="center" gap={12} className="rb:mt-3! rb:pt-3! rb:border-t rb:border-[#DFE4ED]">
<div>{t('application.singleMaxSize')}: </div>
<Form.Item name={sizeKey} noStyle>
<InputNumber min={1} max={500} suffix="MB" className="rb:flex-1" />
</Form.Item>
<Form.Item name={`${option.type}_allowed_extensions`} hidden />
</Flex>
)}
</div>
)
})}
</Flex>
</Form.Item>
</Form>
</RbModal>
);
});
export default FileUploadSettingModal;

View File

@@ -1,45 +1,44 @@
/* /*
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-03-13 17:20:21 * @Date: 2026-03-13 17:20:21
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-13 17:20:21 * @Last Modified time: 2026-03-16 18:31:43
*/ */
import { type FC, useRef } from 'react'; import { type FC, useRef } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button } from 'antd'; import { Button } from 'antd';
import FunConfigModal from './FunConfigModal' import FeaturesConfigModal from './FeaturesConfigModal'
import type { FunConfigModalRef, FunConfigForm } from '../../types' import type { FeaturesConfigModalRef, FeaturesConfigForm } from '../../types'
/** Props for the FunConfig component */ /** Props for the FeaturesConfig component */
interface FunConfigProps { interface FeaturesConfigProps {
/** Current feature configuration values */ /** Current feature configuration values */
value: FunConfigForm; value: FeaturesConfigForm;
/** Callback to propagate updated config back to the parent */ /** Callback to propagate updated config back to the parent */
refresh: (value: FunConfigForm) => void; refresh: (value: FeaturesConfigForm) => void;
} }
const FunConfig: FC<FunConfigProps> = ({ const FeaturesConfig: FC<FeaturesConfigProps> = ({
value, value,
refresh refresh
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
// Ref used to imperatively open the config modal // Ref used to imperatively open the config modal
const funConfigModalRef = useRef<FunConfigModalRef>(null) const funConfigModalRef = useRef<FeaturesConfigModalRef>(null)
/** Open the feature config modal pre-populated with the current values */ /** Open the feature config modal pre-populated with the current values */
const handleFunConfig = () => { const handleFeaturesConfig = () => {
console.log('funConfig', value)
funConfigModalRef.current?.handleOpen(value) funConfigModalRef.current?.handleOpen(value)
} }
return ( return (
<> <>
{/* Button that triggers the feature configuration modal */} {/* Button that triggers the feature configuration modal */}
<Button onClick={handleFunConfig}>{t('application.funConfig')}</Button> <Button onClick={handleFeaturesConfig}>{t('application.features')}</Button>
{/* Modal for editing feature settings; calls refresh on save */} {/* Modal for editing feature settings; calls refresh on save */}
<FunConfigModal <FeaturesConfigModal
ref={funConfigModalRef} ref={funConfigModalRef}
refresh={refresh} refresh={refresh}
/> />
@@ -47,4 +46,4 @@ const FunConfig: FC<FunConfigProps> = ({
) )
} }
export default FunConfig export default FeaturesConfig

View File

@@ -1,182 +0,0 @@
/*
* @Author: ZhaoYing
* @Date: 2026-03-05
* @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-11 15:42:13
*/
import { forwardRef, useImperativeHandle, useState } from 'react';
import { Form, Radio, InputNumber, Flex, Switch, Row, Col } from 'antd';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import RbModal from '@/components/RbModal';
import type { FunConfigForm } from '../../types'
interface FileUploadSettingModalRef {
handleOpen: (values?: FileUploadSettings) => void;
handleClose: () => void;
}
interface FileUploadSettings extends Omit<FunConfigForm, 'enabled'> {}
interface FileUploadSettingModalProps {
onSave: (values: FileUploadSettings) => void;
}
const fileTypeOptions = [
{
type: 'document',
icon: <div className="rb:size-9 rb:bg-cover rb:bg-[url('@/assets/images/file/txt.svg')]"></div>,
formats: 'TXT, MD, MDX, MARKDOWN, PDF, DOC, DOCX',
defaultMaxCount: 1,
defaultMaxSize: 2
},
{
type: 'image',
icon: <div className="rb:size-9 rb:bg-cover rb:bg-[url('@/assets/images/file/image.svg')]"></div>,
formats: 'JPG, JPEG, PNG, GIF, WEBP, SVG',
defaultMaxCount: 1,
defaultMaxSize: 2
},
{
type: 'audio',
icon: <div className="rb:size-9 rb:bg-cover rb:bg-[url('@/assets/images/file/audio.svg')]"></div>,
formats: 'MP3, M4A, WAV, AMR, MPGA',
defaultMaxCount: 1,
defaultMaxSize: 2
},
{
type: 'video',
icon: <div className="rb:size-9 rb:bg-cover rb:bg-[url('@/assets/images/file/video.svg')]"></div>,
formats: 'MP4, MOV, MPEG, WEBM',
defaultMaxCount: 1,
defaultMaxSize: 2
},
];
const FileUploadSettingModal = forwardRef<FileUploadSettingModalRef, FileUploadSettingModalProps>(({
onSave,
}, ref) => {
const { t } = useTranslation();
const [visible, setVisible] = useState(false);
const [form] = Form.useForm();
const values = Form.useWatch([], form)
const handleClose = () => {
setVisible(false);
form.resetFields();
};
const handleOpen = (values?: FileUploadSettings) => {
setVisible(true);
// if (values) {
// form.setFieldsValue(values);
// }
};
const handleSave = async () => {
const values = await form.validateFields();
onSave(values);
handleClose();
};
useImperativeHandle(ref, () => ({
handleOpen,
handleClose
}));
return (
<RbModal
title={t('application.settings')}
open={visible}
onCancel={handleClose}
onOk={handleSave}
width={600}
>
<Form
form={form}
layout="vertical"
initialValues={{
uploadType: 'both',
fileTypes: fileTypeOptions.map(opt => ({
type: opt.type,
enabled: false,
maxCount: opt.defaultMaxCount,
maxSize: opt.defaultMaxSize
}))
}}
>
<Form.Item
label={t('application.uploadType')}
name="uploadType"
>
<Radio.Group block buttonStyle="solid">
<Radio.Button value="local">{t('application.local')}</Radio.Button>
<Radio.Button value="url">URL</Radio.Button>
<Radio.Button value="both">{t('application.both')}</Radio.Button>
</Radio.Group>
</Form.Item>
<div className="rb:text-[12px] rb:text-[#5B6167] rb:mb-1">{t('application.maxCount')}</div>
<Form.Item
name="maxCount"
label={t('application.maxCount')}
>
<InputNumber min={1} max={100} className="rb:w-full!" placeholder={t('common.pleaseEnter')} />
</Form.Item>
<Form.Item label={t('application.supportedTypes')}>
<Form.List name="fileTypes">
{(fields) => (
<Flex vertical gap={12}>
{fields.map((field, index) => {
const option = fileTypeOptions[index];
const isEnabled = values?.fileTypes?.[index]?.enabled;
return (
<div
key={field.key}
className={clsx("rb:border rb:border-[#DFE4ED] rb:rounded-lg rb:p-3", {
'rb:bg-[#f5f7fc]': isEnabled
})}
>
<Row gutter={12}>
<Col flex="36px" className="rb:self-center">
{option.icon}
</Col>
<Col flex="1">
<Flex align="center" justify="space-between">
<Flex vertical>
<div className="rb:font-medium">{t(`application.${option.type}`)}</div>
<div className="rb:text-[12px] rb:text-[#5B6167]">{option.formats}</div>
</Flex>
<Form.Item name={[field.name, 'enabled']} valuePropName="checked" noStyle>
<Switch />
</Form.Item>
</Flex>
</Col>
</Row>
{isEnabled && (
<Flex align="center" gap={12} className="rb:mt-3! rb:pt-3! rb:border-t rb:border-[#DFE4ED]">
<div>{t('application.singleMaxSize')}: </div>
<Form.Item name={[field.name, 'maxSize']} noStyle>
<InputNumber min={1} max={500} suffix="MB" className="rb:flex-1" />
</Form.Item>
</Flex>
)}
<Form.Item name={[field.name, 'type']} hidden>
<input type="hidden" />
</Form.Item>
</div>
);
})}
</Flex>
)}
</Form.List>
</Form.Item>
</Form>
</RbModal>
);
});
export default FileUploadSettingModal;

View File

@@ -1,140 +0,0 @@
/*
* @Author: ZhaoYing
* @Date: 2026-02-03 16:27:56
* @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-13 17:20:30
*/
/**
* Copy Application Modal
* Allows users to duplicate an existing application with a new name
*/
import { forwardRef, useImperativeHandle, useState, useRef } from 'react';
import { Form, Button, Flex } from 'antd';
import { useTranslation } from 'react-i18next';
import type { FunConfigModalRef } from '../../types'
import RbModal from '@/components/RbModal'
import type { FunConfigForm } from '../../types'
import SwitchFormItem from '@/components/FormItem/SwitchFormItem'
import FileUploadSettingModal from './FileUploadSettingModal'
const FormItem = Form.Item;
interface FunConfigModalProps {
refresh: (value: FunConfigForm) => void;
}
/**
* Modal for copying applications
*/
const FunConfigModal = forwardRef<FunConfigModalRef, FunConfigModalProps>(({
refresh,
}, ref) => {
const { t } = useTranslation();
const [visible, setVisible] = useState(false);
const [form] = Form.useForm<FunConfigForm>();
const [loading, setLoading] = useState(false)
const values = Form.useWatch([], form)
const fileUploadSettingModalRef = useRef<any>(null)
/** Close modal and reset form */
const handleClose = () => {
setVisible(false);
form.resetFields();
setLoading(false)
};
/** Open modal */
const handleOpen = (initValue: FunConfigForm) => {
setVisible(true);
form.setFieldsValue(initValue)
};
/** Copy application with new name */
const handleSave = () => {
setVisible(false);
setLoading(true)
const values = form.getFieldsValue()
refresh(values)
}
const handleOpenSettings = () => {
fileUploadSettingModalRef.current?.handleOpen(values)
}
const handleSaveSettings = (settings: any) => {
form.setFieldsValue(settings)
}
/** Expose methods to parent component */
useImperativeHandle(ref, () => ({
handleOpen,
handleClose
}));
return (
<>
<RbModal
title={t('application.funConfig')}
open={visible}
onCancel={handleClose}
okText={t('common.copy')}
onOk={handleSave}
confirmLoading={loading}
>
<Form
form={form}
layout="vertical"
>
<Flex vertical gap={12}>
<div className="rb:relative rb:border rb:border-[#DFE4ED] rb:p-3 rb:rounded-lg rb:bg-[#f5f7fc]">
<SwitchFormItem
title={t(`memoryConversation.web_search`)}
name={['web_search', "enabled"]}
/>
</div>
<div className="rb:relative rb:border rb:border-[#DFE4ED] rb:p-3 rb:rounded-lg rb:bg-[#f5f7fc]">
<SwitchFormItem
title={t('application.textTranfer')}
name={['textTranfer', "enabled"]}
desc={t('application.textTranferDesc')}
/>
</div>
<div className="rb:relative rb:border rb:border-[#DFE4ED] rb:p-3 rb:rounded-lg rb:bg-[#f5f7fc]">
<SwitchFormItem
title={t('application.fileUpload')}
name={['fileUpload', "enabled"]}
desc={values?.fileUpload?.enabled ? undefined : t('application.fileUploadDesc')}
/>
{values?.fileUpload?.enabled && values?.fileTypes?.length > 0 ? <>
<div className="rb:grid rb:grid-cols-3 rb:gap-2 rb:text-[12px] rb:text-[#5B6167]">
<div>{t(`application.supportedTypes`)}</div>
<div>{t('application.maxCount')}</div>
<div>{t('application.singleMaxSize')}</div>
</div>
{values?.fileTypes?.filter(item => item.enabled).map(item => (
<div key={item.type} className="rb:grid rb:grid-cols-3 rb:gap-2">
<div>{t(`application.${item.type}`)}</div>
<div>{item.maxCount} {t('application.unix')}</div>
<div>{item.maxSize} MB</div>
</div>
))}
<Button block onClick={handleOpenSettings}>{t('application.setting')}</Button>
</> : null}
<FormItem name="fileTypes" noStyle hidden></FormItem>
<FormItem name="uploadType" noStyle hidden></FormItem>
</div>
</Flex>
</Form>
</RbModal>
<FileUploadSettingModal
ref={fileUploadSettingModalRef}
onSave={handleSaveSettings}
/>
</>
);
});
export default FunConfigModal;

View File

@@ -1,8 +1,8 @@
/* /*
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-03 16:26:03 * @Date: 2026-02-03 16:26:03
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-02-03 16:26:03 * @Last Modified time: 2026-03-17 15:53:06
*/ */
/** /**
* Tool List Component * Tool List Component
@@ -22,6 +22,7 @@ import type {
import Empty from '@/components/Empty' import Empty from '@/components/Empty'
import ToolModal from './ToolModal' import ToolModal from './ToolModal'
import { getToolMethods, getToolDetail } from '@/api/tools' import { getToolMethods, getToolDetail } from '@/api/tools'
import Tag from '@/components/Tag'
/** /**
* Tool list management component * Tool list management component
@@ -42,23 +43,25 @@ const ToolList: FC<{ value?: ToolOption[]; onChange?: (config: ToolOption[]) =>
getToolMethods(item.tool_id) getToolMethods(item.tool_id)
]) ])
console.log('toolDetail', toolDetail)
switch ((toolDetail as any).tool_type) { switch ((toolDetail as any).tool_type) {
case 'mcp': case 'mcp':
const mcpFilterItem = (methods as any[]).find(vo => vo.name === item.operation) const mcpFilterItem = (methods as any[]).find(vo => vo.name === item.operation)
return { return {
...item, ...item,
is_active: (toolDetail as any).is_active,
label: mcpFilterItem?.description, label: mcpFilterItem?.description,
method_id: mcpFilterItem?.method_id, method_id: mcpFilterItem?.method_id,
value: mcpFilterItem?.name, value: mcpFilterItem?.name,
description: mcpFilterItem?.description, description: mcpFilterItem?.description,
parameters: mcpFilterItem?.parameters parameters: mcpFilterItem?.parameters
} }
break
case 'builtin': case 'builtin':
if ((methods as any[]).length > 1) { if ((methods as any[]).length > 1) {
const builtinFilterItem = (methods as any[]).find(vo => vo.name === item.operation) const builtinFilterItem = (methods as any[]).find(vo => vo.name === item.operation)
return { return {
...item, ...item,
is_active: (toolDetail as any).is_active,
label: builtinFilterItem?.description, label: builtinFilterItem?.description,
method_id: builtinFilterItem?.method_id, method_id: builtinFilterItem?.method_id,
value: builtinFilterItem?.name, value: builtinFilterItem?.name,
@@ -68,17 +71,18 @@ const ToolList: FC<{ value?: ToolOption[]; onChange?: (config: ToolOption[]) =>
} }
return { return {
...item, ...item,
is_active: (toolDetail as any).is_active,
label: (methods as any[])[0]?.description, label: (methods as any[])[0]?.description,
method_id: (methods as any[])[0]?.method_id, method_id: (methods as any[])[0]?.method_id,
value: (methods as any[])[0]?.name, value: (methods as any[])[0]?.name,
description: (methods as any[])[0]?.description, description: (methods as any[])[0]?.description,
parameters: (methods as any[])[0]?.parameters parameters: (methods as any[])[0]?.parameters
} }
break
default: default:
const customFilterItem = (methods as any[]).find(vo => vo.method_id === item.operation) const customFilterItem = (methods as any[]).find(vo => vo.method_id === item.operation)
return { return {
...item, ...item,
is_active: (toolDetail as any).is_active,
label: customFilterItem?.name, label: customFilterItem?.name,
method_id: customFilterItem?.method_id, method_id: customFilterItem?.method_id,
value: customFilterItem?.name, value: customFilterItem?.name,
@@ -127,6 +131,7 @@ const ToolList: FC<{ value?: ToolOption[]; onChange?: (config: ToolOption[]) =>
setToolList([...list]) setToolList([...list])
onChange && onChange(list) onChange && onChange(list)
} }
console.log('toolList', toolList)
return ( return (
<Card <Card
title={t('application.toolConfiguration')} title={t('application.toolConfiguration')}
@@ -143,8 +148,13 @@ const ToolList: FC<{ value?: ToolOption[]; onChange?: (config: ToolOption[]) =>
renderItem={(item, index) => ( renderItem={(item, index) => (
<List.Item> <List.Item>
<div key={index} className="rb:flex rb:items-center rb:justify-between rb:p-[12px_16px] rb:bg-[#FBFDFF] rb:border rb:border-[#DFE4ED] rb:rounded-lg"> <div key={index} className="rb:flex rb:items-center rb:justify-between rb:p-[12px_16px] rb:bg-[#FBFDFF] rb:border rb:border-[#DFE4ED] rb:rounded-lg">
<div className="rb:font-medium rb:leading-4"> <div>
{item.label} <div className="rb:font-medium rb:leading-4">
{item.label}
</div>
<Tag color={item.is_active ? 'success' : 'error'} className="rb:mt-1">
{item.is_active ? t('common.enable') : t('common.deleted')}
</Tag>
</div> </div>
<Space size={12}> <Space size={12}>
<div <div

View File

@@ -1,8 +1,8 @@
/* /*
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-03 16:26:10 * @Date: 2026-02-03 16:26:10
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-02-03 16:26:10 * @Last Modified time: 2026-03-17 15:50:48
*/ */
/** /**
* Type definitions for tool configuration in application settings * Type definitions for tool configuration in application settings
@@ -32,6 +32,7 @@ export interface ToolOption {
tool_id?: string; tool_id?: string;
/** Whether tool is enabled */ /** Whether tool is enabled */
enabled?: boolean; enabled?: boolean;
is_active?: boolean;
} }
/** /**

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-03 16:29:49 * @Date: 2026-02-03 16:29:49
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-13 17:01:04 * @Last Modified time: 2026-03-16 17:42:12
*/ */
import type { KnowledgeConfig } from './components/Knowledge/types' import type { KnowledgeConfig } from './components/Knowledge/types'
import type { Variable } from './components/VariableList/types' import type { Variable } from './components/VariableList/types'
@@ -78,7 +78,7 @@ export interface Config extends MultiAgentConfig {
updated_at: number; updated_at: number;
skills?: SkillConfigForm | null; skills?: SkillConfigForm | null;
funConfig?: FunConfigForm; features?: FeaturesConfigForm;
} }
/** /**
@@ -129,8 +129,8 @@ export interface AgentRef {
* @param flag - Whether to show success message * @param flag - Whether to show success message
*/ */
handleSave: (flag?: boolean) => Promise<unknown>; handleSave: (flag?: boolean) => Promise<unknown>;
funConfig: Config['funConfig']; features: Config['features'];
handleSaveFunConfig?: (value: FunConfigForm) => void; handleSaveFeaturesConfig?: (value: FeaturesConfigForm) => void;
} }
/** /**
@@ -142,8 +142,8 @@ export interface ClusterRef {
* @param flag - Whether to show success message * @param flag - Whether to show success message
*/ */
handleSave: (flag?: boolean) => Promise<unknown>; handleSave: (flag?: boolean) => Promise<unknown>;
funConfig: Config['funConfig']; features: Config['features'];
handleSaveFunConfig?: (value: FunConfigForm) => void; handleSaveFeaturesConfig?: (value: FeaturesConfigForm) => void;
} }
/** /**
@@ -162,8 +162,8 @@ export interface WorkflowRef {
/** Add variable */ /** Add variable */
addVariable: () => void; addVariable: () => void;
config: WorkflowConfig | null; config: WorkflowConfig | null;
funConfig: WorkflowConfig['funConfig']; features: WorkflowConfig['features'];
handleSaveFunConfig?: (value: FunConfigForm) => void; handleSaveFeaturesConfig?: (value: FeaturesConfigForm) => void;
} }
/** /**
@@ -416,17 +416,55 @@ export interface FileTypeConfig {
maxCount: number; maxCount: number;
maxSize: number; maxSize: number;
} }
export interface FunConfigForm { interface FileSetttings {
enabled: boolean; image_enabled: boolean;
fileTypes: FileTypeConfig[] image_max_size_mb: number;
uploadType: 'local' | 'url' | 'both'; image_allowed_extensions: string[];
audio_enabled: boolean;
audio_max_size_mb: number;
audio_allowed_extensions: string[];
document_enabled: boolean;
document_max_size_mb: number;
document_allowed_extensions: string[];
video_enabled: boolean;
video_max_size_mb: number;
video_allowed_extensions: string[];
max_file_count: number;
allowed_transfer_methods: string[] | string;
}
export type FeaturesConfigForm = {
file_upload: FileSetttings & {
enabled: boolean;
settings?: FileSetttings
};
opening_statement: {
enabled: boolean;
statement: string | null;
suggested_questions: string[];
};
suggested_questions_after_answer: {
enabled: boolean;
};
text_to_speech: {
enabled: boolean;
voice: string | null;
language: string | null;
autoplay: boolean;
};
citation: {
enabled: boolean;
};
web_search: {
enabled: boolean;
search_engine: string | null;
};
} }
/** /**
* Function config modal ref methods * Function config modal ref methods
*/ */
export interface FunConfigModalRef { export interface FeaturesConfigModalRef {
/** Open function config modal */ /** Open function config modal */
handleOpen: (value: FunConfigForm) => void; handleOpen: (value: FeaturesConfigForm) => void;
} }
/** /**

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-06 21:09:42 * @Date: 2026-02-06 21:09:42
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-06 12:20:43 * @Last Modified time: 2026-03-17 14:42:31
*/ */
/** /**
* File Upload Component * File Upload Component
@@ -20,7 +20,7 @@
* *
* @component * @component
*/ */
import { useState, useEffect, forwardRef, useImperativeHandle } from 'react'; import { useState, useEffect, forwardRef, useImperativeHandle, useMemo } from 'react';
import { Upload, Progress, App } from 'antd'; import { Upload, Progress, App } from 'antd';
import type { UploadProps, UploadFile } from 'antd'; import type { UploadProps, UploadFile } from 'antd';
import type { UploadProps as RcUploadProps } from 'antd/es/upload/interface'; import type { UploadProps as RcUploadProps } from 'antd/es/upload/interface';
@@ -28,6 +28,7 @@ import { useTranslation } from 'react-i18next';
import { request } from '@/utils/request' import { request } from '@/utils/request'
import { fileUploadUrlWithoutApiPrefix } from '@/api/fileStorage' import { fileUploadUrlWithoutApiPrefix } from '@/api/fileStorage'
import type { FeaturesConfigForm } from '@/views/ApplicationConfig/types';
interface UploadFilesProps extends Omit<UploadProps, 'onChange'> { interface UploadFilesProps extends Omit<UploadProps, 'onChange'> {
/** Upload API endpoint */ /** Upload API endpoint */
@@ -48,14 +49,14 @@ interface UploadFilesProps extends Omit<UploadProps, 'onChange'> {
disabled?: boolean; disabled?: boolean;
/** File size limit in MB */ /** File size limit in MB */
fileSize?: number; fileSize?: number;
/** Allowed file types ['doc', 'xls', 'ppt', 'pdf'] */
fileType?: string[];
/** Auto-upload on file selection, default is true */ /** Auto-upload on file selection, default is true */
isAutoUpload?: boolean; isAutoUpload?: boolean;
/** Maximum number of files allowed */ /** Maximum number of files allowed */
maxCount?: number; maxCount?: number;
/** Custom file removal callback */ /** Custom file removal callback */
onRemove?: (file: UploadFile) => boolean | void | Promise<boolean | void>; onRemove?: (file: UploadFile) => boolean | void | Promise<boolean | void>;
featureConfig: FeaturesConfigForm['file_upload']
} }
const transform_file_type = { const transform_file_type = {
@@ -130,11 +131,11 @@ const UploadFiles = forwardRef<UploadFilesRef, UploadFilesProps>(({
onChange, onChange,
disabled = false, disabled = false,
fileSize = 5, fileSize = 5,
fileType = Object.entries(ALL_FILE_TYPE).map(([key]) => key),
isAutoUpload = true, isAutoUpload = true,
maxCount = 1, maxCount = 1,
onRemove: customOnRemove, onRemove: customOnRemove,
requestConfig, requestConfig,
featureConfig,
...props ...props
}, ref) => { }, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -142,18 +143,37 @@ const UploadFiles = forwardRef<UploadFilesRef, UploadFilesProps>(({
const [fileList, setFileList] = useState<UploadFile[]>(propFileList); const [fileList, setFileList] = useState<UploadFile[]>(propFileList);
const [accept, setAccept] = useState<string | undefined>(); const [accept, setAccept] = useState<string | undefined>();
const fileType = useMemo(() => {
let types: string[] = [];
['image', 'document', 'video', 'audio'].forEach(type => {
if (featureConfig[`${type}_enabled` as keyof FeaturesConfigForm['file_upload']]) {
types = types.concat(featureConfig[`${type}_allowed_extensions` as keyof FeaturesConfigForm['file_upload']] as string[])
}
})
return types
}, [featureConfig])
/** /**
* Validates file type and size before upload * Validates file type and size before upload
* @returns Upload.LIST_IGNORE to prevent upload, or true to proceed * @returns Upload.LIST_IGNORE to prevent upload, or true to proceed
*/ */
const beforeUpload: RcUploadProps['beforeUpload'] = (file) => { const beforeUpload: RcUploadProps['beforeUpload'] = (file) => {
// Validate file size // Determine file category and get max size from featureConfig
if (fileSize) { const mimePrefix = file.type?.split('/')[0]
const isLtMaxSize = (file.size / 1024 / 1024) < fileSize; const categoryMap: Record<string, keyof FeaturesConfigForm['file_upload']> = {
if (!isLtMaxSize) { image: 'image_max_size_mb',
message.error(t('common.fileSizeTip', { size: fileSize })); video: 'video_max_size_mb',
return Upload.LIST_IGNORE; audio: 'audio_max_size_mb',
} }
const maxSizeKey = categoryMap[mimePrefix] ?? 'document_max_size_mb'
const maxSize = (featureConfig[maxSizeKey] as number) ?? fileSize
const fileSizeMB = file.size / 1024 / 1024
const isLtMaxSize = fileSizeMB < maxSize;
if (!isLtMaxSize) {
message.error(t('common.fileSizeTip', { size: maxSize }));
return Upload.LIST_IGNORE;
} }
// Validate file type // Validate file type
if (fileType && fileType.length > 0) { if (fileType && fileType.length > 0) {

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-06 21:09:47 * @Date: 2026-02-06 21:09:47
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-04 17:47:09 * @Last Modified time: 2026-03-17 10:28:04
*/ */
/** /**
* Upload File List Modal Component * Upload File List Modal Component
@@ -18,25 +18,28 @@
* *
* @component * @component
*/ */
import { forwardRef, useImperativeHandle, useState } from 'react'; import { forwardRef, useImperativeHandle, useState, useMemo } from 'react';
import { Form, Input, Select, Button, Flex } from 'antd'; import { Form, Input, Select, Button, Flex } from 'antd';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import type { UploadFileListModalRef } from '../types' import type { UploadFileListModalRef } from '../types'
import RbModal from '@/components/RbModal' import RbModal from '@/components/RbModal'
import type { FeaturesConfigForm } from '@/views/ApplicationConfig/types';
const FormItem = Form.Item; const FormItem = Form.Item;
interface UploadFileListModalProps { interface UploadFileListModalProps {
/** Callback to refresh parent component with new file list */ /** Callback to refresh parent component with new file list */
refresh: (fileList?: any[]) => void; refresh: (fileList?: any[]) => void;
featureConfig: FeaturesConfigForm['file_upload']
} }
/** /**
* Modal for adding remote files via URL * Modal for adding remote files via URL
*/ */
const UploadFileListModal = forwardRef<UploadFileListModalRef, UploadFileListModalProps>(({ const UploadFileListModal = forwardRef<UploadFileListModalRef, UploadFileListModalProps>(({
refresh refresh,
featureConfig
}, ref) => { }, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
@@ -79,6 +82,20 @@ const UploadFileListModal = forwardRef<UploadFileListModalRef, UploadFileListMod
handleOpen handleOpen
})); }));
const fileTypeOptions = useMemo(() => {
const options = [];
if (featureConfig?.image_enabled) {
options.push({ label: t('memoryConversation.image'), value: 'image' });
}
if (featureConfig?.audio_enabled) {
options.push({ label: t('memoryConversation.audio'), value: 'audio' });
}
if (featureConfig?.video_enabled) {
options.push({ label: t('memoryConversation.video'), value: 'video' });
}
return options;
}, [featureConfig, t])
return ( return (
<RbModal <RbModal
title={t('memoryConversation.addRemoteFile')} title={t('memoryConversation.addRemoteFile')}
@@ -103,11 +120,7 @@ const UploadFileListModal = forwardRef<UploadFileListModalRef, UploadFileListMod
> >
<Select <Select
placeholder={t('memoryConversation.fileType')} placeholder={t('memoryConversation.fileType')}
options={[ options={fileTypeOptions}
{ label: t('memoryConversation.image'), value: 'image' },
{ label: t('memoryConversation.audio'), value: 'audio' },
{ label: t('memoryConversation.video'), value: 'video' },
]}
className="rb:w-30" className="rb:w-30"
/> />
</FormItem> </FormItem>

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-03 16:58:03 * @Date: 2026-02-03 16:58:03
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-04 12:10:44 * @Last Modified time: 2026-03-17 15:39:17
*/ */
/** /**
* Conversation Page * Conversation Page
@@ -14,13 +14,12 @@ import { type FC, useState, useEffect, useRef } from 'react'
import { useParams, useLocation } from 'react-router-dom' import { useParams, useLocation } from 'react-router-dom'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import InfiniteScroll from 'react-infinite-scroll-component'; import InfiniteScroll from 'react-infinite-scroll-component';
import { Flex, Skeleton, Form, Dropdown, type MenuProps, App, Divider } from 'antd' import { Flex, Skeleton, App } from 'antd'
import { SettingOutlined } from '@ant-design/icons'
import clsx from 'clsx' import clsx from 'clsx'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { getConversationHistory, sendConversation, getConversationDetail, getShareToken, getExperienceConfig } from '@/api/application' import { getConversationHistory, sendConversation, getConversationDetail, getShareToken, getExperienceConfig } from '@/api/application'
import type { HistoryItem, QueryParams, UploadFileListModalRef } from './types' import type { HistoryItem } from './types'
import Empty from '@/components/Empty' import Empty from '@/components/Empty'
import { formatDateTime } from '@/utils/format'; import { formatDateTime } from '@/utils/format';
import { randomString } from '@/utils/common' import { randomString } from '@/utils/common'
@@ -34,20 +33,14 @@ import OnlineIcon from '@/assets/images/conversation/online.svg'
import OnlineCheckedIcon from '@/assets/images/conversation/onlineChecked.svg' import OnlineCheckedIcon from '@/assets/images/conversation/onlineChecked.svg'
import MemoryFunctionCheckedIcon from '@/assets/images/conversation/memoryFunctionChecked.svg' import MemoryFunctionCheckedIcon from '@/assets/images/conversation/memoryFunctionChecked.svg'
import { type SSEMessage } from '@/utils/stream' import { type SSEMessage } from '@/utils/stream'
import UploadFiles from './components/FileUpload'
import AudioRecorder from '@/components/AudioRecorder'
import { shareFileUploadUrlWithoutApiPrefix } from '@/api/fileStorage' import { shareFileUploadUrlWithoutApiPrefix } from '@/api/fileStorage'
import UploadFileListModal from './components/UploadFileListModal' import ChatToolbar, { type ChatToolbarRef } from '@/components/Chat/ChatToolbar'
import type { VariableConfigModalRef } from '@/views/Workflow/types'
import type { Variable } from '@/views/Workflow/components/Properties/VariableList/types' import type { Variable } from '@/views/Workflow/components/Properties/VariableList/types'
import VariableConfigModal from '@/views/Workflow/components/Chat/VariableConfigModal'; import type { FeaturesConfigForm } from '@/views/ApplicationConfig/types';
/**
* Conversation component for shared applications
*/
const Conversation: FC = () => { const Conversation: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { message: messageApi } = App.useApp() const { message: messageApi, modal } = App.useApp()
const { token } = useParams() const { token } = useParams()
const location = useLocation() const location = useLocation()
const searchParams = new URLSearchParams(location.search) const searchParams = new URLSearchParams(location.search)
@@ -63,35 +56,20 @@ const Conversation: FC = () => {
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true); const [hasMore, setHasMore] = useState(true);
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
const toolbarRef = useRef<ChatToolbarRef>(null)
const [shareToken, setShareToken] = useState<string | null>(localStorage.getItem(`shareToken_${token}`)) const [shareToken, setShareToken] = useState<string | null>(localStorage.getItem(`shareToken_${token}`))
const [fileList, setFileList] = useState<any[]>([])
const [webSearch, setWebSearch] = useState(false)
const [memory, setMemory] = useState(true)
const [features, setFeatures] = useState<FeaturesConfigForm>({} as FeaturesConfigForm)
const [form] = Form.useForm<QueryParams>()
const queryValues = Form.useWatch<QueryParams>([], form)
const uploadFileListModalRef = useRef<UploadFileListModalRef>(null)
const variableConfigModalRef = useRef<VariableConfigModalRef>(null)
const [variables, setVariables] = useState<Variable[]>([]) // Workflow input variables
/**
* Opens the variable configuration modal
*/
const handleEditVariables = () => {
variableConfigModalRef.current?.handleOpen(variables)
}
/**
* Saves updated variable values from the modal
*/
const handleSave = (values: Variable[]) => {
setVariables([...values])
}
useEffect(() => { useEffect(() => {
const shareToken = localStorage.getItem(`shareToken_${token}`) const shareToken = localStorage.getItem(`shareToken_${token}`)
setShareToken(shareToken) setShareToken(shareToken)
if (shareToken && shareToken !== '') return if (shareToken && shareToken !== '') return
getShareToken(token as string, userId || randomString(12, false)) getShareToken(token as string, userId || randomString(12, false))
.then(res => { .then(res => {
const response = res as { access_token: string } || {} const response = res as { access_token: string } || {}
localStorage.setItem(`shareToken_${token}`, response.access_token ?? '') localStorage.setItem(`shareToken_${token}`, response.access_token ?? '')
setShareToken(response.access_token ?? '') setShareToken(response.access_token ?? '')
}) })
@@ -102,12 +80,14 @@ const Conversation: FC = () => {
getHistory() getHistory()
} }
}, [token, shareToken, page, hasMore, historyList]) }, [token, shareToken, page, hasMore, historyList])
useEffect(() => { useEffect(() => {
if (shareToken && token) { if (shareToken && token) {
getExperienceConfig(token) getExperienceConfig(token)
.then(res => { .then(res => {
const response = res as { variables: Variable[] } const response = res as { variables: Variable[]; features: FeaturesConfigForm }
setVariables(response.variables || []) toolbarRef.current?.setVariables(response.variables || [])
setFeatures(response.features)
}) })
} else { } else {
setChatList([]) setChatList([])
@@ -118,7 +98,7 @@ const Conversation: FC = () => {
const groupHistoryByDate = (items: HistoryItem[]): Record<string, HistoryItem[]> => { const groupHistoryByDate = (items: HistoryItem[]): Record<string, HistoryItem[]> => {
return items.reduce((groups: Record<string, HistoryItem[]>, item) => { return items.reduce((groups: Record<string, HistoryItem[]>, item) => {
const date = formatDateTime(item.created_at, 'YYYY-MM-DD') const date = formatDateTime(item.created_at, 'YYYY-MM-DD')
if (!groups[date]) { if (!groups[date]) {
groups[date] = []; groups[date] = [];
} }
@@ -129,9 +109,7 @@ const Conversation: FC = () => {
/** Fetch conversation history with pagination */ /** Fetch conversation history with pagination */
const getHistory = (flag: boolean = false) => { const getHistory = (flag: boolean = false) => {
if (!token || (pageLoading || !hasMore) && !flag) { if (!token || (pageLoading || !hasMore) && !flag) return
return
}
setPageLoading(true); setPageLoading(true);
getConversationHistory(token, { page: flag ? 1 : page, pagesize: 20 }) getConversationHistory(token, { page: flag ? 1 : page, pagesize: 20 })
.then(res => { .then(res => {
@@ -154,19 +132,14 @@ const Conversation: FC = () => {
setHasMore(response.page.hasnext); setHasMore(response.page.hasnext);
setLoading(false); setLoading(false);
}) })
.finally(() => { .finally(() => setPageLoading(false))
setPageLoading(false);
})
} }
/** Switch to different conversation or start new one */ /** Switch to different conversation or start new one */
const handleChangeHistory = (id: string | null) => { const handleChangeHistory = (id: string | null) => {
if (id !== conversation_id) { if (id !== conversation_id) setConversationId(id)
setConversationId(id) if (!id) setMessage('')
}
if (!id) {
setMessage('')
}
} }
useEffect(() => { useEffect(() => {
if (conversation_id) { if (conversation_id) {
getConversationDetail(token as string, conversation_id) getConversationDetail(token as string, conversation_id)
@@ -179,43 +152,38 @@ const Conversation: FC = () => {
} }
}, [conversation_id]) }, [conversation_id])
/** Add user message to chat */
const addUserMessage = (message: string = '', files?: any[]) => { const addUserMessage = (message: string = '', files?: any[]) => {
const newUserMessage: ChatItem = { setChatList(prev => [...prev, {
conversation_id, conversation_id,
role: 'user', role: 'user',
content: message, content: message,
created_at: Date.now(), created_at: Date.now(),
files files
}; }])
setChatList(prev => [...prev, newUserMessage])
} }
/** Add empty assistant message placeholder */
const addAssistantMessage = () => { const addAssistantMessage = () => {
const newAssistantMessage: ChatItem = { setChatList(prev => [...prev, {
created_at: Date.now(), created_at: Date.now(),
role: 'assistant', role: 'assistant',
content: '', content: ''
} }])
setChatList(prev => [...prev, newAssistantMessage])
} }
/** Update assistant message with streaming content */
const updateAssistantMessage = (content: string = '') => {
if (!content) return
if (streamLoading) {
setStreamLoading(false)
}
const updateAssistantMessage = (content: string = '', audio_url?: string) => {
if (!content && !audio_url) return
if (streamLoading) setStreamLoading(false)
setChatList(prev => { setChatList(prev => {
const lastList = [...prev] const lastList = [...prev]
const lastIndex = lastList.length - 1 const lastIndex = lastList.length - 1
const lastMsg = lastList[lastIndex] const lastMsg = lastList[lastIndex]
if (lastMsg?.role === 'assistant') { if (lastMsg?.role === 'assistant') {
return [ return [
...lastList.slice(0, lastList.length - 1), ...lastList.slice(0, lastIndex),
{ {
...lastMsg, ...lastMsg,
content: lastMsg.content + content content: lastMsg.content + content,
audioUrl: audio_url
} }
] ]
} }
@@ -223,22 +191,17 @@ const Conversation: FC = () => {
}) })
} }
const isNeedVariableConfig = variables.some(vo => vo.required && (vo.value === null || vo.value === undefined || vo.value === ''))
/** Send message and handle streaming response */ /** Send message and handle streaming response */
const handleSend = () => { const handleSend = () => {
if (!token || !shareToken) { if (!token || !shareToken) return
return const files = toolbarRef.current?.getFiles() || []
} const variables = toolbarRef.current?.getVariables() || []
const { files = [], ...rest } = queryValues || {}
// Validate required variables before sending
let isCanSend = true let isCanSend = true
const params: Record<string, any> = {} const params: Record<string, any> = {}
if (variables.length > 0) { if (variables.length > 0) {
const needRequired: string[] = [] const needRequired: string[] = []
variables.forEach(vo => { variables.forEach(vo => {
params[vo.name] = vo.value ?? vo.defaultValue params[vo.name] = vo.value ?? vo.defaultValue
if (vo.required && (params[vo.name] === null || params[vo.name] === undefined || params[vo.name] === '')) { if (vo.required && (params[vo.name] === null || params[vo.name] === undefined || params[vo.name] === '')) {
isCanSend = false isCanSend = false
needRequired.push(vo.name) needRequired.push(vo.name)
@@ -249,33 +212,34 @@ const Conversation: FC = () => {
messageApi.error(`${needRequired.join(',')} ${t('workflow.variableRequired')}`) messageApi.error(`${needRequired.join(',')} ${t('workflow.variableRequired')}`)
} }
} }
if (!isCanSend) { if (!isCanSend) return
return
}
setLoading(true) setLoading(true)
setStreamLoading(true) setStreamLoading(true)
addUserMessage(message, files) addUserMessage(message, files)
addAssistantMessage() addAssistantMessage()
toolbarRef.current?.setFiles([])
setFileList([])
let currentConversationId: string | null = null let currentConversationId: string | null = null
const handleStreamMessage = (data: SSEMessage[]) => { const handleStreamMessage = (data: SSEMessage[]) => {
data.forEach((item) => { data.forEach((item) => {
switch(item.event) { const { content, conversation_id: curId, audio_url } = item.data as { content: string; conversation_id: string; audio_url?: string; }
switch (item.event) {
case 'start': case 'start':
case 'node_start': case 'node_start':
const { conversation_id: newId } = item.data as { conversation_id: string } const { conversation_id: newId } = item.data as { conversation_id: string }
currentConversationId = newId currentConversationId = newId
break break
case 'message': case 'message':
const { content, conversation_id: curId } = item.data as { content: string; conversation_id: string; } updateAssistantMessage(content, audio_url)
updateAssistantMessage(content) if (curId) currentConversationId = curId;
if (curId) {
currentConversationId = curId;
}
break break
case 'end': case 'end':
case 'workflow_end': case 'workflow_end':
if (audio_url) {
updateAssistantMessage(content, audio_url)
}
setLoading(false) setLoading(false)
if (currentConversationId && currentConversationId !== conversation_id) { if (currentConversationId && currentConversationId !== conversation_id) {
setConversationId(currentConversationId) setConversationId(currentConversationId)
@@ -286,9 +250,9 @@ const Conversation: FC = () => {
}) })
}; };
form.setFieldValue('files', [])
sendConversation({ sendConversation({
...rest, web_search: webSearch,
memory,
message: message || '', message: message || '',
stream: true, stream: true,
conversation_id: conversation_id || null, conversation_id: conversation_id || null,
@@ -315,32 +279,18 @@ const Conversation: FC = () => {
}) })
} }
const fileChange = (file?: any) => { const handleChangeMemory = (value: boolean) => {
form.setFieldValue('files', [...(queryValues.files || []), file]) modal.confirm({
} title: value ? t('memoryConversation.memoryTipTitle') : t('memoryConversation.memoryCancelTipTitle'),
const handleRecordingComplete = async (file: any) => { okText: t('common.confirm'),
form.setFieldValue('files', [...(queryValues.files || []), { cancelText: t('common.cancel'),
uid: file.file_id, onOk: () => {
response: { data: file }, setMemory(value)
thumbUrl: file.url, },
type: file.type onCancel: () => {
}]) setMemory(!value)
} }
})
const handleShowUpload: MenuProps['onClick'] = ({ key }) => {
switch(key) {
case 'define':
uploadFileListModalRef.current?.handleOpen()
break
}
}
const addFileList = (fileList?: any[]) => {
if (!fileList || fileList.length <= 0) return
form.setFieldValue('files', [...(queryValues.files || []), ...fileList])
}
const updateFileList = (fileList?: any[]) => {
console.log('fileList', fileList)
form.setFieldValue('files', [...(fileList || [])])
} }
return ( return (
@@ -349,8 +299,8 @@ const Conversation: FC = () => {
<div className="rb:group rb:flex rb:items-center rb:justify-center rb:font-regular rb:cursor-pointer rb:mb-5 rb:border rb:border-[#DFE4ED] rb:hover:border-[#155EEF] rb:hover:text-[#155EEF] rb:rounded-lg rb:py-2.5" <div className="rb:group rb:flex rb:items-center rb:justify-center rb:font-regular rb:cursor-pointer rb:mb-5 rb:border rb:border-[#DFE4ED] rb:hover:border-[#155EEF] rb:hover:text-[#155EEF] rb:rounded-lg rb:py-2.5"
onClick={() => handleChangeHistory(null)} onClick={() => handleChangeHistory(null)}
> >
<div <div
className="rb:w-5 rb:h-5 rb:cursor-pointer rb:mr-2 rb:bg-cover rb:bg-[url('@/assets/images/conversation/conversation.svg')] rb:group-hover:bg-[url('@/assets/images/conversation/conversation_hover.svg')]" className="rb:w-5 rb:h-5 rb:cursor-pointer rb:mr-2 rb:bg-cover rb:bg-[url('@/assets/images/conversation/conversation.svg')] rb:group-hover:bg-[url('@/assets/images/conversation/conversation_hover.svg')]"
></div> ></div>
{t('memoryConversation.startANewConversation')} {t('memoryConversation.startANewConversation')}
</div> </div>
@@ -365,7 +315,6 @@ const Conversation: FC = () => {
next={getHistory} next={getHistory}
hasMore={hasMore} hasMore={hasMore}
loader={<Skeleton active />} loader={<Skeleton active />}
// endMessage={<Divider plain>It is all, nothing more 🤐</Divider>}
scrollableTarget="scrollableDiv" scrollableTarget="scrollableDiv"
> >
{Object.entries(groupHistoryList).map(([date, items]) => ( {Object.entries(groupHistoryList).map(([date, items]) => (
@@ -374,8 +323,8 @@ const Conversation: FC = () => {
{items.map(item => ( {items.map(item => (
<div key={item.updated_at} className="rb:mb-3"> <div key={item.updated_at} className="rb:mb-3">
<div className={clsx("rb:p-[8px_13px] rb:rounded-lg rb:leading-5 rb:cursor-pointer rb:hover:bg-[#F0F3F8]", { <div className={clsx("rb:p-[8px_13px] rb:rounded-lg rb:leading-5 rb:cursor-pointer rb:hover:bg-[#F0F3F8]", {
'rb:bg-[#FFFFFF] rb:shadow-[0px_2px_4px_0px_rgba(0,0,0,0.15)] rb:font-medium rb:hover:bg-[#FFFFFF]!': item.id === conversation_id, 'rb:bg-[#FFFFFF] rb:shadow-[0px_2px_4px_0px_rgba(0,0,0,0.15)] rb:font-medium rb:hover:bg-[#FFFFFF]!': item.id === conversation_id,
})} })}
onClick={() => handleChangeHistory(item.id)} onClick={() => handleChangeHistory(item.id)}
> >
{item.title} {item.title}
@@ -391,109 +340,60 @@ const Conversation: FC = () => {
</div> </div>
<div className="rb:relative rb:h-screen rb:px-4 rb:flex-[1_1_auto]"> <div className="rb:relative rb:h-screen rb:px-4 rb:flex-[1_1_auto]">
<div className='rb:w-190 rb:h-screen rb:mx-auto rb:pt-10'> <div className='rb:w-190 rb:h-screen rb:mx-auto rb:pt-10'>
<Chat <Chat
empty={<Empty url={ChatEmpty} className="rb:h-full" size={[320,180]} title={t('memoryConversation.chatEmpty')} subTitle={t('memoryConversation.emptyDesc')} />} empty={<Empty url={ChatEmpty} className="rb:h-full" size={[320, 180]} title={t('memoryConversation.chatEmpty')} subTitle={t('memoryConversation.emptyDesc')} />}
contentClassName={!queryValues?.files?.length ? "rb:h-[calc(100%-144px)]" : "rb:h-[calc(100%-208px)]"} contentClassName={!fileList.length ? "rb:h-[calc(100%-144px)]" : "rb:h-[calc(100%-208px)]"}
data={chatList} data={chatList}
streamLoading={streamLoading} streamLoading={streamLoading}
loading={loading} loading={loading}
onChange={setMessage} onChange={setMessage}
onSend={handleSend} onSend={handleSend}
labelFormat={(item) => dayjs(item.created_at).locale('en').format('MMMM D, YYYY [at] h:mm A')} labelFormat={(item) => dayjs(item.created_at).locale('en').format('MMMM D, YYYY [at] h:mm A')}
fileList={queryValues?.files || []} fileList={fileList}
fileChange={updateFileList} fileChange={(list) => {
> setFileList(list || [])
<Form form={form} initialValues={{ memory: false, web_search: false}}> toolbarRef.current?.setFiles(list || [])
<Flex justify="space-between" className="rb:flex-1"> }}
<Flex gap={8} align="center"> >
<Form.Item name="files" noStyle> <ChatToolbar
<Dropdown ref={toolbarRef}
menu={{ features={features}
items: [ onFilesChange={setFileList}
{ key: 'define', label: t('memoryConversation.addRemoteFile') }, uploadAction={shareFileUploadUrlWithoutApiPrefix}
{ uploadRequestConfig={{
key: 'upload', label: ( headers: {
<UploadFiles 'Content-Type': 'multipart/form-data',
action={shareFileUploadUrlWithoutApiPrefix} Authorization: `Bearer ${shareToken || ''}`,
onChange={fileChange} }
requestConfig={{ }}
headers: { extra={
'Content-Type': 'multipart/form-data', <>
Authorization: `Bearer ${shareToken || ''}`, {features.web_search?.enabled &&
}}}
/>
)
},
],
onClick: handleShowUpload
}}
>
<div
className="rb:size-6 rb:cursor-pointer rb:bg-cover rb:bg-[url('@/assets/images/conversation/link.svg')] rb:hover:bg-[url('@/assets/images/conversation/link_hover.svg')]"
></div>
</Dropdown>
</Form.Item>
<Form.Item name="web_search" valuePropName="checked" className="rb:mb-0!">
<ButtonCheckbox <ButtonCheckbox
icon={OnlineIcon} icon={OnlineIcon}
checkedIcon={OnlineCheckedIcon} checkedIcon={OnlineCheckedIcon}
checked={webSearch}
onChange={setWebSearch}
> >
{t(`memoryConversation.web_search`)} {t('memoryConversation.web_search')}
</ButtonCheckbox> </ButtonCheckbox>
</Form.Item> }
<Form.Item name="memory" valuePropName="checked" className="rb:mb-0!"> <ButtonCheckbox
<ButtonCheckbox icon={MemoryFunctionIcon}
icon={MemoryFunctionIcon} checkedIcon={MemoryFunctionCheckedIcon}
checkedIcon={MemoryFunctionCheckedIcon} checked={memory}
> onChange={handleChangeMemory}
{t(`memoryConversation.memory`)} >
</ButtonCheckbox> {t('memoryConversation.memory')}
</Form.Item> </ButtonCheckbox>
{variables.length > 0 && ( </>
<Form.Item name="variables" className="rb:mb-0!"> }
<div />
className={clsx("rb:flex rb:items-center rb:border rb:rounded-lg rb:px-2 rb:text-[12px] rb:h-6 rb:cursor-pointer rb:hover:bg-[#F0F3F8] rb:text-[#212332]", { </Chat>
'rb:border-[#FF5D34] rb:text-[#FF5D34]': isNeedVariableConfig,
'rb:border-[#DFE4ED]': !isNeedVariableConfig,
})}
onClick={handleEditVariables}
>
<SettingOutlined className="rb:mr-1" />
{t(`memoryConversation.variableConfig`)}
</div>
</Form.Item>
)}
</Flex>
<Flex align="center">
<AudioRecorder
action={shareFileUploadUrlWithoutApiPrefix}
requestConfig={{
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${shareToken || ''}`,
}
}}
onRecordingComplete={handleRecordingComplete}
/>
<Divider type="vertical" className="rb:ml-1.5! rb:mr-3!" />
</Flex>
</Flex>
</Form>
</Chat>
</div> </div>
</div> </div>
<UploadFileListModal
ref={uploadFileListModalRef}
refresh={addFileList}
/>
<VariableConfigModal
ref={variableConfigModalRef}
refresh={handleSave}
variables={variables}
/>
</Flex> </Flex>
) )
} }
export default Conversation export default Conversation

View File

@@ -2,7 +2,7 @@
* @Author: ZhaoYing * @Author: ZhaoYing
* @Date: 2026-02-06 21:10:56 * @Date: 2026-02-06 21:10:56
* @Last Modified by: ZhaoYing * @Last Modified by: ZhaoYing
* @Last Modified time: 2026-03-04 18:51:48 * @Last Modified time: 2026-03-17 15:05:21
*/ */
/** /**
* Workflow Chat Component * Workflow Chat Component
@@ -21,50 +21,56 @@
* *
* @component * @component
*/ */
import { forwardRef, useImperativeHandle, useState, useRef } from 'react' import { forwardRef, useImperativeHandle, useState, useRef, useEffect, useCallback } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { App, Space, Button, Flex, Dropdown, type MenuProps, Divider } from 'antd' import { App } from 'antd'
import ChatIcon from '@/assets/images/application/chat.png' import ChatIcon from '@/assets/images/application/chat.png'
import RbDrawer from '@/components/RbDrawer'; import RbDrawer from '@/components/RbDrawer';
import VariableConfigModal from './VariableConfigModal'
import { draftRun } from '@/api/application'; import { draftRun } from '@/api/application';
import Empty from '@/components/Empty' import Empty from '@/components/Empty'
import ChatContent from '@/components/Chat/ChatContent' import ChatContent from '@/components/Chat/ChatContent'
import type { ChatItem } from '@/components/Chat/types' import type { ChatItem } from '@/components/Chat/types'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import type { ChatRef, VariableConfigModalRef, GraphRef } from '../../types' import type { ChatRef, GraphRef, WorkflowConfig } from '../../types'
import { type SSEMessage } from '@/utils/stream' import { type SSEMessage } from '@/utils/stream'
import type { Variable } from '../Properties/VariableList/types' import type { Variable } from '../Properties/VariableList/types'
import ChatInput from '@/components/Chat/ChatInput' import ChatInput from '@/components/Chat/ChatInput'
import UploadFiles from '@/views/Conversation/components/FileUpload' import ChatToolbar from '@/components/Chat/ChatToolbar'
import AudioRecorder from '@/components/AudioRecorder' import type { ChatToolbarRef } from '@/components/Chat/ChatToolbar'
import UploadFileListModal from '@/views/Conversation/components/UploadFileListModal'
import type { UploadFileListModalRef } from '@/views/Conversation/types'
import Runtime from './Runtime'; import Runtime from './Runtime';
import type { FeaturesConfigForm } from '@/views/ApplicationConfig/types';
const Chat = forwardRef<ChatRef, { appId: string; graphRef: GraphRef }>(({ appId, graphRef }, ref) => { const Chat = forwardRef<ChatRef, { appId: string; graphRef: GraphRef; data: WorkflowConfig | null }>(({ appId, graphRef, data }, ref) => {
const { t } = useTranslation() const { t } = useTranslation()
const { message: messageApi } = App.useApp() const { message: messageApi } = App.useApp()
const variableConfigModalRef = useRef<VariableConfigModalRef>(null) const toolbarRef = useRef<ChatToolbarRef>(null)
// State management const toolbarCallbackRef = useCallback((node: ChatToolbarRef | null) => {
const [open, setOpen] = useState(false) // Drawer visibility (toolbarRef as React.MutableRefObject<ChatToolbarRef | null>).current = node
const [loading, setLoading] = useState(false) // Send button loading state }, [])
const [chatList, setChatList] = useState<ChatItem[]>([]) // Chat message history const [open, setOpen] = useState(false)
const [variables, setVariables] = useState<Variable[]>([]) // Workflow input variables const [loading, setLoading] = useState(false)
const [streamLoading, setStreamLoading] = useState(false) // SSE streaming state const [chatList, setChatList] = useState<ChatItem[]>([])
const [conversationId, setConversationId] = useState<string | null>(null) // Current conversation ID const [variables, setVariables] = useState<Variable[]>([])
const [fileList, setFileList] = useState<any[]>([]) // Uploaded files const [streamLoading, setStreamLoading] = useState(false)
const [message, setMessage] = useState<string | undefined>(undefined) // Current input message const [conversationId, setConversationId] = useState<string | null>(null)
const uploadFileListModalRef = useRef<UploadFileListModalRef>(null) const [fileList, setFileList] = useState<any[]>([])
const [message, setMessage] = useState<string | undefined>(undefined)
const [features, setFeatures] = useState<FeaturesConfigForm>({} as FeaturesConfigForm)
/** /**
* Opens the chat drawer and loads workflow variables from the start node * Opens the chat drawer and loads workflow variables from the start node
*/ */
const handleOpen = () => { const handleOpen = () => {
setOpen(true) setOpen(true)
getVariables() if (data?.features) setFeatures(data.features)
} }
useEffect(() => {
if (open && graphRef.current && toolbarRef.current) {
getVariables()
}
}, [open])
/** /**
* Extracts variables from the workflow's start node and merges with previous values * Extracts variables from the workflow's start node and merges with previous values
*/ */
@@ -84,7 +90,9 @@ const Chat = forwardRef<ChatRef, { appId: string; graphRef: GraphRef }>(({ appId
vo.value = lastVo.value vo.value = lastVo.value
} }
}) })
setVariables(curVariables) console.log('curVariables', curVariables)
setVariables([...curVariables])
toolbarRef.current?.setVariables([...curVariables])
} }
} }
/** /**
@@ -96,22 +104,12 @@ const Chat = forwardRef<ChatRef, { appId: string; graphRef: GraphRef }>(({ appId
setVariables([]) setVariables([])
setConversationId(null) setConversationId(null)
setMessage(undefined) setMessage(undefined)
toolbarRef.current?.setFiles([])
toolbarRef.current?.setVariables([])
setFileList([]) setFileList([])
setLoading(false) setLoading(false)
setStreamLoading(false) setStreamLoading(false)
} }
/**
* Opens the variable configuration modal
*/
const handleEditVariables = () => {
variableConfigModalRef.current?.handleOpen(variables)
}
/**
* Saves updated variable values from the modal
*/
const handleSave = (values: Variable[]) => {
setVariables([...values])
}
/** /**
* Sends a message to execute the workflow * Sends a message to execute the workflow
* *
@@ -337,14 +335,16 @@ const Chat = forwardRef<ChatRef, { appId: string; graphRef: GraphRef }>(({ appId
}) })
} }
const files = toolbarRef.current?.getFiles() || []
setMessage(undefined) setMessage(undefined)
toolbarRef.current?.setFiles([])
setFileList([]) setFileList([])
const data = { const data = {
message: message, message: message,
variables: params, variables: params,
stream: true, stream: true,
conversation_id: conversationId, conversation_id: conversationId,
files: fileList.map(file => { files: files.map(file => {
if (file.url) { if (file.url) {
return file return file
} else { } else {
@@ -379,65 +379,20 @@ const Chat = forwardRef<ChatRef, { appId: string; graphRef: GraphRef }>(({ appId
}) })
} }
/**
* Updates the current input message
*/
const handleMessageChange = (message: string) => {
setMessage(message)
}
/**
* Handles file upload from local device
*/
const fileChange = (file?: any) => {
setFileList([...fileList, file])
}
const handleRecordingComplete = async (file: any) => {
setFileList([...fileList, {
response: { data: file },
thumbUrl: file.url,
type: file.type
}])
}
/**
* Handles dropdown menu actions for file upload
*/
const handleShowUpload: MenuProps['onClick'] = ({ key }) => {
switch(key) {
case 'define':
uploadFileListModalRef.current?.handleOpen()
break
}
}
/**
* Adds files from remote URL modal
*/
const addFileList = (list?: any[]) => {
if (!list || list.length <= 0) return
setFileList([...fileList, ...(list || [])])
}
/**
* Updates the entire file list (used when removing files)
*/
const updateFileList = (list?: any[]) => { const updateFileList = (list?: any[]) => {
setFileList([...list || []]) setFileList([...list || []])
toolbarRef.current?.setFiles([...list || []])
} }
// Expose methods to parent component via ref
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
handleOpen, handleOpen,
handleClose handleClose
})); }));
console.log('fileList', fileList)
return ( return (
<RbDrawer <RbDrawer
title={<div className="rb:flex rb:items-center rb:gap-2.5"> title={<div className="rb:flex rb:items-center rb:gap-2.5">
{t('workflow.run')} {t('workflow.run')}
{variables.length > 0 && <Space>
<Button size="small" onClick={handleEditVariables}>{t('application.variable')}</Button>
</Space>}
</div>} </div>}
classNames={{ classNames={{
body: 'rb:p-0!' body: 'rb:p-0!'
@@ -466,48 +421,16 @@ const Chat = forwardRef<ChatRef, { appId: string; graphRef: GraphRef }>(({ appId
fileChange={updateFileList} fileChange={updateFileList}
fileList={fileList} fileList={fileList}
onSend={handleSend} onSend={handleSend}
onChange={handleMessageChange} onChange={(msg) => setMessage(msg)}
> >
<Flex justify="space-between" className="rb:flex-1"> <ChatToolbar
<Flex gap={8} align="center"> ref={toolbarCallbackRef}
<Dropdown features={features}
menu={{ onFilesChange={setFileList}
items: [ onVariablesChange={setVariables}
{ key: 'define', label: t('memoryConversation.addRemoteFile') }, />
{
key: 'upload', label: (
<UploadFiles
onChange={fileChange}
/>
)
},
],
onClick: handleShowUpload
}}
>
<div
className="rb:size-6 rb:cursor-pointer rb:bg-cover rb:bg-[url('@/assets/images/conversation/link.svg')] rb:hover:bg-[url('@/assets/images/conversation/link_hover.svg')]"
></div>
</Dropdown>
</Flex>
<Flex align="center">
<AudioRecorder onRecordingComplete={handleRecordingComplete} />
<Divider type="vertical" className="rb:ml-1.5! rb:mr-3!" />
</Flex>
</Flex>
</ChatInput> </ChatInput>
</div> </div>
<VariableConfigModal
ref={variableConfigModalRef}
refresh={handleSave}
variables={variables}
/>
<UploadFileListModal
ref={uploadFileListModalRef}
refresh={addFileList}
/>
</RbDrawer> </RbDrawer>
) )
}) })

View File

@@ -61,7 +61,7 @@ const Workflow = forwardRef<WorkflowRef>((_props, ref) => {
graphRef, graphRef,
addVariable, addVariable,
config, config,
funConfig: config?.funConfig features: config?.features
})) }))
return ( return (
<div className="rb:h-[calc(100vh-64px)] rb:relative"> <div className="rb:h-[calc(100vh-64px)] rb:relative">
@@ -115,6 +115,7 @@ const Workflow = forwardRef<WorkflowRef>((_props, ref) => {
/> />
<Chat <Chat
ref={chatRef} ref={chatRef}
data={config}
graphRef={graphRef} graphRef={graphRef}
appId={config?.app_id as string} appId={config?.app_id as string}
/> />

View File

@@ -2,7 +2,7 @@
import { Graph } from '@antv/x6'; import { Graph } from '@antv/x6';
import type { KnowledgeConfig } from './components/Properties/Knowledge/types' import type { KnowledgeConfig } from './components/Properties/Knowledge/types'
import type { Variable } from './components/Properties/VariableList/types' import type { Variable } from './components/Properties/VariableList/types'
import type { FunConfigForm } from '@/views/ApplicationConfig/types' import type { FeaturesConfigForm } from '@/views/ApplicationConfig/types'
export interface NodeConfig { export interface NodeConfig {
type: 'input' | 'textarea' | 'select' | 'inputNumber' | 'slider' | 'customSelect' | 'define' | 'knowledge' | 'variableList' | string; type: 'input' | 'textarea' | 'select' | 'inputNumber' | 'slider' | 'customSelect' | 'define' | 'knowledge' | 'variableList' | string;
placeholder?: string; placeholder?: string;
@@ -91,7 +91,7 @@ export interface WorkflowConfig {
created_at: number; created_at: number;
updated_at: number; updated_at: number;
funConfig?: FunConfigForm; features?: FeaturesConfigForm;
} }
export interface ChatRef { export interface ChatRef {