feat: last run frontend (#21369)

The frontend of feat: Persist Variables for Enhanced Debugging Workflow (#20699).

Co-authored-by: jZonG <jzongcode@gmail.com>
This commit is contained in:
Joel
2025-06-24 09:10:30 +08:00
committed by GitHub
parent 10b738a296
commit 1a1bfd4048
122 changed files with 5888 additions and 2061 deletions

View File

@@ -1,4 +1,4 @@
import React, { type FC, useCallback, useEffect, useRef } from 'react'
import React, { type FC, useCallback, useEffect, useMemo, useRef } from 'react'
import useTheme from '@/hooks/use-theme'
import { Theme } from '@/types/app'
import classNames from '@/utils/classnames'
@@ -14,6 +14,7 @@ type CodeEditorProps = {
showFormatButton?: boolean
editorWrapperClassName?: string
readOnly?: boolean
hideTopMenu?: boolean
} & React.HTMLAttributes<HTMLDivElement>
const CodeEditor: FC<CodeEditorProps> = ({
@@ -22,12 +23,14 @@ const CodeEditor: FC<CodeEditorProps> = ({
showFormatButton = true,
editorWrapperClassName,
readOnly = false,
hideTopMenu = false,
className,
}) => {
const { t } = useTranslation()
const { theme } = useTheme()
const monacoRef = useRef<any>(null)
const editorRef = useRef<any>(null)
const [isMounted, setIsMounted] = React.useState(false)
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
@@ -63,6 +66,7 @@ const CodeEditor: FC<CodeEditorProps> = ({
},
})
monaco.editor.setTheme('light-theme')
setIsMounted(true)
}, [])
const formatJsonContent = useCallback(() => {
@@ -75,6 +79,11 @@ const CodeEditor: FC<CodeEditorProps> = ({
onUpdate?.(value)
}, [onUpdate])
const editorTheme = useMemo(() => {
if (theme === Theme.light)
return 'light-theme'
return 'dark-theme'
}, [theme])
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
editorRef.current?.layout()
@@ -89,39 +98,39 @@ const CodeEditor: FC<CodeEditorProps> = ({
}, [])
return (
<div className={classNames('flex flex-col h-full bg-components-input-bg-normal overflow-hidden', className)}>
<div className='flex items-center justify-between pl-2 pr-1 pt-1'>
<div className='system-xs-semibold-uppercase py-0.5 text-text-secondary'>
<span className='px-1 py-0.5'>JSON</span>
</div>
<div className='flex items-center gap-x-0.5'>
{showFormatButton && (
<Tooltip popupContent={t('common.operation.format')}>
<div className={classNames('flex flex-col h-full bg-components-input-bg-normal overflow-hidden', hideTopMenu && 'pt-2', className)}>
{!hideTopMenu && (
<div className='flex items-center justify-between pl-2 pr-1 pt-1'>
<div className='system-xs-semibold-uppercase py-0.5 text-text-secondary'>
<span className='px-1 py-0.5'>JSON</span>
</div>
<div className='flex items-center gap-x-0.5'>
{showFormatButton && (
<Tooltip popupContent={t('common.operation.format')}>
<button
type='button'
className='flex h-6 w-6 items-center justify-center'
onClick={formatJsonContent}
>
<RiIndentIncrease className='h-4 w-4 text-text-tertiary' />
</button>
</Tooltip>
)}
<Tooltip popupContent={t('common.operation.copy')}>
<button
type='button'
className='flex h-6 w-6 items-center justify-center'
onClick={formatJsonContent}
>
<RiIndentIncrease className='h-4 w-4 text-text-tertiary' />
onClick={() => copy(value)}>
<RiClipboardLine className='h-4 w-4 text-text-tertiary' />
</button>
</Tooltip>
)}
<Tooltip popupContent={t('common.operation.copy')}>
<button
type='button'
className='flex h-6 w-6 items-center justify-center'
onClick={() => copy(value)}>
<RiClipboardLine className='h-4 w-4 text-text-tertiary' />
</button>
</Tooltip>
</div>
</div>
</div>
<div
ref={containerRef}
className={classNames('relative overflow-hidden', editorWrapperClassName)}
>
)}
<div className={classNames('relative overflow-hidden', editorWrapperClassName)}>
<Editor
defaultLanguage='json'
theme={isMounted ? editorTheme : 'default-theme'} // sometimes not load the default theme
value={value}
onChange={handleEditorChange}
onMount={handleEditorDidMount}

View File

@@ -1,21 +1,30 @@
import React, { type FC } from 'react'
import CodeEditor from './code-editor'
import cn from '@/utils/classnames'
type SchemaEditorProps = {
schema: string
onUpdate: (schema: string) => void
hideTopMenu?: boolean
className?: string
readonly?: boolean
}
const SchemaEditor: FC<SchemaEditorProps> = ({
schema,
onUpdate,
hideTopMenu,
className,
readonly = false,
}) => {
return (
<CodeEditor
className='grow rounded-xl'
readOnly={readonly}
className={cn('grow rounded-xl', className)}
editorWrapperClassName='grow'
value={schema}
onUpdate={onUpdate}
hideTopMenu={hideTopMenu}
/>
)
}

View File

@@ -1,8 +1,29 @@
// import { RETRIEVAL_OUTPUT_STRUCT } from '../../constants'
import { BlockEnum, EditionType } from '../../types'
import { type NodeDefault, type PromptItem, PromptRole } from '../../types'
import type { LLMNodeType } from './types'
import { ALL_CHAT_AVAILABLE_BLOCKS, ALL_COMPLETION_AVAILABLE_BLOCKS } from '@/app/components/workflow/blocks'
const RETRIEVAL_OUTPUT_STRUCT = `{
"content": "",
"title": "",
"url": "",
"icon": "",
"metadata": {
"dataset_id": "",
"dataset_name": "",
"document_id": [],
"document_name": "",
"document_data_source_type": "",
"segment_id": "",
"segment_position": "",
"segment_word_count": "",
"segment_hit_count": "",
"segment_index_node_hash": "",
"score": ""
}
}`
const i18nPrefix = 'workflow.errorMsg'
const nodeDefault: NodeDefault<LLMNodeType> = {
@@ -27,6 +48,10 @@ const nodeDefault: NodeDefault<LLMNodeType> = {
enabled: false,
},
},
defaultRunInputData: {
'#context#': [RETRIEVAL_OUTPUT_STRUCT],
'#files#': [],
},
getAvailablePrevNodes(isChatMode: boolean) {
const nodes = isChatMode
? ALL_CHAT_AVAILABLE_BLOCKS

View File

@@ -5,7 +5,6 @@ import MemoryConfig from '../_base/components/memory-config'
import VarReferencePicker from '../_base/components/variable/var-reference-picker'
import ConfigVision from '../_base/components/config-vision'
import useConfig from './use-config'
import { findVariableWhenOnLLMVision } from '../utils'
import type { LLMNodeType } from './types'
import ConfigPrompt from './components/config-prompt'
import VarList from '@/app/components/workflow/nodes/_base/components/variable/var-list'
@@ -14,10 +13,7 @@ import Field from '@/app/components/workflow/nodes/_base/components/field'
import Split from '@/app/components/workflow/nodes/_base/components/split'
import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'
import { InputVarType, type NodePanelProps } from '@/app/components/workflow/types'
import BeforeRunForm from '@/app/components/workflow/nodes/_base/components/before-run-form'
import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'
import ResultPanel from '@/app/components/workflow/run/result-panel'
import type { NodePanelProps } from '@/app/components/workflow/types'
import Tooltip from '@/app/components/base/tooltip'
import Editor from '@/app/components/workflow/nodes/_base/components/prompt/editor'
import StructureOutput from './components/structure-output'
@@ -31,7 +27,6 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({
data,
}) => {
const { t } = useTranslation()
const {
readOnly,
inputs,
@@ -58,80 +53,16 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({
handleMemoryChange,
handleVisionResolutionEnabledChange,
handleVisionResolutionChange,
isShowSingleRun,
hideSingleRun,
inputVarValues,
setInputVarValues,
visionFiles,
setVisionFiles,
contexts,
setContexts,
runningStatus,
isModelSupportStructuredOutput,
structuredOutputCollapsed,
setStructuredOutputCollapsed,
handleStructureOutputEnableChange,
handleStructureOutputChange,
handleRun,
handleStop,
varInputs,
runResult,
filterJinjia2InputVar,
} = useConfig(id, data)
const model = inputs.model
const singleRunForms = (() => {
const forms: FormProps[] = []
if (varInputs.length > 0) {
forms.push(
{
label: t(`${i18nPrefix}.singleRun.variable`)!,
inputs: varInputs,
values: inputVarValues,
onChange: setInputVarValues,
},
)
}
if (inputs.context?.variable_selector && inputs.context?.variable_selector.length > 0) {
forms.push(
{
label: t(`${i18nPrefix}.context`)!,
inputs: [{
label: '',
variable: '#context#',
type: InputVarType.contexts,
required: false,
}],
values: { '#context#': contexts },
onChange: keyValue => setContexts(keyValue['#context#']),
},
)
}
if (isVisionModel && data.vision?.enabled && data.vision?.configs?.variable_selector) {
const currentVariable = findVariableWhenOnLLMVision(data.vision.configs.variable_selector, availableVars)
forms.push(
{
label: t(`${i18nPrefix}.vision`)!,
inputs: [{
label: currentVariable?.variable as any,
variable: '#files#',
type: currentVariable?.formType as any,
required: false,
}],
values: { '#files#': visionFiles },
onChange: keyValue => setVisionFiles((keyValue as any)['#files#']),
},
)
}
return forms
})()
const handleModelChange = useCallback((model: {
provider: string
modelId: string
@@ -344,18 +275,6 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({
)}
</>
</OutputVars>
{isShowSingleRun && (
<BeforeRunForm
nodeName={inputs.title}
nodeType={inputs.type}
onHide={hideSingleRun}
forms={singleRunForms}
runningStatus={runningStatus}
onRun={handleRun}
onStop={handleStop}
result={<ResultPanel {...runResult} showSteps={false} />}
/>
)}
</div>
)
}

View File

@@ -16,9 +16,8 @@ import {
ModelTypeEnum,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
import useOneStepRun from '@/app/components/workflow/nodes/_base/hooks/use-one-step-run'
import { RETRIEVAL_OUTPUT_STRUCT } from '@/app/components/workflow/constants'
import { checkHasContextBlock, checkHasHistoryBlock, checkHasQueryBlock } from '@/app/components/base/prompt-editor/constants'
import useInspectVarsCrud from '@/app/components/workflow/hooks/use-inspect-vars-crud'
const useConfig = (id: string, payload: LLMNodeType) => {
const { nodesReadOnly: readOnly } = useNodesReadOnly()
@@ -29,6 +28,8 @@ const useConfig = (id: string, payload: LLMNodeType) => {
const { inputs, setInputs: doSetInputs } = useNodeCrud<LLMNodeType>(id, payload)
const inputRef = useRef(inputs)
const { deleteNodeInspectorVars } = useInspectVarsCrud()
const setInputs = useCallback((newInputs: LLMNodeType) => {
if (newInputs.memory && !newInputs.memory.role_prefix) {
const newPayload = produce(newInputs, (draft) => {
@@ -293,14 +294,16 @@ const useConfig = (id: string, payload: LLMNodeType) => {
setInputs(newInputs)
if (enabled)
setStructuredOutputCollapsed(false)
}, [inputs, setInputs])
deleteNodeInspectorVars(id)
}, [inputs, setInputs, deleteNodeInspectorVars, id])
const handleStructureOutputChange = useCallback((newOutput: StructuredOutput) => {
const newInputs = produce(inputs, (draft) => {
draft.structured_output = newOutput
})
setInputs(newInputs)
}, [inputs, setInputs])
deleteNodeInspectorVars(id)
}, [inputs, setInputs, deleteNodeInspectorVars, id])
const filterInputVar = useCallback((varPayload: Var) => {
return [VarType.number, VarType.string, VarType.secret, VarType.arrayString, VarType.arrayNumber, VarType.file, VarType.arrayFile].includes(varPayload.type)
@@ -322,81 +325,6 @@ const useConfig = (id: string, payload: LLMNodeType) => {
filterVar: filterMemoryPromptVar,
})
// single run
const {
isShowSingleRun,
hideSingleRun,
getInputVars,
runningStatus,
handleRun,
handleStop,
runInputData,
runInputDataRef,
setRunInputData,
runResult,
toVarInputs,
} = useOneStepRun<LLMNodeType>({
id,
data: inputs,
defaultRunInputData: {
'#context#': [RETRIEVAL_OUTPUT_STRUCT],
'#files#': [],
},
})
const inputVarValues = (() => {
const vars: Record<string, any> = {}
Object.keys(runInputData)
.filter(key => !['#context#', '#files#'].includes(key))
.forEach((key) => {
vars[key] = runInputData[key]
})
return vars
})()
const setInputVarValues = useCallback((newPayload: Record<string, any>) => {
const newVars = {
...newPayload,
'#context#': runInputDataRef.current['#context#'],
'#files#': runInputDataRef.current['#files#'],
}
setRunInputData(newVars)
}, [runInputDataRef, setRunInputData])
const contexts = runInputData['#context#']
const setContexts = useCallback((newContexts: string[]) => {
setRunInputData({
...runInputDataRef.current,
'#context#': newContexts,
})
}, [runInputDataRef, setRunInputData])
const visionFiles = runInputData['#files#']
const setVisionFiles = useCallback((newFiles: any[]) => {
setRunInputData({
...runInputDataRef.current,
'#files#': newFiles,
})
}, [runInputDataRef, setRunInputData])
const allVarStrArr = (() => {
const arr = isChatModel ? (inputs.prompt_template as PromptItem[]).filter(item => item.edition_type !== EditionType.jinja2).map(item => item.text) : [(inputs.prompt_template as PromptItem).text]
if (isChatMode && isChatModel && !!inputs.memory) {
arr.push('{{#sys.query#}}')
arr.push(inputs.memory.query_prompt_template)
}
return arr
})()
const varInputs = (() => {
const vars = getInputVars(allVarStrArr)
if (isShowVars)
return [...vars, ...toVarInputs(inputs.prompt_config?.jinja2_variables || [])]
return vars
})()
return {
readOnly,
isChatMode,
@@ -423,24 +351,11 @@ const useConfig = (id: string, payload: LLMNodeType) => {
handleSyeQueryChange,
handleVisionResolutionEnabledChange,
handleVisionResolutionChange,
isShowSingleRun,
hideSingleRun,
inputVarValues,
setInputVarValues,
visionFiles,
setVisionFiles,
contexts,
setContexts,
varInputs,
runningStatus,
isModelSupportStructuredOutput,
handleStructureOutputChange,
structuredOutputCollapsed,
setStructuredOutputCollapsed,
handleStructureOutputEnableChange,
handleRun,
handleStop,
runResult,
filterJinjia2InputVar,
}
}

View File

@@ -0,0 +1,198 @@
import type { MutableRefObject } from 'react'
import { useTranslation } from 'react-i18next'
import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'
import type { InputVar, PromptItem, Var, Variable } from '@/app/components/workflow/types'
import { InputVarType, VarType } from '@/app/components/workflow/types'
import type { LLMNodeType } from './types'
import { EditionType } from '../../types'
import useNodeCrud from '../_base/hooks/use-node-crud'
import { useIsChatMode } from '../../hooks'
import { useCallback } from 'react'
import useConfigVision from '../../hooks/use-config-vision'
import { noop } from 'lodash-es'
import { findVariableWhenOnLLMVision } from '../utils'
import useAvailableVarList from '../_base/hooks/use-available-var-list'
const i18nPrefix = 'workflow.nodes.llm'
type Params = {
id: string,
payload: LLMNodeType,
runInputData: Record<string, any>
runInputDataRef: MutableRefObject<Record<string, any>>
getInputVars: (textList: string[]) => InputVar[]
setRunInputData: (data: Record<string, any>) => void
toVarInputs: (variables: Variable[]) => InputVar[]
}
const useSingleRunFormParams = ({
id,
payload,
runInputData,
runInputDataRef,
getInputVars,
setRunInputData,
toVarInputs,
}: Params) => {
const { t } = useTranslation()
const { inputs } = useNodeCrud<LLMNodeType>(id, payload)
const getVarInputs = getInputVars
const isChatMode = useIsChatMode()
const contexts = runInputData['#context#']
const setContexts = useCallback((newContexts: string[]) => {
setRunInputData?.({
...runInputDataRef.current,
'#context#': newContexts,
})
}, [runInputDataRef, setRunInputData])
const visionFiles = runInputData['#files#']
const setVisionFiles = useCallback((newFiles: any[]) => {
setRunInputData?.({
...runInputDataRef.current,
'#files#': newFiles,
})
}, [runInputDataRef, setRunInputData])
// model
const model = inputs.model
const modelMode = inputs.model?.mode
const isChatModel = modelMode === 'chat'
const {
isVisionModel,
} = useConfigVision(model, {
payload: inputs.vision,
onChange: noop,
})
const isShowVars = (() => {
if (isChatModel)
return (inputs.prompt_template as PromptItem[]).some(item => item.edition_type === EditionType.jinja2)
return (inputs.prompt_template as PromptItem).edition_type === EditionType.jinja2
})()
const filterMemoryPromptVar = useCallback((varPayload: Var) => {
return [VarType.arrayObject, VarType.array, VarType.number, VarType.string, VarType.secret, VarType.arrayString, VarType.arrayNumber, VarType.file, VarType.arrayFile].includes(varPayload.type)
}, [])
const {
availableVars,
} = useAvailableVarList(id, {
onlyLeafNodeVar: false,
filterVar: filterMemoryPromptVar,
})
const allVarStrArr = (() => {
const arr = isChatModel ? (inputs.prompt_template as PromptItem[]).filter(item => item.edition_type !== EditionType.jinja2).map(item => item.text) : [(inputs.prompt_template as PromptItem).text]
if (isChatMode && isChatModel && !!inputs.memory) {
arr.push('{{#sys.query#}}')
arr.push(inputs.memory.query_prompt_template)
}
return arr
})()
const varInputs = (() => {
const vars = getVarInputs(allVarStrArr) || []
if (isShowVars)
return [...vars, ...(toVarInputs ? (toVarInputs(inputs.prompt_config?.jinja2_variables || [])) : [])]
return vars
})()
const inputVarValues = (() => {
const vars: Record<string, any> = {}
Object.keys(runInputData)
.filter(key => !['#context#', '#files#'].includes(key))
.forEach((key) => {
vars[key] = runInputData[key]
})
return vars
})()
const setInputVarValues = useCallback((newPayload: Record<string, any>) => {
const newVars = {
...newPayload,
'#context#': runInputDataRef.current['#context#'],
'#files#': runInputDataRef.current['#files#'],
}
setRunInputData?.(newVars)
}, [runInputDataRef, setRunInputData])
const forms = (() => {
const forms: FormProps[] = []
if (varInputs.length > 0) {
forms.push(
{
label: t(`${i18nPrefix}.singleRun.variable`)!,
inputs: varInputs,
values: inputVarValues,
onChange: setInputVarValues,
},
)
}
if (inputs.context?.variable_selector && inputs.context?.variable_selector.length > 0) {
forms.push(
{
label: t(`${i18nPrefix}.context`)!,
inputs: [{
label: '',
variable: '#context#',
type: InputVarType.contexts,
required: false,
}],
values: { '#context#': contexts },
onChange: keyValue => setContexts(keyValue['#context#']),
},
)
}
if (isVisionModel && payload.vision?.enabled && payload.vision?.configs?.variable_selector) {
const currentVariable = findVariableWhenOnLLMVision(payload.vision.configs.variable_selector, availableVars)
forms.push(
{
label: t(`${i18nPrefix}.vision`)!,
inputs: [{
label: currentVariable?.variable as any,
variable: '#files#',
type: currentVariable?.formType as any,
required: false,
}],
values: { '#files#': visionFiles },
onChange: keyValue => setVisionFiles((keyValue as any)['#files#']),
},
)
}
return forms
})()
const getDependentVars = () => {
const promptVars = varInputs.map(item => item.variable.slice(1, -1).split('.'))
const contextVar = payload.context.variable_selector
const vars = [...promptVars, contextVar]
if (isVisionModel && payload.vision?.enabled && payload.vision?.configs?.variable_selector) {
const visionVar = payload.vision.configs.variable_selector
vars.push(visionVar)
}
return vars
}
const getDependentVar = (variable: string) => {
if(variable === '#context#')
return payload.context.variable_selector
if(variable === '#files#')
return payload.vision.configs?.variable_selector
return false
}
return {
forms,
getDependentVars,
getDependentVar,
}
}
export default useSingleRunFormParams