chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,195 @@
import type { ComponentProps } from 'react'
import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { useStoreApi } from 'reactflow'
import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
import { renderWorkflowFlowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
import ClassList from '../../_base/components/branch-list/class-list'
import AdvancedSetting from '../components/advanced-setting'
vi.mock('@/app/components/workflow/nodes/_base/components/prompt/editor', () => ({
default: ({
title,
value,
onChange,
onRemove,
showRemove,
readOnly,
}: ComponentProps<
typeof import('@/app/components/workflow/nodes/_base/components/prompt/editor').default
>) => (
<div>
<div>{title}</div>
<input
aria-label="Class description"
readOnly={readOnly}
value={value}
onChange={(event) => onChange(event.target.value)}
/>
{showRemove && !readOnly && (
<button type="button" onClick={onRemove}>
remove-item
</button>
)}
</div>
),
}))
vi.mock('../../_base/hooks/use-available-var-list', () => ({
default: vi.fn(() => ({
availableVars: [{ variable: ['node-1', 'answer'], type: VarType.string }],
availableNodesWithParent: [
{ id: 'node-1', data: { title: 'Answer', desc: '', type: BlockEnum.Answer } },
],
})),
}))
const createTopic = (overrides: Partial<Topic> = {}): Topic => ({
id: 'topic-1',
name: 'Billing questions',
...overrides,
})
describe('question-classifier path', () => {
// Class editing and advanced settings share the real branch and memory controls.
describe('Path Integration', () => {
it('should render advanced settings and memory config', async () => {
const user = userEvent.setup()
const onInstructionChange = vi.fn()
const onMemoryChange = vi.fn()
render(
<AdvancedSetting
instruction="Route by topic"
onInstructionChange={onInstructionChange}
hideMemorySetting={false}
onMemoryChange={onMemoryChange}
isChatModel
isChatApp
nodesOutputVars={[]}
availableNodes={[]}
/>,
)
await user.type(screen.getByDisplayValue('Route by topic'), '!')
await user.click(screen.getByRole('switch'))
expect(onInstructionChange).toHaveBeenCalledWith('Route by topic!')
expect(onMemoryChange).toHaveBeenCalledWith({
window: { enabled: false, size: 50 },
query_prompt_template: '{{#sys.query#}}\n\n{{#sys.files#}}',
})
})
it('adds, edits, removes and collapses classes while retaining unrelated branches', async () => {
const user = userEvent.setup()
let flow: ReturnType<typeof useStoreApi>
function ClassListHarness() {
flow = useStoreApi()
const [list, setList] = useState(() => [
createTopic(),
createTopic({ id: 'topic-2', name: 'Refunds' }),
])
return <ClassList nodeId="node-1" list={list} onChange={setList} filterVar={() => true} />
}
const nodes = [
createNode({
id: 'node-1',
data: {
type: BlockEnum.QuestionClassifier,
_connectedSourceHandleIds: ['topic-1', 'topic-2'],
},
}),
createNode({ id: 'billing', data: { _connectedTargetHandleIds: ['target'] } }),
createNode({ id: 'refunds', data: { _connectedTargetHandleIds: ['target'] } }),
]
const edges = [
createEdge({
id: 'billing-edge',
source: 'node-1',
sourceHandle: 'topic-1',
target: 'billing',
}),
createEdge({
id: 'refunds-edge',
source: 'node-1',
sourceHandle: 'topic-2',
target: 'refunds',
}),
]
render(<ClassListHarness />, { nodes, edges })
await user.click(
screen.getByRole('button', { name: 'workflowModels.nodes.questionClassifiers.addClass' }),
)
expect(screen.getAllByRole('textbox', { name: 'Class description' })).toHaveLength(3)
await user.type(screen.getByDisplayValue('Billing questions'), ' updated')
expect(screen.getByDisplayValue('Billing questions updated')).toBeInTheDocument()
await user.click(screen.getAllByRole('button', { name: 'remove-item' })[0]!)
expect(screen.queryByDisplayValue('Billing questions updated')).not.toBeInTheDocument()
expect(screen.getByDisplayValue('Refunds')).toBeInTheDocument()
expect(flow!.getState().edges).toEqual([expect.objectContaining(edges[1]!)])
expect(
flow!
.getState()
.getNodes()
.find((node) => node.id === 'node-1')?.data._connectedSourceHandleIds,
).toEqual(['topic-2'])
expect(
flow!
.getState()
.getNodes()
.find((node) => node.id === 'billing')?.data._connectedTargetHandleIds,
).toEqual([])
await user.click(
screen.getByRole('button', { name: /workflow.nodes.questionClassifiers.class/ }),
)
expect(
screen.queryByRole('button', { name: 'workflowModels.nodes.questionClassifiers.addClass' }),
).not.toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: /workflow.nodes.questionClassifiers.class/ }),
)
expect(screen.getByDisplayValue('Refunds')).toBeInTheDocument()
})
it('prevents editing descriptions and memory settings in readonly mode', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
const onMemoryChange = vi.fn()
render(
<>
<ClassList
nodeId="node-1"
list={[createTopic()]}
onChange={onChange}
filterVar={() => true}
readonly
/>
<AdvancedSetting
instruction="Route by topic"
onInstructionChange={onChange}
hideMemorySetting={false}
onMemoryChange={onMemoryChange}
isChatModel
isChatApp
nodesOutputVars={[]}
availableNodes={[]}
readonly
/>
</>,
)
await user.type(screen.getByDisplayValue('Billing questions'), '!')
expect(onChange).not.toHaveBeenCalled()
expect(screen.queryByRole('button', { name: 'remove-item' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'workflowModels.nodes.questionClassifiers.addClass' }),
).not.toBeInTheDocument()
expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
await user.click(screen.getByRole('switch'))
expect(onMemoryChange).not.toHaveBeenCalled()
})
})
})
@@ -0,0 +1,131 @@
import type { QuestionClassifierNodeType } from '../types'
import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum } from '@/app/components/workflow/types'
import {
createCatalogModelFixture,
createModelCatalogFixture,
seedModelProviderQueries,
} from '@/test/console/model-provider'
import { createConsoleQueryWrapper, seedAppDslVersion } from '@/test/console/query-data'
import { seedToolProviders } from '@/test/console/tool-providers'
import { createNuqsTestRenderer } from '@/test/nuqs-testing'
import Node from '../node'
const render = createNuqsTestRenderer((ui) => {
const { queryClient } = createConsoleQueryWrapper()
seedAppDslVersion(queryClient)
seedModelProviderQueries(queryClient, [
createModelCatalogFixture({
models: [createCatalogModelFixture({ model: 'gpt-4o', label: { en_US: 'GPT-4o' } })],
}),
])
seedToolProviders(queryClient, {
builtInTools: [],
customTools: [],
workflowTools: [],
mcpTools: [],
})
return renderWorkflowFlowComponent(ui, { queryClient })
})
const createTopic = (overrides: Partial<Topic> = {}): Topic => ({
id: 'topic-1',
name: 'Billing questions',
...overrides,
})
const createData = (
overrides: Partial<QuestionClassifierNodeType> = {},
): QuestionClassifierNodeType => ({
title: 'Question Classifier',
desc: '',
type: BlockEnum.QuestionClassifier,
model: {
provider: 'openai',
name: 'gpt-4o',
mode: 'chat',
completion_params: {},
},
classes: [createTopic()],
query_variable_selector: ['node-1', 'query'],
instruction: 'Route by topic',
vision: {
enabled: false,
},
...overrides,
})
const baseNodeProps = {
id: 'node-1',
type: 'custom',
selected: false,
zIndex: 1,
xPos: 0,
yPos: 0,
dragging: false,
isConnectable: true,
}
describe('question-classifier/node', () => {
it('shows the configured model and class labels', () => {
render(
<Node
{...baseNodeProps}
data={createData({
classes: [
createTopic({ label: 'Billing' }),
createTopic({ id: 'topic-2', name: 'Refunds', label: 'Refund desk' }),
],
})}
/>,
)
expect(screen.getByText('GPT-4o')).toBeInTheDocument()
expect(screen.getByText('Billing')).toBeInTheDocument()
expect(screen.getByText('Refund desk')).toBeInTheDocument()
})
it('returns nothing when neither model nor classes are configured and truncates long class names', async () => {
const user = userEvent.setup()
const longName = 'L'.repeat(60)
const { rerender } = render(
<Node
{...baseNodeProps}
data={createData({
model: {
provider: '',
name: '',
mode: 'chat',
completion_params: {},
},
classes: [createTopic({ id: 'topic-2', name: longName })],
})}
/>,
)
expect(screen.getByText(`${longName.slice(0, 50)}...`)).toBeInTheDocument()
await user.hover(screen.getByRole('button', { name: longName }))
expect(await screen.findByText(longName)).toBeInTheDocument()
rerender(
<Node
{...baseNodeProps}
data={createData({
model: {
provider: '',
name: '',
mode: 'chat',
completion_params: {},
},
classes: [],
})}
/>,
)
expect(screen.queryByText(`${longName.slice(0, 50)}...`)).not.toBeInTheDocument()
expect(screen.queryByText('GPT-4o')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,130 @@
import type { QuestionClassifierNodeType } from '../types'
import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'
import { act, waitFor } from '@testing-library/react'
import { useNodes, useReactFlow } from 'reactflow'
import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
import { renderWorkflowFlowHook } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum } from '@/app/components/workflow/types'
import { consoleQuery } from '@/service/console'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { seedToolProviders } from '@/test/console/tool-providers'
import useConfig from '../use-config'
// Model capabilities are external catalog data; node updates and vision reconciliation stay real.
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
useModelListAndDefaultModelAndCurrentProviderAndModel: () => ({}),
useTextGenerationCurrentProviderAndModelAndModelList: ({ model }: { model: string }) => ({
currentModel: { features: model === 'vision-model' ? [ModelFeatureEnum.vision] : [] },
}),
}))
const createPayload = (
overrides: Partial<QuestionClassifierNodeType> = {},
): QuestionClassifierNodeType => ({
type: BlockEnum.QuestionClassifier,
title: 'Question Classifier',
desc: '',
model: { provider: 'openai', name: 'vision-model', mode: 'chat', completion_params: {} },
classes: [{ id: 'topic-1', name: 'Billing questions', label: 'CLASS 1' }],
_targetBranches: [{ id: 'topic-1', name: 'Billing questions' }],
query_variable_selector: ['start', 'query'],
instruction: 'Route by topic',
vision: { enabled: true },
...overrides,
})
const setup = (
payload = createPayload(),
resource: EditorResource = { kind: 'app', appId: 'app-1', mode: 'workflow' },
) => {
const { queryClient } = createConsoleQueryWrapper()
seedToolProviders(queryClient, {
builtInTools: [],
customTools: [],
workflowTools: [],
mcpTools: [],
})
queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
return renderWorkflowFlowHook(
() => {
const nodes = useNodes<QuestionClassifierNodeType>()
return {
config: useConfig(
'classifier',
nodes.find((node) => node.id === 'classifier')?.data ?? payload,
),
flow: useReactFlow(),
}
},
{
resource,
queryClient,
initialStoreState: {
nodesDefaultConfigs: { [BlockEnum.QuestionClassifier]: createPayload() },
},
nodes: [
createNode({ id: 'start', data: { type: BlockEnum.Start, variables: [] } }),
createNode({ id: 'classifier', data: payload }),
],
edges: [createEdge({ source: 'start', target: 'classifier' })],
},
)
}
it('keeps the selected model after real vision reconciliation disables unsupported vision', async () => {
const { result } = setup()
expect(result.current.config.inputs.vision.enabled).toBe(true)
act(() =>
result.current.config.handleModelChanged({
provider: 'openai',
modelId: 'text-model',
mode: 'chat',
}),
)
await waitFor(() => expect(result.current.config.inputs.vision.enabled).toBe(false))
expect(result.current.flow.getNode('classifier')?.data.model).toEqual(
expect.objectContaining({ provider: 'openai', name: 'text-model', mode: 'chat' }),
)
})
it('persists consecutive model, completion and class edits without losing earlier changes', async () => {
const { result } = setup()
act(() =>
result.current.config.handleModelChanged({
provider: 'openai',
modelId: 'text-model',
mode: 'chat',
}),
)
await waitFor(() => expect(result.current.config.inputs.vision.enabled).toBe(false))
act(() => result.current.config.handleCompletionParamsChange({ temperature: 0.2 }))
act(() =>
result.current.config.handleTopicsChange([{ id: 'refund', name: 'Refunds', label: 'CLASS 1' }]),
)
expect(result.current.flow.getNode('classifier')?.data).toEqual(
expect.objectContaining({
model: expect.objectContaining({
name: 'text-model',
completion_params: { temperature: 0.2 },
}),
classes: [{ id: 'refund', name: 'Refunds', label: 'CLASS 1' }],
_targetBranches: [{ id: 'refund', name: 'Refunds' }],
vision: { enabled: false },
}),
)
})
it.each([
{ resource: { kind: 'snippet', snippetId: 'snippet-1' } as EditorResource, selector: [] },
{ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } as EditorResource, selector: [] },
{
resource: { kind: 'app', appId: 'app-1', mode: 'advanced-chat' } as EditorResource,
selector: ['start', 'sys.query'],
},
])('derives the default query selector from $resource', async ({ resource, selector }) => {
const { result } = setup(createPayload({ query_variable_selector: [] }), resource)
await waitFor(() =>
expect(result.current.config.inputs.query_variable_selector).toEqual(selector),
)
})
@@ -0,0 +1,119 @@
import type { QuestionClassifierNodeType } from '../types'
import type { InputVar } from '@/app/components/workflow/types'
import { act } from '@testing-library/react'
import { useState } from 'react'
import { renderWorkflowCanvasHook as renderHook } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
import { Resolution } from '@/types/app'
import { createSingleRunGraphOptions } from '../../__tests__/single-run-graph-options'
import useSingleRunFormParams from '../use-single-run-form-params'
const createData = (
overrides: Partial<QuestionClassifierNodeType> = {},
): QuestionClassifierNodeType => ({
title: 'Question Classifier',
desc: '',
type: BlockEnum.QuestionClassifier,
model: {
provider: 'openai',
name: 'gpt-4o',
mode: 'chat',
completion_params: {},
},
classes: [{ id: 'topic-1', name: 'Billing questions' }],
query_variable_selector: ['node-1', 'query'],
instruction: 'Route by {{#node-2.answer#}}',
vision: {
enabled: true,
configs: {
variable_selector: ['node-3', 'image'],
detail: Resolution.high,
},
},
...overrides,
})
describe('question-classifier/use-single-run-form-params', () => {
it('builds variable and vision forms and exposes dependent variables', () => {
const getInputVars = (): InputVar[] => [
{
label: 'Answer',
variable: '#node-2.answer#',
type: InputVarType.textInput,
required: true,
},
]
const payload = createData()
const { result } = renderHook(() => {
const [runInputData, setRunInputData] = useState<Record<string, unknown>>({
query: 'hello',
'#files#': ['file-1'],
})
return useSingleRunFormParams({
id: 'current-node',
payload,
runInputData,
runInputDataRef: { current: runInputData },
getInputVars,
setRunInputData,
toVarInputs: () => [],
})
}, createSingleRunGraphOptions(payload))
expect(result.current.forms).toHaveLength(2)
expect(result.current.forms[0]!.inputs).toEqual(
expect.arrayContaining([
expect.objectContaining({
variable: 'query',
type: InputVarType.paragraph,
}),
expect.objectContaining({
variable: '#node-2.answer#',
}),
]),
)
expect(result.current.forms[1]!.inputs).toEqual([
{
label: 'image',
variable: '#files#',
type: InputVarType.singleFile,
required: false,
},
])
act(() => result.current.forms[0]!.onChange({ query: 'updated' }))
expect(result.current.forms[0]!.values).toMatchObject({ query: 'updated' })
expect(result.current.forms[1]!.values).toEqual({ '#files#': ['file-1'] })
act(() => result.current.forms[1]!.onChange({ '#files#': ['file-2'] }))
expect(result.current.forms[0]!.values).toMatchObject({ query: 'updated' })
expect(result.current.forms[1]!.values).toEqual({ '#files#': ['file-2'] })
expect(result.current.getDependentVars()).toEqual([
['node-1', 'query'],
['node-2', 'answer'],
['node-3', 'image'],
])
expect(result.current.getDependentVar('query')).toEqual(['node-1', 'query'])
expect(result.current.getDependentVar('#files#')).toEqual(['node-3', 'image'])
expect(result.current.getDependentVar('unknown')).toBe(false)
})
it('omits the vision form when the selected model does not support vision', () => {
const payload = createData()
const { result } = renderHook(
() =>
useSingleRunFormParams({
id: 'current-node',
payload,
runInputData: {},
runInputDataRef: { current: {} },
getInputVars: () => [],
setRunInputData: vi.fn(),
toVarInputs: () => [],
}),
createSingleRunGraphOptions(payload, false),
)
expect(result.current.forms).toHaveLength(1)
})
})
@@ -0,0 +1,204 @@
import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'
import type { CodeNodeType } from '@/app/components/workflow/nodes/code/types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { replacePromptEditorText } from '@/app/components/base/prompt-editor/plugins/__tests__/test-helpers'
import {
createEdge,
createNode,
createStartNode,
} from '@/app/components/workflow/__tests__/fixtures'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
import { consoleQuery } from '@/service/console'
import { seedModelProviderQueries } from '@/test/console/model-provider'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { seedToolProviders } from '@/test/console/tool-providers'
import ClassItem from '../../../_base/components/branch-list/class-item'
const createTopic = (overrides: Partial<Topic> = {}): Topic => ({
id: 'topic-1',
name: 'Billing questions',
...overrides,
})
const createCodeNode = () => {
const data = {
title: 'Answer producer',
desc: '',
type: BlockEnum.Code,
code_language: CodeLanguage.python3,
code: 'def main():\n return {"answer": "Billing question"}',
variables: [],
outputs: { answer: { type: VarType.string, children: null } },
} satisfies CodeNodeType
return createNode({ id: 'code', data })
}
const renderClass = (ui: React.ReactElement) => {
const { queryClient } = createConsoleQueryWrapper({ appDslVersion: '0.6.0' })
seedModelProviderQueries(queryClient, [])
seedToolProviders(queryClient, {
builtInTools: [],
customTools: [],
workflowTools: [],
mcpTools: [],
})
queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
const start = createStartNode({
id: 'start',
data: {
title: 'Inputs',
variables: [
{
variable: 'query',
label: 'Query',
type: InputVarType.textInput,
required: true,
},
],
},
})
const code = createCodeNode()
const classifier = createNode({
id: 'node-1',
data: { title: 'Classifier', type: BlockEnum.QuestionClassifier },
})
return renderWorkflowFlowComponent(
<EventEmitterContextProvider>{ui}</EventEmitterContextProvider>,
{
queryClient,
nodes: [start, code, classifier],
edges: [
createEdge({
source: start.id,
target: code.id,
data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Code },
}),
createEdge({
source: code.id,
target: classifier.id,
data: { sourceType: BlockEnum.Code, targetType: BlockEnum.QuestionClassifier },
}),
],
},
)
}
describe('question-classifier/class-item', () => {
it('forwards editor updates and remove actions', async () => {
const user = userEvent.setup()
function EditableClass() {
const [topic, setTopic] = useState(createTopic)
const [removed, setRemoved] = useState(false)
return (
<>
{!removed && (
<ClassItem
nodeId="node-1"
payload={topic}
onChange={setTopic}
onRemove={() => setRemoved(true)}
index={1}
filterVar={() => true}
/>
)}
<output aria-label="Saved class">{JSON.stringify(topic)}</output>
<output aria-label="Removal state">{removed ? 'removed' : 'present'}</output>
</>
)
}
renderClass(<EditableClass />)
expect(screen.getByRole('button', { name: 'CLASS 1' })).toBeInTheDocument()
await replacePromptEditorText(screen.getByRole('textbox'), 'Billing questions updated')
await waitFor(() =>
expect(JSON.parse(screen.getByRole('status', { name: 'Saved class' }).textContent!)).toEqual({
id: 'topic-1',
name: 'Billing questions updated',
}),
)
await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
expect(screen.getByRole('status', { name: 'Removal state' })).toHaveTextContent('removed')
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
})
it('preserves a custom label when editing the classifier name', async () => {
function LabeledClass() {
const [topic, setTopic] = useState(() => createTopic({ label: 'Billing' }))
return (
<>
<ClassItem
nodeId="node-1"
payload={topic}
onChange={setTopic}
onRemove={() => {}}
index={1}
filterVar={() => true}
/>
<output aria-label="Saved class">{JSON.stringify(topic)}</output>
</>
)
}
renderClass(<LabeledClass />)
await replacePromptEditorText(screen.getByRole('textbox'), 'Billing questions updated')
await waitFor(() =>
expect(JSON.parse(screen.getByRole('status', { name: 'Saved class' }).textContent!)).toEqual({
id: 'topic-1',
name: 'Billing questions updated',
label: 'Billing',
}),
)
expect(screen.getByRole('button', { name: 'Billing' })).toBeInTheDocument()
})
})
it('preserves the group name during label editing and updates it on save', async () => {
const user = userEvent.setup()
function NamedClass() {
const [topic, setTopic] = useState(() => createTopic({ label: 'Billing' }))
const [readonly, setReadonly] = useState(false)
return (
<>
<button type="button" onClick={() => setReadonly(true)}>
Make readonly
</button>
<div role="group" aria-labelledby="class-title">
<ClassItem
labelId="class-title"
nodeId="node-1"
payload={topic}
onChange={setTopic}
onRemove={() => {}}
index={1}
filterVar={() => true}
readonly={readonly}
/>
</div>
</>
)
}
renderClass(<NamedClass />)
expect(screen.getByRole('group', { name: 'Billing' })).toBeInTheDocument()
await user.dblClick(screen.getByRole('button', { name: 'Billing' }))
const labelInput = screen.getByRole('textbox', {
name: 'workflowModels.nodes.questionClassifiers.labelEditorAriaLabel',
})
await user.clear(labelInput)
await user.type(labelInput, 'Refunds')
expect(screen.getByRole('group', { name: 'Billing' })).toBeInTheDocument()
await user.keyboard('{Enter}')
expect(screen.getByRole('group', { name: 'Refunds' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Make readonly' }))
expect(screen.getByRole('group', { name: 'Refunds' })).toBeInTheDocument()
})
@@ -0,0 +1,70 @@
import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { renderWorkflowFlowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'
import ClassList from '../../../_base/components/branch-list/class-list'
// Class editing is covered by the adjacent integration suite; this boundary isolates list ordering.
vi.mock('../../../_base/components/branch-list/class-item', () => ({
default: ({ payload, index, labelId }: { payload: Topic; index: number; labelId: string }) => (
<div id={labelId}>{`${index}:${payload.name}`}</div>
),
}))
const createTopic = (overrides: Partial<Topic> = {}): Topic => ({
id: 'topic-1',
name: 'Billing questions',
...overrides,
})
describe('question-classifier/class-list', () => {
it('confirms keyboard sorting through the branch-aware sort callback', async () => {
const user = userEvent.setup()
const handleSortTopic = vi.fn()
const onChange = vi.fn()
const topics = [createTopic(), createTopic({ id: 'topic-2', name: 'Refunds' })]
function Fixture() {
const [list, setList] = useState(topics)
return (
<ClassList
nodeId="node-1"
list={list}
onChange={onChange}
filterVar={() => true}
handleSortTopic={(items) => {
handleSortTopic(items)
setList(items)
}}
/>
)
}
render(<Fixture />)
const handle = screen.getAllByRole('button', { pressed: false })[0]!
for (let index = 0; index < 10 && document.activeElement !== handle; index++) await user.tab()
expect(handle).toHaveFocus()
await user.keyboard('{Enter}{ArrowDown}')
expect(screen.getByText('1:Refunds')).toBeInTheDocument()
expect(handleSortTopic).not.toHaveBeenCalled()
await user.keyboard('{Enter}')
expect(handleSortTopic).toHaveBeenCalledExactlyOnceWith([topics[1], topics[0]])
expect(onChange).not.toHaveBeenCalled()
})
it('hides drag and add affordances when readonly', () => {
render(
<ClassList
nodeId="node-1"
list={[createTopic(), createTopic({ id: 'topic-2', name: 'Refunds' })]}
onChange={vi.fn()}
filterVar={() => true}
readonly
/>,
)
expect(
screen.queryByText('workflowModels.nodes.questionClassifiers.addClass'),
).not.toBeInTheDocument()
expect(screen.queryByRole('button', { pressed: false })).not.toBeInTheDocument()
})
})
@@ -0,0 +1,85 @@
'use client'
import type { FC } from 'react'
import type { Memory, Node, NodeOutPutVar } from '@/app/components/workflow/types'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import Editor from '@/app/components/workflow/nodes/_base/components/prompt/editor'
import MemoryConfig from '../../_base/components/memory-config'
const i18nPrefix = 'nodes.questionClassifiers'
type Props = Readonly<{
instruction: string
onInstructionChange: (instruction: string) => void
hideMemorySetting: boolean
memory?: Memory
onMemoryChange: (memory?: Memory) => void
readonly?: boolean
isChatModel: boolean
isChatApp: boolean
hasSetBlockStatus?: {
context: boolean
history: boolean
query: boolean
}
nodesOutputVars: NodeOutPutVar[]
availableNodes: Node[]
}>
const AdvancedSetting: FC<Props> = ({
instruction,
onInstructionChange,
hideMemorySetting,
memory,
onMemoryChange,
readonly,
isChatModel,
isChatApp,
hasSetBlockStatus,
nodesOutputVars,
availableNodes,
}) => {
const instructionLabelId = React.useId()
const { t } = useTranslation(['workflowModels'])
return (
<>
<Editor
title={
<div className="flex items-center space-x-1">
<span id={instructionLabelId} className="uppercase">
{t(($) => $[`${i18nPrefix}.instruction`], { ns: 'workflowModels' })}
</span>
<Infotip>
<InfotipTrigger aria-labelledby={instructionLabelId} className="ml-0.5 size-3.5" />
<InfotipContent aria-labelledby={instructionLabelId} className="w-30">
{t(($) => $[`${i18nPrefix}.instructionTip`], { ns: 'workflowModels' })}
</InfotipContent>
</Infotip>
</div>
}
value={instruction}
onChange={onInstructionChange}
readOnly={readonly}
isChatModel={isChatModel}
isChatApp={isChatApp}
isShowContext={false}
hasSetBlockStatus={hasSetBlockStatus}
nodesOutputVars={nodesOutputVars}
availableNodes={availableNodes}
/>
{!hideMemorySetting && (
<MemoryConfig
className="mt-4"
readonly={!!readonly}
config={{ data: memory }}
onChange={onMemoryChange}
canSetRoleName={false}
/>
)}
</>
)
}
export default React.memo(AdvancedSetting)
@@ -0,0 +1,98 @@
import type { TFunction } from 'i18next'
import type { NodeDefault } from '../../types'
import type { QuestionClassifierNodeType } from './types'
import { BlockClassification } from '@/app/components/workflow/block-selector/types'
import { BlockEnum } from '@/app/components/workflow/types'
import { genNodeMetaData } from '@/app/components/workflow/utils'
const i18nPrefix = ''
const metaData = genNodeMetaData({
classification: BlockClassification.QuestionUnderstand,
sort: 1,
type: BlockEnum.QuestionClassifier,
})
const nodeDefault: NodeDefault<QuestionClassifierNodeType> = {
metaData,
defaultValue: {
query_variable_selector: [],
model: {
provider: '',
name: '',
mode: 'chat' as const,
completion_params: {
temperature: 0.7,
},
},
classes: [
{
id: '1',
name: '',
label: 'CLASS 1',
},
{
id: '2',
name: '',
label: 'CLASS 2',
},
],
_targetBranches: [
{
id: '1',
name: '',
},
{
id: '2',
name: '',
},
],
vision: {
enabled: false,
},
},
checkValid(payload: QuestionClassifierNodeType, t: TFunction<['workflow']>) {
let errorMessages = ''
if (
!errorMessages &&
(!payload.query_variable_selector || payload.query_variable_selector.length === 0)
)
errorMessages = t(($) => $[`${i18nPrefix}errorMsg.fieldRequired`], {
ns: 'workflow',
field: t(($) => $[`${i18nPrefix}nodes.questionClassifiers.inputVars`], { ns: 'workflow' }),
})
if (!errorMessages && !payload.model.provider)
errorMessages = t(($) => $[`${i18nPrefix}errorMsg.fieldRequired`], {
ns: 'workflow',
field: t(($) => $[`${i18nPrefix}nodes.questionClassifiers.model`], { ns: 'workflow' }),
})
if (!errorMessages && (!payload.classes || payload.classes.length === 0))
errorMessages = t(($) => $[`${i18nPrefix}errorMsg.fieldRequired`], {
ns: 'workflow',
field: t(($) => $[`${i18nPrefix}nodes.questionClassifiers.class`], { ns: 'workflow' }),
})
if (!errorMessages && payload.classes.some((item) => !item.name))
errorMessages = t(($) => $[`${i18nPrefix}errorMsg.fieldRequired`], {
ns: 'workflow',
field: t(($) => $[`${i18nPrefix}nodes.questionClassifiers.topicName`], { ns: 'workflow' }),
})
if (
!errorMessages &&
payload.vision?.enabled &&
!payload.vision.configs?.variable_selector?.length
)
errorMessages = t(($) => $[`${i18nPrefix}errorMsg.fieldRequired`], {
ns: 'workflow',
field: t(($) => $[`${i18nPrefix}errorMsg.fields.visionVariable`], { ns: 'workflow' }),
})
return {
isValid: !errorMessages,
errorMessage: errorMessages,
}
},
}
export default nodeDefault
@@ -0,0 +1,34 @@
import type { FC } from 'react'
import type { NodeProps } from 'reactflow'
import type { QuestionClassifierNodeType } from './types'
import * as React from 'react'
import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { ModelSelector } from '@/app/components/header/account-setting/model-provider-page/model-selector'
import { NodeBranches } from '../_base/components/branch-list/node-branches'
const Node: FC<NodeProps<QuestionClassifierNodeType>> = (props) => {
const { data } = props
const { provider, name: modelId } = data.model
// const tempTopics = data.topics
const topics = data.classes
const { textGenerationModelList } = useTextGenerationCurrentProviderAndModelAndModelList()
const hasSetModel = provider && modelId
if (!hasSetModel && !topics.length) return null
return (
<div className="mb-1 px-3 py-1">
{hasSetModel && (
<ModelSelector
value={{ provider, model: modelId }}
models={textGenerationModelList}
size="small"
disabled
/>
)}
{!!topics.length && <NodeBranches node={props} branches={topics} />}
</div>
)
}
export default React.memo(Node)
@@ -0,0 +1,140 @@
import type { FC } from 'react'
import type { QuestionClassifierNodeType } from './types'
import type { NodePanelProps } from '@/app/components/workflow/types'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
import { FieldCollapse } from '@/app/components/workflow/nodes/_base/components/collapse'
import Field from '@/app/components/workflow/nodes/_base/components/field'
import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'
import Split from '@/app/components/workflow/nodes/_base/components/split'
import ClassList from '../_base/components/branch-list/class-list'
import ConfigVision from '../_base/components/config-vision'
import VarReferencePicker from '../_base/components/variable/var-reference-picker'
import AdvancedSetting from './components/advanced-setting'
import useConfig from './use-config'
const i18nPrefix = 'nodes.questionClassifiers'
const Panel: FC<NodePanelProps<QuestionClassifierNodeType>> = ({ id, data }) => {
const { t } = useTranslation(['workflow', 'workflowModels'])
const {
readOnly,
inputs,
handleModelChanged,
isChatflow,
isChatModel,
handleCompletionParamsChange,
handleQueryVarChange,
handleTopicsChange,
hasSetBlockStatus,
availableVars,
availableNodesWithParent,
handleInstructionChange,
handleMemoryChange,
isVisionModel,
handleVisionResolutionChange,
handleVisionResolutionEnabledChange,
filterVar,
handleSortTopic,
} = useConfig(id, data)
const model = inputs.model
return (
<div className="pt-2">
<div className="space-y-4 px-4">
<Field title={t(($) => $[`${i18nPrefix}.model`], { ns: 'workflow' })} required>
<ModelParameterModal
popupClassName="w-[387px]!"
isInWorkflow
isAdvancedMode={true}
provider={model?.provider}
completionParams={model.completion_params}
modelId={model.name}
setModel={handleModelChanged}
onCompletionParamsChange={handleCompletionParamsChange}
hideDebugWithMultipleModel
debugWithMultipleModel={false}
readonly={readOnly}
nodesOutputVars={availableVars}
availableNodes={availableNodesWithParent}
/>
</Field>
<Field title={t(($) => $[`${i18nPrefix}.inputVars`], { ns: 'workflow' })} required>
<VarReferencePicker
readonly={readOnly}
isShowNodeName
nodeId={id}
value={inputs.query_variable_selector}
onChange={handleQueryVarChange}
filterVar={filterVar}
/>
</Field>
<Split />
<ConfigVision
nodeId={id}
readOnly={readOnly}
isVisionModel={isVisionModel}
enabled={inputs.vision?.enabled}
onEnabledChange={handleVisionResolutionEnabledChange}
config={inputs.vision?.configs}
onConfigChange={handleVisionResolutionChange}
/>
<ClassList
nodeId={id}
list={inputs.classes}
onChange={handleTopicsChange}
readonly={readOnly}
filterVar={filterVar}
handleSortTopic={handleSortTopic}
/>
<Split />
</div>
<FieldCollapse title={t(($) => $[`${i18nPrefix}.advancedSetting`], { ns: 'workflowModels' })}>
<AdvancedSetting
hideMemorySetting={!isChatflow}
instruction={inputs.instruction}
onInstructionChange={handleInstructionChange}
memory={inputs.memory}
onMemoryChange={handleMemoryChange}
readonly={readOnly}
isChatApp={isChatflow}
isChatModel={isChatModel}
hasSetBlockStatus={hasSetBlockStatus}
nodesOutputVars={availableVars}
availableNodes={availableNodesWithParent}
/>
</FieldCollapse>
<Split />
<div>
<OutputVars>
<>
<VarItem
name="class_name"
type="string"
description={t(($) => $[`${i18nPrefix}.outputVars.className`], {
ns: 'workflowModels',
})}
/>
<VarItem
name="class_label"
type="string"
description={t(($) => $[`${i18nPrefix}.outputVars.classLabel`], {
ns: 'workflowModels',
})}
/>
<VarItem
name="usage"
type="object"
description={t(($) => $[`${i18nPrefix}.outputVars.usage`], { ns: 'workflowModels' })}
/>
</>
</OutputVars>
</div>
</div>
)
}
export default React.memo(Panel)
@@ -0,0 +1,20 @@
import type { Topic } from '../_base/components/branch-list/types'
import type {
CommonNodeType,
Memory,
ModelConfig,
ValueSelector,
VisionSetting,
} from '@/app/components/workflow/types'
export type QuestionClassifierNodeType = CommonNodeType & {
query_variable_selector: ValueSelector
model: ModelConfig
classes: Topic[]
instruction: string
memory?: Memory
vision: {
enabled: boolean
configs?: VisionSetting
}
}
@@ -0,0 +1,281 @@
import type { Memory, ValueSelector, Var } from '../../types'
import type { QuestionClassifierNodeType } from './types'
import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'
import { produce } from 'immer'
import { useAtomValue } from 'jotai'
import { startTransition, useCallback, useEffect, useRef } from 'react'
import { useUpdateNodeInternals } from 'reactflow'
import { checkHasQueryBlock } from '@/app/components/base/prompt-editor/constants'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import {
editorResourceKindAtom,
isChatflowAtom,
} from '@/app/components/workflow/editor-resource/state'
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
import useConfigVision from '../../hooks/use-config-vision'
import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'
import { useStore } from '../../store'
import { BlockEnum, VarType } from '../../types'
import useAvailableVarList from '../_base/hooks/use-available-var-list'
const useConfig = (id: string, payload: QuestionClassifierNodeType) => {
const updateNodeInternals = useUpdateNodeInternals()
const { nodesReadOnly: readOnly } = useNodesReadOnly()
const isChatflow = useAtomValue(isChatflowAtom)
const resourceKind = useAtomValue(editorResourceKindAtom)
const isSnippetFlow = resourceKind === 'snippet'
const defaultConfig = useStore((s) => s.nodesDefaultConfigs)?.[payload.type]
const { getBeforeNodesInSameBranch } = useWorkflow()
const startNode = getBeforeNodesInSameBranch(id).find(
(node) => node.data.type === BlockEnum.Start,
)
const startNodeId = startNode?.id
const { inputs, setInputs: doSetInputs } = useNodeCrud<QuestionClassifierNodeType>(id, payload)
const inputRef = useRef(inputs)
const setInputs = useCallback(
(newInputs: QuestionClassifierNodeType) => {
doSetInputs(newInputs)
inputRef.current = newInputs
},
[doSetInputs],
)
useEffect(() => {
inputRef.current = inputs
}, [inputs])
const isHandlingModelChangeRef = useRef(false)
const { currentProvider, currentModel } = useModelListAndDefaultModelAndCurrentProviderAndModel(
ModelTypeEnum.textGeneration,
)
const model = inputs.model
const modelMode = inputs.model?.mode
const isChatModel = modelMode === 'chat'
const handleVisionChange = useCallback(
(newPayload: QuestionClassifierNodeType['vision']) => {
const newInputs = produce(inputRef.current, (draft) => {
draft.vision = newPayload
})
setInputs(newInputs)
},
[setInputs],
)
const {
isVisionModel,
handleVisionResolutionEnabledChange,
handleVisionResolutionChange,
handleModelChanged: handleVisionConfigAfterModelChanged,
} = useConfigVision(model, {
payload: inputs.vision,
onChange: handleVisionChange,
})
const handleModelChanged = useCallback(
(model: { provider: string; modelId: string; mode?: string }) => {
const newInputs = produce(inputRef.current, (draft) => {
draft.model.provider = model.provider
draft.model.name = model.modelId
draft.model.mode = model.mode!
})
isHandlingModelChangeRef.current = true
setInputs(newInputs)
},
[setInputs],
)
useEffect(() => {
if (currentProvider?.provider && currentModel?.model && !model.provider) {
startTransition(() => {
handleModelChanged({
provider: currentProvider?.provider,
modelId: currentModel?.model,
mode: currentModel?.model_properties?.mode as string | undefined,
})
})
}
}, [model.provider, currentProvider, currentModel, handleModelChanged])
const handleCompletionParamsChange = useCallback(
(newParams: Record<string, unknown>) => {
const newInputs = produce(inputs, (draft) => {
draft.model.completion_params = newParams
})
setInputs(newInputs)
},
[inputs, setInputs],
)
// change to vision model to set vision enabled, else disabled
useEffect(() => {
if (!isHandlingModelChangeRef.current) return
isHandlingModelChangeRef.current = false
startTransition(() => {
handleVisionConfigAfterModelChanged()
})
}, [handleVisionConfigAfterModelChanged, isVisionModel])
const handleQueryVarChange = useCallback(
(newVar: ValueSelector | string) => {
const newInputs = produce(inputs, (draft) => {
draft.query_variable_selector = newVar as ValueSelector
})
setInputs(newInputs)
},
[inputs, setInputs],
)
useEffect(() => {
const isReady = defaultConfig && Object.keys(defaultConfig).length > 0
if (!isReady) return
const currentInputs = inputRef.current
let shouldUpdate = false
const nextInputs = produce(currentInputs, (draft) => {
if (!draft.model) draft.model = defaultConfig.model
if (!draft.classes) draft.classes = defaultConfig.classes
if (!draft._targetBranches) draft._targetBranches = defaultConfig._targetBranches
if (!draft.vision) draft.vision = defaultConfig.vision
if (
!isSnippetFlow &&
draft.query_variable_selector.length === 0 &&
isChatflow &&
startNodeId
) {
draft.query_variable_selector = [startNodeId, 'sys.query']
shouldUpdate = true
}
if (!currentInputs.model && defaultConfig.model) shouldUpdate = true
if (!currentInputs.classes && defaultConfig.classes) shouldUpdate = true
if (!currentInputs._targetBranches && defaultConfig._targetBranches) shouldUpdate = true
if (!currentInputs.vision && defaultConfig.vision) shouldUpdate = true
})
if (!shouldUpdate) return
startTransition(() => {
setInputs(nextInputs)
})
}, [defaultConfig, isChatflow, isSnippetFlow, setInputs, startNodeId])
const handleClassesChange = useCallback(
(newClasses: Topic[]) => {
const newInputs = produce(inputs, (draft) => {
draft.classes = newClasses
draft._targetBranches = newClasses.map((item: Topic) => ({
id: item.id,
name: item.name,
}))
})
setInputs(newInputs)
},
[inputs, setInputs],
)
const filterInputVar = useCallback((varPayload: Var) => {
const scalarVariableTypes: readonly VarType[] = [VarType.number, VarType.string]
return scalarVariableTypes.includes(varPayload.type)
}, [])
const filterVisionInputVar = useCallback((varPayload: Var) => {
const fileVariableTypes: readonly VarType[] = [VarType.file, VarType.arrayFile]
return fileVariableTypes.includes(varPayload.type)
}, [])
const { availableVars, availableNodesWithParent } = useAvailableVarList(id, {
onlyLeafNodeVar: false,
filterVar: filterInputVar,
})
const { availableVars: availableVisionVars } = useAvailableVarList(id, {
onlyLeafNodeVar: false,
filterVar: filterVisionInputVar,
})
const hasSetBlockStatus = {
history: false,
query: isChatflow ? checkHasQueryBlock(inputs.instruction) : false,
context: false,
}
const handleInstructionChange = useCallback(
(instruction: string) => {
const newInputs = produce(inputs, (draft) => {
draft.instruction = instruction
})
setInputs(newInputs)
},
[inputs, setInputs],
)
const handleMemoryChange = useCallback(
(memory?: Memory) => {
const newInputs = produce(inputs, (draft) => {
draft.memory = memory
})
setInputs(newInputs)
},
[inputs, setInputs],
)
const filterVar = useCallback((varPayload: Var) => {
return varPayload.type === VarType.string
}, [])
const handleSortTopic = useCallback(
(newTopics: (Topic & { id: string })[]) => {
const newInputs = produce(inputs, (draft) => {
const sortedTopics = newTopics.filter(Boolean)
draft.classes = sortedTopics.map((item) => ({
id: item.id,
name: item.name,
label: item.label,
}))
draft._targetBranches = sortedTopics.map((item) => ({
id: item.id,
name: item.name,
}))
})
setInputs(newInputs)
updateNodeInternals(id)
},
[id, inputs, setInputs, updateNodeInternals],
)
return {
readOnly,
inputs,
handleModelChanged,
isChatflow,
isChatModel,
handleCompletionParamsChange,
handleQueryVarChange,
filterVar,
handleTopicsChange: handleClassesChange,
hasSetBlockStatus,
availableVars,
availableNodesWithParent,
availableVisionVars,
handleInstructionChange,
handleMemoryChange,
isVisionModel,
handleVisionResolutionEnabledChange,
handleVisionResolutionChange,
handleSortTopic,
}
}
export default useConfig
@@ -0,0 +1,159 @@
import type { RefObject } from 'react'
import type { QuestionClassifierNodeType } from './types'
import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'
import type { InputVar, Var, Variable } from '@/app/components/workflow/types'
import { noop } from 'es-toolkit/function'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { InputVarType, VarType } from '@/app/components/workflow/types'
import useConfigVision from '../../hooks/use-config-vision'
import useAvailableVarList from '../_base/hooks/use-available-var-list'
import useNodeCrud from '../_base/hooks/use-node-crud'
import { findVariableWhenOnLLMVision } from '../utils'
const i18nPrefix = 'nodes.questionClassifiers'
type Params = {
id: string
payload: QuestionClassifierNodeType
runInputData: Record<string, any>
runInputDataRef: RefObject<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,
}: Params) => {
const { t } = useTranslation(['workflow', 'workflowModels'])
const { inputs } = useNodeCrud<QuestionClassifierNodeType>(id, payload)
const model = inputs.model
const { isVisionModel } = useConfigVision(model, {
payload: inputs.vision,
onChange: noop,
})
const visionFiles = runInputData['#files#']
const setVisionFiles = useCallback(
(newFiles: unknown[]) => {
setRunInputData?.({
...runInputDataRef.current,
'#files#': newFiles,
})
},
[runInputDataRef, setRunInputData],
)
const varInputs = getInputVars([inputs.instruction])
const inputVarValues = (() => {
const vars: Record<string, any> = {}
Object.keys(runInputData)
.filter((key) => !['#files#'].includes(key))
.forEach((key) => {
vars[key] = runInputData[key]
})
return vars
})()
const setInputVarValues = useCallback(
(newPayload: Record<string, unknown>) => {
const newVars = {
...newPayload,
'#files#': runInputDataRef.current['#files#'],
}
setRunInputData?.(newVars)
},
[runInputDataRef, setRunInputData],
)
const filterVisionInputVar = useCallback((varPayload: Var) => {
const fileVariableTypes: readonly VarType[] = [VarType.file, VarType.arrayFile]
return fileVariableTypes.includes(varPayload.type)
}, [])
const { availableVars: availableVisionVars } = useAvailableVarList(id, {
onlyLeafNodeVar: false,
filterVar: filterVisionInputVar,
})
const forms = (() => {
const forms: FormProps[] = []
forms.push({
label: t(($) => $['nodes.llm.singleRun.variable'], { ns: 'workflowModels' })!,
inputs: [
{
label: t(($) => $[`${i18nPrefix}.inputVars`], { ns: 'workflow' })!,
variable: 'query',
type: InputVarType.paragraph,
required: true,
},
...varInputs,
],
values: inputVarValues,
onChange: setInputVarValues,
})
if (isVisionModel && payload.vision?.enabled && payload.vision?.configs?.variable_selector) {
const currentVariable = findVariableWhenOnLLMVision(
payload.vision.configs.variable_selector,
availableVisionVars,
)
forms.push({
label: t(($) => $['nodes.llm.vision'], { ns: 'workflowModels' })!,
inputs: [
{
label: currentVariable?.variable as any,
variable: '#files#',
type: currentVariable?.formType as any,
required: false,
},
],
values: { '#files#': visionFiles },
onChange: (keyValue) => setVisionFiles(keyValue['#files#']),
})
}
return forms
})()
const getDependentVars = () => {
const promptVars = varInputs
.map((item) => {
// Guard against null/undefined variable to prevent app crash
if (!item.variable || typeof item.variable !== 'string') return []
return item.variable.slice(1, -1).split('.')
})
.filter((arr) => arr.length > 0)
const vars = [payload.query_variable_selector, ...promptVars]
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 === 'query') return payload.query_variable_selector
if (variable === '#files#') return payload.vision.configs?.variable_selector
return false
}
return {
forms,
getDependentVars,
getDependentVar,
}
}
export default useSingleRunFormParams