Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
test(web): exercise workflow behavior through real stores (#44622)
Stephen Zhou6d4b08f5f935
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-rag-pipeline-search.spec.tsx b/web/app/components/rag-pipeline/hooks/__tests__/use-rag-pipeline-search.spec.tsxindex 484a6dc11d8..b4f8f6ca591 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-rag-pipeline-search.spec.tsx+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-rag-pipeline-search.spec.tsx@@ -1,21 +1,12 @@-import { renderHook } from '@testing-library/react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { describe, expect, it, vi } from 'vite-plus/test'+import { createNode } from '@/app/components/workflow/__tests__/fixtures'+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'import { BlockEnum } from '@/app/components/workflow/types'+import { seedModelProviderQueries } from '@/test/console/model-provider'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import { findRagPipelineNodes } from '../../goto-anything-search'import { useRagPipelineSearch } from '../use-rag-pipeline-search'-const mockNodes: Array<{ id: string; data: Record<string, unknown> }> = []-vi.mock('@/app/components/workflow/store/workflow/use-nodes', () => ({- default: () => mockNodes,-}))--const mockHandleNodeSelect = vi.fn()-vi.mock('@/app/components/workflow/hooks/use-nodes-interactions', () => ({- useNodesInteractions: () => ({- handleNodeSelect: mockHandleNodeSelect,- }),-}))-vi.mock('@/app/components/workflow/hooks/use-tool-icon', () => ({useGetToolIcon: () => () => null,}))@@ -24,24 +15,19 @@ vi.mock('@/app/components/workflow/block-icon', () => ({default: () => null,}))-const mockCleanupListener = vi.fn()-vi.mock('@/app/components/workflow/utils/node-navigation', () => ({- setupNodeSelectionListener: () => mockCleanupListener,-}))--describe('useRagPipelineSearch', () => {- beforeEach(() => {- vi.clearAllMocks()- mockNodes.length = 0- })-- afterEach(() => {- vi.clearAllMocks()+const renderSearch = (nodes: ReturnType<typeof createNode>[] = []) => {+ const { queryClient } = createConsoleQueryWrapper({ appDslVersion: '1.0' })+ seedModelProviderQueries(queryClient)+ return renderWorkflowCanvasHook(() => useRagPipelineSearch(), {+ queryClient,+ initialStoreState: { nodes },})+}+describe('useRagPipelineSearch', () => {describe('hook lifecycle', () => {it('should expose empty search results when no nodes exist', () => {- const { unmount } = renderHook(() => useRagPipelineSearch())+ const { unmount } = renderSearch()expect(findRagPipelineNodes('LLM')).toEqual([])@@ -49,57 +35,54 @@ describe('useRagPipelineSearch', () => {})it('should cleanup search function on unmount', () => {- mockNodes.push({- id: 'node-1',- data: { type: BlockEnum.Start, title: 'Start', desc: '' },- })-- const { unmount } = renderHook(() => useRagPipelineSearch())+ const { unmount } = renderSearch([+ createNode({+ id: 'node-1',+ data: { type: BlockEnum.Start, title: 'Start', desc: '' },+ }),+ ])expect(findRagPipelineNodes('Start')).not.toEqual([])unmount()expect(findRagPipelineNodes('Start')).toEqual([])- expect(mockCleanupListener).toHaveBeenCalledOnce()})})describe('search functionality', () => {- beforeEach(() => {- mockNodes.push(- {- id: 'node-1',- data: { type: BlockEnum.LLM, title: 'GPT Model', desc: 'Language model' },- },- {- id: 'node-2',- data: {- type: BlockEnum.KnowledgeRetrieval,- title: 'Knowledge Base',- desc: 'Search knowledge',- dataset_ids: ['ds1', 'ds2'],- },- },- {- id: 'node-3',- data: {- type: BlockEnum.Tool,- title: 'Web Search',- desc: '',- tool_description: 'Search the web',- tool_label: 'WebSearch',- },+ const nodes = [+ createNode({+ id: 'node-1',+ data: { type: BlockEnum.LLM, title: 'GPT Model', desc: 'Language model' },+ }),+ createNode({+ id: 'node-2',+ data: {+ type: BlockEnum.KnowledgeRetrieval,+ title: 'Knowledge Base',+ desc: 'Search knowledge',+ dataset_ids: ['ds1', 'ds2'],},- {- id: 'node-4',- data: { type: BlockEnum.Start, title: 'Start Node', desc: 'Pipeline entry' },+ }),+ createNode({+ id: 'node-3',+ data: {+ type: BlockEnum.Tool,+ title: 'Web Search',+ desc: '',+ tool_description: 'Search the web',+ tool_label: 'WebSearch',},- )- })+ }),+ createNode({+ id: 'node-4',+ data: { type: BlockEnum.Start, title: 'Start Node', desc: 'Pipeline entry' },+ }),+ ]it('should find nodes by title', () => {- renderHook(() => useRagPipelineSearch())+ renderSearch(nodes)const results = findRagPipelineNodes('GPT')@@ -107,7 +90,7 @@ describe('useRagPipelineSearch', () => {})it('should find nodes by type', () => {- renderHook(() => useRagPipelineSearch())+ renderSearch(nodes)const results = findRagPipelineNodes(BlockEnum.LLM)@@ -115,7 +98,7 @@ describe('useRagPipelineSearch', () => {})it('should sort by alphabetical order when no search term', () => {- renderHook(() => useRagPipelineSearch())+ renderSearch(nodes)const results = findRagPipelineNodes('')const titles = results.map((r) => r.title)@@ -124,7 +107,7 @@ describe('useRagPipelineSearch', () => {})it('should sort by relevance score when search term provided', () => {- renderHook(() => useRagPipelineSearch())+ renderSearch(nodes)const results = findRagPipelineNodes('Search')@@ -132,7 +115,7 @@ describe('useRagPipelineSearch', () => {})it('should return empty array when no nodes match', () => {- renderHook(() => useRagPipelineSearch())+ renderSearch(nodes)const results = findRagPipelineNodes('nonexistent-xyz-12345')@@ -140,7 +123,7 @@ describe('useRagPipelineSearch', () => {})it('should enhance Tool node description from tool_description', () => {- renderHook(() => useRagPipelineSearch())+ renderSearch(nodes)const results = findRagPipelineNodes('web')@@ -150,7 +133,7 @@ describe('useRagPipelineSearch', () => {})it('should include metadata with nodeId', () => {- renderHook(() => useRagPipelineSearch())+ renderSearch(nodes)const results = findRagPipelineNodes('Start')diff --git a/web/app/components/snippets/hooks/__tests__/use-snippet-start-run.spec.ts b/web/app/components/snippets/hooks/__tests__/use-snippet-start-run.spec.tsindex 978fb6c54c2..dd3feb9c945 100644--- a/web/app/components/snippets/hooks/__tests__/use-snippet-start-run.spec.ts+++ b/web/app/components/snippets/hooks/__tests__/use-snippet-start-run.spec.ts@@ -2,19 +2,14 @@ import type { InputVar } from '@/models/pipeline'import { act } from '@testing-library/react'import {baseRunningData,- renderWorkflowHook,+ renderWorkflowCanvasHook,} from '@/app/components/workflow/__tests__/workflow-test-env'+import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { PipelineInputVarType } from '@/models/pipeline'import { useSnippetDraftStore } from '../../draft-store'import { useSnippetStartRun } from '../use-snippet-start-run'-const mockHandleCancelDebugAndPreviewPanel = vi.fn()const mockHandleRun = vi.fn()-vi.mock('@/app/components/workflow/hooks/use-workflow-panel-interactions', () => ({- useWorkflowInteractions: () => ({- handleCancelDebugAndPreviewPanel: mockHandleCancelDebugAndPreviewPanel,- }),-}))const inputFields: InputVar[] = [{@@ -26,7 +21,7 @@ const inputFields: InputVar[] = []const renderStart = (initialStoreState = {}) =>- renderWorkflowHook(() => useSnippetStartRun({ handleRun: mockHandleRun }), {+ renderWorkflowCanvasHook(() => useSnippetStartRun({ handleRun: mockHandleRun }), {resource: { kind: 'snippet', snippetId: 'snippet-1' },initialStoreState: { showEnvPanel: true, showGlobalVariablePanel: true, ...initialStoreState },})@@ -60,10 +55,16 @@ it('runs immediately without leaving an old input form visible when there are no})it('closes an already open debug panel without starting another run', () => {- const { result } = renderStart({ showDebugAndPreviewPanel: true })+ const { result, store } = renderStart({+ showDebugAndPreviewPanel: true,+ workflowRunningData: baseRunningData({ result: { status: WorkflowRunningStatus.Succeeded } }),+ })act(() => result.current.handleWorkflowStartRunInWorkflow())- expect(mockHandleCancelDebugAndPreviewPanel).toHaveBeenCalledOnce()+ expect(store.getState()).toMatchObject({+ showDebugAndPreviewPanel: false,+ workflowRunningData: undefined,+ })expect(mockHandleRun).not.toHaveBeenCalled()})@@ -77,5 +78,4 @@ it('leaves panels and the active run unchanged while already running', () => {showGlobalVariablePanel: true,})expect(mockHandleRun).not.toHaveBeenCalled()- expect(mockHandleCancelDebugAndPreviewPanel).not.toHaveBeenCalled()})diff --git a/web/app/components/workflow/__tests__/inspect-vars-provider.tsx b/web/app/components/workflow/__tests__/inspect-vars-provider.tsxnew file mode 100644index 00000000000..e280009abe8--- /dev/null+++ b/web/app/components/workflow/__tests__/inspect-vars-provider.tsx@@ -0,0 +1,9 @@+import type { ReactNode } from 'react'+import { HooksStoreContextProvider } from '../hooks-store/provider'+import { useInspectVarsCrudCommon } from '../hooks/use-inspect-vars-crud-common'++// Compose the same inspector owner and facade as the editor providers.+export function InspectVarsProvider({ children }: { children: ReactNode }) {+ const inspect = useInspectVarsCrudCommon()+ return <HooksStoreContextProvider {...inspect}>{children}</HooksStoreContextProvider>+}diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/use-last-run.spec.ts b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/use-last-run.spec.tsindex f44e17180c1..2d133c69ee1 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/use-last-run.spec.ts+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/use-last-run.spec.ts@@ -2,84 +2,46 @@ import type { IterationNodeType } from '@/app/components/workflow/nodes/iteratioimport type { ListFilterNodeType } from '@/app/components/workflow/nodes/list-operator/types'import type { Node } from '@/app/components/workflow/types'import { act } from '@testing-library/react'-import { renderWorkflowHook } from '@/app/components/workflow/__tests__/workflow-test-env'-import { BlockEnum, ErrorHandleMode, VarType } from '@/app/components/workflow/types'+import { useStoreApi } from 'reactflow'+import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'+import {+ BlockEnum,+ ErrorHandleMode,+ NodeRunningStatus,+ VarType,+} from '@/app/components/workflow/types'import useLastRun from '../use-last-run'-const mockHandleSyncWorkflowDraft = vi.fn()-const mockHandleRun = vi.fn()-const mockIterationChildren = vi.hoisted(() => vi.fn())--vi.mock('../../../../../../hooks/use-workflow', async (importOriginal) => {- const actual = await importOriginal<typeof import('../../../../../../hooks/use-workflow')>()+const request = vi.hoisted(() => vi.fn())+vi.mock('@/service/base', () => ({ ssePost: request }))+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleResponses } = await import('@/test/console/service-responses')return {...actual,- useWorkflow: () => ({- getIterationNodeChildren: mockIterationChildren,- getBeforeNodesInSameBranch: () => [],- }),- useIsNodeInIteration: () => ({ isNodeInIteration: () => false }),- }-})--vi.mock('../../../../../../hooks/use-nodes-sync-draft', async (importOriginal) => {- const actual =- await importOriginal<typeof import('../../../../../../hooks/use-nodes-sync-draft')>()-- return {- ...actual,- useNodesSyncDraft: () => ({- handleSyncWorkflowDraft: mockHandleSyncWorkflowDraft,+ consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'spec.schemaDefinitions.get': async () => [],+ 'workspaces.current.tools.builtin.get': async () => [],+ 'workspaces.current.tools.api.get': async () => [],+ 'workspaces.current.tools.workflow.get': async () => [],+ 'workspaces.current.tools.mcp.get': async () => [],}),}})+// Checklist validation owns its own suite; this test follows container submission.vi.mock('../../../../../../hooks/use-checklist', () => ({useWorkflowRunValidation: () => ({warningNodes: [],}),}))-vi.mock('../../../../../../hooks/use-inspect-vars-crud', () => ({- default: () => ({- conversationVars: [],- systemVars: [],- hasSetInspectVar: vi.fn(() => false),- }),-}))--vi.mock('@/app/components/workflow/nodes/_base/hooks/use-one-step-run', () => ({- default: () => ({- hideSingleRun: vi.fn(),- handleRun: mockHandleRun,- getInputVars: vi.fn(() => []),- toVarInputs: vi.fn(() => []),- varSelectorsToVarInputs: vi.fn(() => []),- runInputData: {},- runInputDataRef: { current: {} },- setRunInputData: vi.fn(),- showSingleRun: vi.fn(),- runResult: {},- iterationRunResult: [],- loopRunResult: [],- setNodeRunning: vi.fn(),- checkValid: vi.fn(() => ({ isValid: true })),- }),-}))--vi.mock('@/service/use-workflow', () => ({- useInvalidateLastRun: () => vi.fn(),-}))-describe('useLastRun', () => {- beforeEach(() => {- vi.clearAllMocks()- mockHandleSyncWorkflowDraft.mockReset()- })-it('submits list inputs from the real container form using selector keys', async () => {const child: Node<ListFilterNodeType> = {id: 'list',+ parentId: 'iteration',position: { x: 0, y: 0 },data: {type: BlockEnum.ListFilter,@@ -97,8 +59,6 @@ describe('useLastRun', () => {limit: { enabled: false },},}- mockIterationChildren.mockReturnValue([child])- mockHandleSyncWorkflowDraft.mockImplementation((_force, _sync, options) => options.onSuccess())const data: IterationNodeType = {type: BlockEnum.Iteration,title: 'Iteration',@@ -115,14 +75,47 @@ describe('useLastRun', () => {_children: [{ nodeId: 'list', nodeType: BlockEnum.ListFilter }],_isShowTips: false,}- const { result } = renderWorkflowHook(() =>- useLastRun({- id: 'iteration',- resource: { kind: 'app', appId: 'flow-id', mode: 'workflow' },- data,- defaultRunInputData: {},- isPaused: false,+ const { result } = renderWorkflowCanvasHook(+ () => ({+ ...useLastRun({+ id: 'iteration',+ resource: { kind: 'app', appId: 'flow-id', mode: 'workflow' },+ data,+ defaultRunInputData: {},+ isPaused: false,+ }),+ flow: useStoreApi(),}),+ {+ resource: { kind: 'app', appId: 'flow-id', mode: 'workflow' },+ nodes: [+ createNode({+ id: 'source',+ data: {+ type: BlockEnum.Code,+ outputs: {+ items: { type: VarType.arrayNumber },+ minimum: { type: VarType.number },+ serial: { type: VarType.number },+ },+ },+ }),+ createNode({ id: 'iteration', data }),+ createNode({+ id: 'iteration-start',+ parentId: 'iteration',+ data: { type: BlockEnum.IterationStart },+ }),+ child,+ ],+ edges: [+ createEdge({ source: 'source', target: 'iteration' }),+ createEdge({ source: 'iteration-start', target: 'list' }),+ ],+ hooksStoreProps: {+ doSyncWorkflowDraft: async (_skip, callbacks) => callbacks?.onSuccess?.(),+ },+ },)await act(async () => {@@ -134,11 +127,25 @@ describe('useLastRun', () => {})})- expect(mockHandleRun).toHaveBeenCalledWith({- 'list.#source.items#': [1, 2],- 'list.#source.minimum#': 0,- 'list.#source.serial#': 1,- 'iteration.input_selector': [1, 2],- })+ expect(request).toHaveBeenCalledWith(+ 'apps/flow-id/workflows/draft/iteration/nodes/iteration/run',+ {+ body: {+ inputs: {+ 'list.#source.items#': [1, 2],+ 'list.#source.minimum#': 0,+ 'list.#source.serial#': 1,+ 'iteration.input_selector': [1, 2],+ },+ },+ },+ expect.any(Object),+ )+ expect(+ result.current.flow+ .getState()+ .getNodes()+ .find((node) => node.id === 'iteration')?.data._singleRunningStatus,+ ).toBe(NodeRunningStatus.Running)})})diff --git a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-node-crud.spec.ts b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-node-crud.spec.tsindex 7d74f22bed7..51b80e7a623 100644--- a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-node-crud.spec.ts+++ b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-node-crud.spec.ts@@ -1,27 +1,12 @@import type { CommonNodeType } from '@/app/components/workflow/types'-import { renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { useStoreApi } from 'reactflow'+import { createNode } from '@/app/components/workflow/__tests__/fixtures'+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'import { BlockEnum } from '@/app/components/workflow/types'import useNodeCrud from '../use-node-crud'-const mockHandleNodeDataUpdateWithSyncDraft = vi.hoisted(() => ({- current: vi.fn(),-}))--vi.mock('../../../../hooks/use-node-data-update', async (importOriginal) => {- const actual = await importOriginal<typeof import('../../../../hooks/use-node-data-update')>()-- return {- ...actual,- useNodeDataUpdate: () => ({- handleNodeDataUpdateWithSyncDraft: mockHandleNodeDataUpdateWithSyncDraft.current,- }),- }-})--type TestNodeData = CommonNodeType<{- value: string-}>-+type TestNodeData = CommonNodeType<{ value: string }>const createData = (value = 'initial'): TestNodeData => ({type: BlockEnum.LLM,title: 'Test Node',@@ -29,40 +14,41 @@ const createData = (value = 'initial'): TestNodeData => ({value,})-describe('useNodeCrud', () => {- beforeEach(() => {- vi.clearAllMocks()- mockHandleNodeDataUpdateWithSyncDraft.current = vi.fn()- })-- it('forwards node data updates with the current node id and latest updater', () => {- const { result, rerender } = renderHook(({ id, data }) => useNodeCrud(id, data), {- initialProps: {- id: 'node-1',- data: createData(),- },- })-- result.current.setInputs(createData('changed'))-- expect(mockHandleNodeDataUpdateWithSyncDraft.current).toHaveBeenCalledWith({- id: 'node-1',- data: createData('changed'),- })-- const nextUpdater = vi.fn()- mockHandleNodeDataUpdateWithSyncDraft.current = nextUpdater-- rerender({- id: 'node-2',- data: createData('changed'),- })-- result.current.setInputs(createData('latest'))-- expect(nextUpdater).toHaveBeenCalledWith({- id: 'node-2',- data: createData('latest'),- })- })+it('saves edits to the current node after switching the editor to another node', () => {+ const { result, rerender } = renderWorkflowCanvasHook(+ ({ id, data }) => ({+ ...useNodeCrud(id, data),+ flow: useStoreApi(),+ }),+ {+ initialProps: { id: 'node-1', data: createData() },+ nodes: [+ createNode({ id: 'node-1', data: createData() }),+ createNode({ id: 'node-2', data: createData() }),+ ],+ },+ )++ act(() => result.current.setInputs(createData('changed')))+ expect(+ result.current.flow+ .getState()+ .getNodes()+ .map((node) => [node.id, node.data.value]),+ ).toEqual([+ ['node-1', 'changed'],+ ['node-2', 'initial'],+ ])++ rerender({ id: 'node-2', data: createData() })+ act(() => result.current.setInputs(createData('latest')))+ expect(+ result.current.flow+ .getState()+ .getNodes()+ .map((node) => [node.id, node.data.value]),+ ).toEqual([+ ['node-1', 'changed'],+ ['node-2', 'latest'],+ ])})diff --git a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-output-var-list.spec.ts b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-output-var-list.spec.tsindex a9ed58915e4..e9b841c7b56 100644--- a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-output-var-list.spec.ts+++ b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-output-var-list.spec.ts@@ -1,47 +1,36 @@import type { CodeNodeType } from '@/app/components/workflow/nodes/code/types'-import { act, renderHook } from '@testing-library/react'+import type { VarInInspect } from '@/types/workflow'+import { act } from '@testing-library/react'+import { useState } from 'react'+import { useNodes, useStoreApi } from 'reactflow'+import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'+import { InspectVarsProvider } from '@/app/components/workflow/__tests__/inspect-vars-provider'+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'import { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'import { BlockEnum, VarType } from '@/app/components/workflow/types'+import useNodeCrud from '../use-node-crud'import useOutputVarList from '../use-output-var-list'-const mockSetInputs = vi.hoisted(() => vi.fn())-const mockOnOutputKeyOrdersChange = vi.hoisted(() => vi.fn())-const mockHandleOutVarRenameChange = vi.hoisted(() => vi.fn())-const mockIsVarUsedInNodes = vi.hoisted(() => vi.fn())-const mockRemoveUsedVarInNodes = vi.hoisted(() => vi.fn())-const mockDeleteInspectVar = vi.hoisted(() => vi.fn())-const mockRenameInspectVarName = vi.hoisted(() => vi.fn())-const inspectState = vi.hoisted(() => ({- nodesWithInspectVars: [] as Array<{- nodeId: string- vars: Array<{ id: string; name: string }>- }>,-}))--vi.mock('@/app/components/workflow/hooks/use-workflow', async (importOriginal) => {- const actual =- await importOriginal<typeof import('@/app/components/workflow/hooks/use-workflow')>()-+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleResponses, withConsoleClientResponses } =+ await import('@/test/console/service-responses')return {...actual,- useWorkflow: () => ({- handleOutVarRenameChange: (...args: unknown[]) => mockHandleOutVarRenameChange(...args),- isVarUsedInNodes: (...args: unknown[]) => mockIsVarUsedInNodes(...args),- removeUsedVarInNodes: (...args: unknown[]) => mockRemoveUsedVarInNodes(...args),+ consoleClient: withConsoleClientResponses(actual.consoleClient, {+ 'apps.byAppId.workflows.draft.variables.byVariableId.delete': async () => ({}),+ 'apps.byAppId.workflows.draft.variables.byVariableId.patch': async () => ({}),+ }),+ consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'workspaces.current.tools.builtin.get': async () => [],+ 'workspaces.current.tools.api.get': async () => [],+ 'workspaces.current.tools.workflow.get': async () => [],+ 'workspaces.current.tools.mcp.get': async () => [],}),}})-vi.mock('@/app/components/workflow/hooks/use-inspect-vars-crud', () => ({- __esModule: true,- default: () => ({- deleteInspectVar: (...args: unknown[]) => mockDeleteInspectVar(...args),- renameInspectVarName: (...args: unknown[]) => mockRenameInspectVarName(...args),- nodesWithInspectVars: inspectState.nodesWithInspectVars,- }),-}))-const createPayload = (overrides: Partial<CodeNodeType> = {}): CodeNodeType => ({title: 'Code',desc: '',@@ -56,287 +45,245 @@ const createPayload = (overrides: Partial<CodeNodeType> = {}): CodeNodeType => (...overrides,})-const renderUseOutputVarList = (- payload: CodeNodeType = createPayload(),- outputKeyOrders: string[] = Object.keys(payload.outputs),-) =>- renderHook(() =>- useOutputVarList<CodeNodeType>({- id: 'code-node',- inputs: payload,- setInputs: mockSetInputs,- outputKeyOrders,- onOutputKeyOrdersChange: mockOnOutputKeyOrdersChange,- }),- )+const inspected = (name: string, type: VarType): VarInInspect => ({+ id: `inspect-${name}`,+ type: 'node',+ name,+ description: '',+ selector: ['code-node', name],+ value_type: type,+ value: type === VarType.string ? 'cached' : 7,+ edited: false,+ visible: true,+ is_truncated: false,+ full_content: { size_bytes: 0, download_url: '' },+})-describe('useOutputVarList', () => {- beforeEach(() => {- vi.clearAllMocks()- mockIsVarUsedInNodes.mockReturnValue(false)- inspectState.nodesWithInspectVars = [- {- nodeId: 'code-node',- vars: [- { id: 'inspect-primary', name: 'primary' },- { id: 'inspect-secondary', name: 'secondary' },+function setup(payload = createPayload(), referenced = '', orders = Object.keys(payload.outputs)) {+ return renderWorkflowCanvasHook(+ () => {+ const inputs = useNodes<CodeNodeType>().find((node) => node.id === 'code-node')!.data+ const { setInputs } = useNodeCrud('code-node', inputs)+ const [outputKeyOrders, setOutputKeyOrders] = useState(orders)+ return {+ ...useOutputVarList({+ id: 'code-node',+ inputs,+ setInputs,+ outputKeyOrders,+ onOutputKeyOrdersChange: setOutputKeyOrders,+ }),+ inputs,+ outputKeyOrders,+ flow: useStoreApi(),+ }+ },+ {+ wrapper: InspectVarsProvider,+ nodes: [+ createNode({ id: 'code-node', data: payload }),+ createNode({+ id: 'consumer',+ data: createPayload({+ variables: referenced+ ? [{ variable: 'input', value_selector: ['code-node', referenced] }]+ : [],+ }),+ }),+ ],+ edges: [createEdge({ source: 'code-node', target: 'consumer' })],+ initialStoreState: {+ nodesWithInspectVars: [+ {+ nodeId: 'code-node',+ nodeType: BlockEnum.Code,+ title: 'Code',+ nodePayload: payload,+ vars: [inspected('primary', VarType.string), inspected('secondary', VarType.number)],+ },],},- ]- })-- it('removes the row right away when no other node uses the variable', () => {- const { result } = renderUseOutputVarList()-- act(() => {- result.current.handleRemoveVariable(0)- })-- expect(result.current.isShowRemoveVarConfirm).toBe(false)- expect(mockSetInputs).toHaveBeenCalledWith(- expect.objectContaining({- outputs: { secondary: { type: VarType.number, children: null } },- }),- )- expect(mockOnOutputKeyOrdersChange).toHaveBeenCalledWith(['secondary'])- expect(mockRemoveUsedVarInNodes).not.toHaveBeenCalled()- expect(mockDeleteInspectVar).toHaveBeenCalledWith('code-node', 'inspect-primary')- })-- it('removes the row after the confirmation when other nodes use the variable', () => {- mockIsVarUsedInNodes.mockReturnValue(true)- const { result } = renderUseOutputVarList()-- act(() => {- result.current.handleRemoveVariable(0)- })-- expect(result.current.isShowRemoveVarConfirm).toBe(true)- expect(mockSetInputs).not.toHaveBeenCalled()- expect(mockDeleteInspectVar).not.toHaveBeenCalled()-- act(() => {- result.current.onRemoveVarConfirm()- })-- expect(mockRemoveUsedVarInNodes).toHaveBeenCalledWith(['code-node', 'primary'])- expect(mockSetInputs).toHaveBeenCalledWith(- expect.objectContaining({- outputs: { secondary: { type: VarType.number, children: null } },- }),- )- expect(mockOnOutputKeyOrdersChange).toHaveBeenCalledWith(['secondary'])- expect(mockDeleteInspectVar).toHaveBeenCalledWith('code-node', 'inspect-primary')- expect(result.current.isShowRemoveVarConfirm).toBe(false)- })-- it('removes the confirmed row by its own index, not by the shared name', () => {- mockIsVarUsedInNodes.mockReturnValue(true)- const { result } = renderUseOutputVarList()-- act(() => {- result.current.handleRemoveVariable(1)- })- act(() => {- result.current.onRemoveVarConfirm()- })+ },+ )+}+const fallbacks: CodeNodeType['default_value'] = [+ { key: 'primary', type: VarType.string, value: 'sentinel' },+ { key: 'secondary', type: VarType.number, value: 7 },+]+afterEach(() => vi.useRealTimers())++it.each([+ { index: 0, name: 'primary', remaining: 'secondary' },+ { index: 1, name: 'secondary', remaining: 'primary' },+])('removes referenced $name only after confirmation', async ({ index, name, remaining }) => {+ const { result, store } = setup(createPayload(), name)+ await act(async () => result.current.handleRemoveVariable(index))+ expect(result.current.isShowRemoveVarConfirm).toBe(true)+ expect(result.current.inputs.outputs).toEqual(createPayload().outputs)+ expect(store.getState().nodesWithInspectVars[0]?.vars).toHaveLength(2)+ await act(async () => result.current.onRemoveVarConfirm())+ expect(result.current.isShowRemoveVarConfirm).toBe(false)+ expect(Object.keys(result.current.inputs.outputs)).toEqual([remaining])+ expect(result.current.outputKeyOrders).toEqual([remaining])+ expect(+ result.current.flow+ .getState()+ .getNodes()+ .find((node) => node.id === 'consumer')?.data.variables,+ ).toEqual([{ variable: 'input', value_selector: [] }])+ expect(store.getState().nodesWithInspectVars[0]?.vars.map((variable) => variable.name)).toEqual([+ remaining,+ ])+})- expect(mockRemoveUsedVarInNodes).toHaveBeenCalledWith(['code-node', 'secondary'])- expect(mockSetInputs).toHaveBeenCalledWith(- expect.objectContaining({- outputs: { primary: { type: VarType.string, children: null } },- }),- )- expect(mockOnOutputKeyOrdersChange).toHaveBeenCalledWith(['primary'])+it('removes an unused output and its inspected value immediately', async () => {+ const { result, store } = setup()+ await act(async () => result.current.handleRemoveVariable(0))+ expect(result.current.isShowRemoveVarConfirm).toBe(false)+ expect(result.current.inputs.outputs).toEqual({+ secondary: { type: VarType.number, children: null },})+ expect(result.current.outputKeyOrders).toEqual(['secondary'])+ expect(store.getState().nodesWithInspectVars[0]?.vars).toEqual([+ inspected('secondary', VarType.number),+ ])+})- it('keeps the row when the confirmation is cancelled', () => {- mockIsVarUsedInNodes.mockReturnValue(true)- const { result } = renderUseOutputVarList()-- act(() => {- result.current.handleRemoveVariable(0)- })- act(() => {- result.current.hideRemoveVarConfirm()- })+it('preserves the output, inspected values and downstream reference on cancellation', async () => {+ const { result, store } = setup(createPayload(), 'primary')+ await act(async () => result.current.handleRemoveVariable(0))+ act(() => result.current.hideRemoveVarConfirm())+ expect(result.current.isShowRemoveVarConfirm).toBe(false)+ expect(result.current.inputs.outputs).toEqual(createPayload().outputs)+ expect(result.current.outputKeyOrders).toEqual(['primary', 'secondary'])+ expect(store.getState().nodesWithInspectVars[0]?.vars).toHaveLength(2)+ expect(+ result.current.flow+ .getState()+ .getNodes()+ .find((node) => node.id === 'consumer')?.data.variables,+ ).toEqual([{ variable: 'input', value_selector: ['code-node', 'primary'] }])+})- expect(result.current.isShowRemoveVarConfirm).toBe(false)- expect(mockSetInputs).not.toHaveBeenCalled()- expect(mockDeleteInspectVar).not.toHaveBeenCalled()- expect(mockOnOutputKeyOrdersChange).not.toHaveBeenCalled()- expect(mockRemoveUsedVarInNodes).not.toHaveBeenCalled()+it('keeps the output and inspected value while another row has the same name', async () => {+ const { result, store } = setup(+ createPayload({ outputs: { primary: { type: VarType.string, children: null } } }),+ 'primary',+ ['primary', 'primary'],+ )+ await act(async () => result.current.handleRemoveVariable(0))+ await act(async () => result.current.onRemoveVarConfirm())+ expect(result.current.outputKeyOrders).toEqual(['primary'])+ expect(result.current.inputs.outputs).toEqual({+ primary: { type: VarType.string, children: null },})+ expect(store.getState().nodesWithInspectVars[0]?.vars).toContainEqual(+ inspected('primary', VarType.string),+ )+})- it('keeps the output entry when another row still shares the removed name', () => {- mockIsVarUsedInNodes.mockReturnValue(true)- const payload = createPayload({- outputs: { primary: { type: VarType.string, children: null } },- })- const { result } = renderUseOutputVarList(payload, ['primary', 'primary'])-- act(() => {- result.current.handleRemoveVariable(0)- })- act(() => {- result.current.onRemoveVarConfirm()- })-- expect(mockOnOutputKeyOrdersChange).toHaveBeenCalledWith(['primary'])- expect(mockSetInputs).toHaveBeenCalledWith(- expect.objectContaining({- outputs: { primary: { type: VarType.string, children: null } },- }),+it.each([true, false])(+ 'retains configured fallbacks after removal (referenced: %s)',+ async (referenced) => {+ const { result } = setup(+ createPayload({ error_strategy: ErrorHandleTypeEnum.defaultValue, default_value: fallbacks }),+ referenced ? 'secondary' : '',)- expect(mockDeleteInspectVar).not.toHaveBeenCalled()- })-- it('recomputes the default value after a confirmed removal', () => {- mockIsVarUsedInNodes.mockReturnValue(true)- const payload = createPayload({ error_strategy: ErrorHandleTypeEnum.defaultValue })- const { result } = renderUseOutputVarList(payload)-- act(() => {- result.current.handleRemoveVariable(1)- })- act(() => {- result.current.onRemoveVarConfirm()- })-- const lastInputs = mockSetInputs.mock.calls.at(-1)![0] as CodeNodeType- expect(lastInputs.default_value).toEqual([{ key: 'primary', type: VarType.string, value: '' }])- })-- it.each([true, false])(- 'keeps the remaining fallbacks when removing an output (confirmation: %s)',- (requiresConfirmation) => {- mockIsVarUsedInNodes.mockReturnValue(requiresConfirmation)- const payload = createPayload({- error_strategy: ErrorHandleTypeEnum.defaultValue,- default_value: [- { key: 'primary', type: VarType.string, value: 'sentinel' },- { key: 'secondary', type: VarType.number, value: 7 },- ],- })- const { result } = renderUseOutputVarList(payload)-- act(() => {- result.current.handleRemoveVariable(1)- })- if (requiresConfirmation) act(() => result.current.onRemoveVarConfirm())+ await act(async () => result.current.handleRemoveVariable(1))+ if (referenced) await act(async () => result.current.onRemoveVarConfirm())+ expect(result.current.inputs.default_value).toEqual([fallbacks[0]])+ },+)- const lastInputs = mockSetInputs.mock.calls.at(-1)![0] as CodeNodeType- expect(lastInputs.default_value).toEqual([- { key: 'primary', type: VarType.string, value: 'sentinel' },- ])- },+it('creates the remaining fallback when none was configured', async () => {+ const { result } = setup(+ createPayload({ error_strategy: ErrorHandleTypeEnum.defaultValue }),+ 'secondary',)+ await act(async () => result.current.handleRemoveVariable(1))+ await act(async () => result.current.onRemoveVarConfirm())+ expect(result.current.inputs.default_value).toEqual([+ { key: 'primary', type: VarType.string, value: '' },+ ])+})- it('keeps the configured fallbacks when another output is added', () => {- const payload = createPayload({- error_strategy: ErrorHandleTypeEnum.defaultValue,- default_value: [- { key: 'primary', type: VarType.string, value: 'sentinel' },- { key: 'secondary', type: VarType.number, value: 7 },- ],- })- const { result } = renderUseOutputVarList(payload)-- act(() => {- result.current.handleAddVariable()- })-- const lastInputs = mockSetInputs.mock.calls.at(-1)![0] as CodeNodeType- expect(lastInputs.default_value).toEqual([- { key: 'primary', type: VarType.string, value: 'sentinel' },- { key: 'secondary', type: VarType.number, value: 7 },- { key: 'var_3', type: VarType.string, value: '' },- ])- })-- it('carries the configured fallback over to the new name of a renamed output', () => {- const payload = createPayload({- error_strategy: ErrorHandleTypeEnum.defaultValue,- default_value: [- { key: 'primary', type: VarType.string, value: 'sentinel' },- { key: 'secondary', type: VarType.number, value: 7 },- ],- })- const { result } = renderUseOutputVarList(payload)-- act(() => {- result.current.handleVarsChange(- {- renamed: { type: VarType.string, children: null },- secondary: { type: VarType.number, children: null },- },- 0,- 'renamed',- )- })-- expect(mockOnOutputKeyOrdersChange).toHaveBeenCalledWith(['renamed', 'secondary'])- expect(mockHandleOutVarRenameChange).toHaveBeenCalledWith(- 'code-node',- ['code-node', 'primary'],- ['code-node', 'renamed'],- )- const lastInputs = mockSetInputs.mock.calls.at(-1)![0] as CodeNodeType- expect(lastInputs.default_value).toEqual([- { key: 'renamed', type: VarType.string, value: 'sentinel' },- { key: 'secondary', type: VarType.number, value: 7 },- ])- })-- it('only resets the fallback of the output whose type changed', () => {- const payload = createPayload({- error_strategy: ErrorHandleTypeEnum.defaultValue,- default_value: [- { key: 'primary', type: VarType.string, value: 'sentinel' },- { key: 'secondary', type: VarType.number, value: 7 },- ],- })- const { result } = renderUseOutputVarList(payload)+it('preserves existing fallbacks when adding an output', () => {+ const { result } = setup(+ createPayload({ error_strategy: ErrorHandleTypeEnum.defaultValue, default_value: fallbacks }),+ )+ act(() => result.current.handleAddVariable())+ expect(result.current.outputKeyOrders).toEqual(['primary', 'secondary', 'var_3'])+ expect(result.current.inputs.default_value).toEqual([+ ...fallbacks,+ { key: 'var_3', type: VarType.string, value: '' },+ ])+})- act(() => {- result.current.handleVarsChange({- primary: { type: VarType.string, children: null },- secondary: { type: VarType.string, children: null },- })- })+it('renames the output, fallback and downstream reference together', async () => {+ vi.useFakeTimers()+ const { result } = setup(+ createPayload({ error_strategy: ErrorHandleTypeEnum.defaultValue, default_value: fallbacks }),+ 'primary',+ )+ act(() =>+ result.current.handleVarsChange(+ {+ renamed: { type: VarType.string, children: null },+ secondary: { type: VarType.number, children: null },+ },+ 0,+ 'renamed',+ ),+ )+ expect(result.current.outputKeyOrders).toEqual(['renamed', 'secondary'])+ expect(result.current.inputs.default_value).toEqual([+ { ...fallbacks[0], key: 'renamed' },+ fallbacks[1],+ ])+ expect(+ result.current.flow+ .getState()+ .getNodes()+ .find((node) => node.id === 'consumer')?.data.variables,+ ).toEqual([{ variable: 'input', value_selector: ['code-node', 'renamed'] }])+ await act(async () => vi.advanceTimersByTimeAsync(501))+})- expect(mockDeleteInspectVar).toHaveBeenCalledExactlyOnceWith('code-node', 'inspect-secondary')- const lastInputs = mockSetInputs.mock.calls.at(-1)![0] as CodeNodeType- expect(lastInputs.default_value).toEqual([- { key: 'primary', type: VarType.string, value: 'sentinel' },- { key: 'secondary', type: VarType.string, value: '' },- ])- })+it('resets only the changed output fallback and stale inspected value', async () => {+ const { result, store } = setup(+ createPayload({ error_strategy: ErrorHandleTypeEnum.defaultValue, default_value: fallbacks }),+ )+ await act(async () =>+ result.current.handleVarsChange({+ primary: { type: VarType.string, children: null },+ secondary: { type: VarType.string, children: null },+ }),+ )+ expect(result.current.inputs.default_value).toEqual([+ fallbacks[0],+ { key: 'secondary', type: VarType.string, value: '' },+ ])+ expect(store.getState().nodesWithInspectVars[0]?.vars).toEqual([+ inspected('primary', VarType.string),+ ])+})- it('does not touch the fallbacks when the error strategy is not default-value', () => {- const payload = createPayload({+it('leaves fallbacks alone under the failure-branch strategy', async () => {+ const { result } = setup(+ createPayload({error_strategy: ErrorHandleTypeEnum.failBranch,- default_value: [{ key: 'primary', type: VarType.string, value: 'sentinel' }],- })- const { result } = renderUseOutputVarList(payload)-- act(() => {- result.current.handleRemoveVariable(1)- })+ default_value: [fallbacks[0]!],+ }),+ )+ await act(async () => result.current.handleRemoveVariable(1))+ expect(result.current.inputs.default_value).toEqual([fallbacks[0]])+})- const lastInputs = mockSetInputs.mock.calls.at(-1)![0] as CodeNodeType- expect(lastInputs.default_value).toEqual([- { key: 'primary', type: VarType.string, value: 'sentinel' },- ])- })- it('keeps inspected values when an output schema is unchanged', () => {- const { result } = renderUseOutputVarList()- act(() =>- result.current.handleVarsChange({- primary: { type: VarType.string, children: null },- secondary: { type: VarType.number, children: null },- }),- )- expect(mockDeleteInspectVar).not.toHaveBeenCalled()- })+it('preserves inspected values when the output schema is unchanged', async () => {+ const { result, store } = setup()+ await act(async () => result.current.handleVarsChange(createPayload().outputs))+ expect(store.getState().nodesWithInspectVars[0]?.vars).toEqual([+ inspected('primary', VarType.string),+ inspected('secondary', VarType.number),+ ])})diff --git a/web/app/components/workflow/nodes/data-source/__tests__/before-run-form.spec.tsx b/web/app/components/workflow/nodes/data-source/__tests__/before-run-form.spec.tsxindex 50688632782..ded0cb3ab19 100644--- a/web/app/components/workflow/nodes/data-source/__tests__/before-run-form.spec.tsx+++ b/web/app/components/workflow/nodes/data-source/__tests__/before-run-form.spec.tsx@@ -1,98 +1,146 @@import type { CustomRunFormProps, DataSourceNodeType } from '../types'-import { render, screen } from '@testing-library/react'+import type { DataSourceShape } from '@/app/components/datasets/documents/create-from-pipeline/data-source/store'+import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { useDataSourceStoreWithSelector } from '@/app/components/datasets/documents/create-from-pipeline/data-source/store'+import { useStoreApi } from 'reactflow'+import {+ useDataSourceStore,+ useDataSourceStoreWithSelector,+} from '@/app/components/datasets/documents/create-from-pipeline/data-source/store'+import { createNode } from '@/app/components/workflow/__tests__/fixtures'+import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'import { DatasourceType } from '@/models/pipeline'-import { BlockEnum } from '../../../types'+import { BlockEnum, NodeRunningStatus } from '../../../types'import BeforeRunForm from '../before-run-form'-import useBeforeRunForm from '../hooks/use-before-run-form'-const mockClearOnlineDocumentData = vi.hoisted(() => vi.fn())-const mockClearWebsiteCrawlData = vi.hoisted(() => vi.fn())-const mockClearOnlineDriveData = vi.hoisted(() => vi.fn())+const run = vi.hoisted(() => vi.fn())+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleResponses } = await import('@/test/console/service-responses')+ return {+ ...actual,+ consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'rag.pipelines.byPipelineId.workflows.draft.datasource.variablesInspect.post': run,+ }),+ }+})+vi.mock('@/service/workflow', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/service/workflow')>()),+ fetchNodeInspectVars: async () => [],+}))-function CredentialAction({- name,- credentialId,+const document: DataSourceShape['onlineDocuments'][number] = {+ workspace_id: 'workspace',+ page_id: 'page',+ page_name: 'Guide',+ page_icon: null,+ parent_id: '',+ type: 'page',+ is_bound: false,+}+const website: DataSourceShape['websitePages'][number] = {+ source_url: 'https://example.com',+ title: 'Guide',+ markdown: '# Guide',+ description: '',+}+const localFiles: DataSourceShape['localFileList'] = [+ {+ fileID: 'upload',+ progress: 100,+ file: Object.assign(new File(['pdf'], 'guide.pdf', { type: 'application/pdf' }), {+ id: 'file-1',+ extension: 'pdf',+ mime_type: 'application/pdf',+ }),+ },+]++// Uploading/browsing belongs to the independently tested datasource children.+// These controls exercise their public selection and credential callbacks against the real store.+function Selection({+ type,onCredentialChange,+ allowedExtensions,}: {- name: string- credentialId: string- onCredentialChange: (id: string) => void+ type: DatasourceType+ onCredentialChange?: (id: string) => void+ allowedExtensions?: string[]}) {- const currentCredentialId = useDataSourceStoreWithSelector((state) => state.currentCredentialId)+ const store = useDataSourceStore()+ const credential = useDataSourceStoreWithSelector((state) => state.currentCredentialId)+ const selected = useDataSourceStoreWithSelector(+ (state) =>+ state.localFileList.length ++ state.onlineDocuments.length ++ state.websitePages.length ++ state.selectedFileIds.length,+ )+ const select = () => {+ const state = store.getState()+ if (type === DatasourceType.localFile) state.setLocalFileList(localFiles)+ if (type === DatasourceType.onlineDocument) {+ state.setOnlineDocuments([document])+ state.setSelectedPagesId(new Set(['page']))+ state.setCurrentDocument(document)+ }+ if (type === DatasourceType.websiteCrawl) {+ state.setWebsitePages([website])+ state.setCurrentWebsite(website)+ state.setPreviewIndex(0)+ }+ if (type === DatasourceType.onlineDrive) {+ state.setOnlineDriveFileList([{ id: 'drive-file', name: 'Guide', type: 'file' }])+ state.setBucket('bucket')+ state.setSelectedFileIds(['drive-file'])+ }+ }return (<>- <button type="button" onClick={() => onCredentialChange(credentialId)}>- {name}+ <span>{allowedExtensions?.join(',')}</span>+ <button type="button" onClick={select}>+ Select Guide</button>- <output>{currentCredentialId}</output>+ <output aria-label="Selected documents">{selected}</output>+ <output aria-label="Credential">{credential}</output>+ {onCredentialChange && (+ <button type="button" onClick={() => onCredentialChange('new-credential')}>+ Switch credential+ </button>+ )}</>)}-vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/local-file', () => ({- __esModule: true,- default: ({ allowedExtensions }: { allowedExtensions: string[] }) => (- <div>{allowedExtensions.join(',')}</div>+ default: (props: { allowedExtensions: string[] }) => (+ <Selection {...props} type={DatasourceType.localFile} />),}))-vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/online-documents',() => ({- __esModule: true,- default: ({ onCredentialChange }: { onCredentialChange: (credentialId: string) => void }) => (- <CredentialAction- name="online-documents"- credentialId="credential-doc"- onCredentialChange={onCredentialChange}- />+ default: (props: { onCredentialChange: (id: string) => void }) => (+ <Selection {...props} type={DatasourceType.onlineDocument} />),}),)-vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/website-crawl',() => ({- __esModule: true,- default: ({ onCredentialChange }: { onCredentialChange: (credentialId: string) => void }) => (- <CredentialAction- name="website-crawl"- credentialId="credential-site"- onCredentialChange={onCredentialChange}- />+ default: (props: { onCredentialChange: (id: string) => void }) => (+ <Selection {...props} type={DatasourceType.websiteCrawl} />),}),)-vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/online-drive',() => ({- __esModule: true,- default: ({ onCredentialChange }: { onCredentialChange: (credentialId: string) => void }) => (- <CredentialAction- name="online-drive"- credentialId="credential-drive"- onCredentialChange={onCredentialChange}- />+ default: (props: { onCredentialChange: (id: string) => void }) => (+ <Selection {...props} type={DatasourceType.onlineDrive} />),}),)-vi.mock('@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks', () => ({- useOnlineDocument: () => ({ clearOnlineDocumentData: mockClearOnlineDocumentData }),- useWebsiteCrawl: () => ({ clearWebsiteCrawlData: mockClearWebsiteCrawlData }),- useOnlineDrive: () => ({ clearOnlineDriveData: mockClearOnlineDriveData }),-}))--vi.mock('../hooks/use-before-run-form', () => ({- __esModule: true,- default: vi.fn(),-}))--const mockUseBeforeRunForm = vi.mocked(useBeforeRunForm)-const createData = (overrides: Partial<DataSourceNodeType> = {}): DataSourceNodeType => ({title: 'Datasource',desc: '',@@ -123,110 +171,53 @@ const createProps = (overrides: Partial<CustomRunFormProps> = {}): CustomRunForm...overrides,})-describe('data-source/before-run-form', () => {- beforeEach(() => {- vi.clearAllMocks()- mockUseBeforeRunForm.mockReturnValue({- isPending: false,- handleRunWithSyncDraft: vi.fn(),- datasourceType: DatasourceType.localFile,- datasourceNodeData: createData(),- startRunBtnDisabled: false,- })+function setup(props = createProps()) {+ let flow: ReturnType<typeof useStoreApi>+ function Form() {+ flow = useStoreApi()+ return <BeforeRunForm {...props} />+ }+ renderWorkflowFlowComponent(<Form />, {+ resource: props.resource,+ nodes: [createNode({ id: props.nodeId, data: props.payload })],+ hooksStoreProps: { doSyncWorkflowDraft: async (_skip, callbacks) => callbacks?.onSuccess?.() },})+ return { props, nodeData: () => flow.getState().getNodes()[0]!.data }+}- it('renders the local-file preparation form and triggers run/cancel actions', async () => {- const user = userEvent.setup()- const onCancel = vi.fn()- const handleRunWithSyncDraft = vi.fn()-- mockUseBeforeRunForm.mockReturnValue({- isPending: false,- handleRunWithSyncDraft,- datasourceType: DatasourceType.localFile,- datasourceNodeData: createData(),- startRunBtnDisabled: false,- })-- render(<BeforeRunForm {...createProps({ onCancel })} />)-- expect(screen.getByText(/Datasource/)).toBeInTheDocument()- expect(screen.getByText('pdf,md')).toBeInTheDocument()-- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))- await user.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))-- expect(onCancel).toHaveBeenCalled()- expect(handleRunWithSyncDraft).toHaveBeenCalled()+beforeEach(() => run.mockResolvedValue({ id: 'run-1', status: NodeRunningStatus.Succeeded }))++it('runs the selected local file and exposes cancel through the form', async () => {+ const user = userEvent.setup()+ const { props, nodeData } = setup()+ expect(screen.getByText(/Datasource/)).toBeInTheDocument()+ expect(screen.getByText('pdf,md')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'Select Guide' }))+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ await user.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))+ await waitFor(() => expect(nodeData()._singleRunningStatus).toBe(NodeRunningStatus.Succeeded))+ expect(run).toHaveBeenCalledWith({+ params: { pipeline_id: 'flow-id' },+ body: expect.objectContaining({+ start_node_id: props.nodeId,+ datasource_type: DatasourceType.localFile,+ datasource_info: expect.objectContaining({ related_id: 'file-1', name: 'guide.pdf' }),+ }),})+ expect(props.onCancel).toHaveBeenCalledOnce()+})- it('clears stale online document data before switching credentials', async () => {+it.each([DatasourceType.onlineDocument, DatasourceType.websiteCrawl, DatasourceType.onlineDrive])(+ 'clears the previous %s selection when credentials change',+ async (type) => {const user = userEvent.setup()-- mockUseBeforeRunForm.mockReturnValue({- isPending: false,- handleRunWithSyncDraft: vi.fn(),- datasourceType: DatasourceType.onlineDocument,- datasourceNodeData: createData({ provider_type: DatasourceType.onlineDocument }),- startRunBtnDisabled: true,- })-- render(- <BeforeRunForm- {...createProps({ payload: createData({ provider_type: DatasourceType.onlineDocument }) })}- />,- )-- await user.click(screen.getByRole('button', { name: 'online-documents' }))-- expect(mockClearOnlineDocumentData).toHaveBeenCalled()- expect(screen.getByRole('status')).toHaveTextContent('credential-doc')+ setup(createProps({ payload: createData({ provider_type: type }) }))+ await user.click(screen.getByRole('button', { name: 'Select Guide' }))+ expect(screen.getByRole('status', { name: 'Selected documents' })).toHaveTextContent('1')+ expect(screen.getByRole('button', { name: 'workflow.singleRun.startRun' })).toBeEnabled()+ await user.click(screen.getByRole('button', { name: 'Switch credential' }))+ expect(screen.getByRole('status', { name: 'Credential' })).toHaveTextContent('new-credential')+ expect(screen.getByRole('status', { name: 'Selected documents' })).toHaveTextContent('0')expect(screen.getByRole('button', { name: 'workflow.singleRun.startRun' })).toBeDisabled()- })-- it('clears website crawl data before switching credentials', async () => {- const user = userEvent.setup()-- mockUseBeforeRunForm.mockReturnValue({- isPending: false,- handleRunWithSyncDraft: vi.fn(),- datasourceType: DatasourceType.websiteCrawl,- datasourceNodeData: createData({ provider_type: DatasourceType.websiteCrawl }),- startRunBtnDisabled: false,- })-- render(- <BeforeRunForm- {...createProps({ payload: createData({ provider_type: DatasourceType.websiteCrawl }) })}- />,- )-- await user.click(screen.getByRole('button', { name: 'website-crawl' }))-- expect(mockClearWebsiteCrawlData).toHaveBeenCalled()- expect(screen.getByRole('status')).toHaveTextContent('credential-site')- })-- it('clears online drive data before switching credentials', async () => {- const user = userEvent.setup()-- mockUseBeforeRunForm.mockReturnValue({- isPending: false,- handleRunWithSyncDraft: vi.fn(),- datasourceType: DatasourceType.onlineDrive,- datasourceNodeData: createData({ provider_type: DatasourceType.onlineDrive }),- startRunBtnDisabled: false,- })-- render(- <BeforeRunForm- {...createProps({ payload: createData({ provider_type: DatasourceType.onlineDrive }) })}- />,- )-- await user.click(screen.getByRole('button', { name: 'online-drive' }))-- expect(mockClearOnlineDriveData).toHaveBeenCalled()- expect(screen.getByRole('status')).toHaveTextContent('credential-drive')- })-})+ },+)diff --git a/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsxindex 25574d70540..03375eb75e6 100644--- a/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx+++ b/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx@@ -1,10 +1,12 @@import type { ComponentProps } from 'react'import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'-import { render, screen } from '@testing-library/react'+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 { useEdgesInteractions } from '../../../hooks/use-edges-interactions'import ClassList from '../../_base/components/branch-list/class-list'import AdvancedSetting from '../components/advanced-setting'@@ -45,16 +47,6 @@ vi.mock('../../_base/hooks/use-available-var-list', () => ({})),}))-vi.mock('../../../hooks/use-edges-interactions', async (importOriginal) => {- const actual = await importOriginal<typeof import('../../../hooks/use-edges-interactions')>()- return {- ...actual,- useEdgesInteractions: vi.fn(),- }-})--const mockUseEdgesInteractions = vi.mocked(useEdgesInteractions)-const createTopic = (overrides: Partial<Topic> = {}): Topic => ({id: 'topic-1',name: 'Billing questions',@@ -62,13 +54,6 @@ const createTopic = (overrides: Partial<Topic> = {}): Topic => ({})describe('question-classifier path', () => {- beforeEach(() => {- vi.clearAllMocks()- mockUseEdgesInteractions.mockReturnValue({- handleEdgeDeleteByDeleteBranch: vi.fn(),- } as unknown as ReturnType<typeof useEdgesInteractions>)- })-// Class editing and advanced settings share the real branch and memory controls.describe('Path Integration', () => {it('should render advanced settings and memory config', async () => {@@ -101,47 +86,63 @@ describe('question-classifier path', () => {it('adds, edits, removes and collapses classes while retaining unrelated branches', async () => {const user = userEvent.setup()- const onChange = vi.fn()- const removeEdge = vi.fn()- mockUseEdgesInteractions.mockReturnValue({- handleEdgeDeleteByDeleteBranch: removeEdge,- } as unknown as ReturnType<typeof useEdgesInteractions>)+ let flow: ReturnType<typeof useStoreApi>function ClassListHarness() {- const [list, setList] = useState([+ flow = useStoreApi()+ const [list, setList] = useState(() => [createTopic(),createTopic({ id: 'topic-2', name: 'Refunds' }),])- return (- <ClassList- nodeId="node-1"- list={list}- onChange={(next) => {- setList(next)- onChange(next)- }}- filterVar={() => true}- />- )+ return <ClassList nodeId="node-1" list={list} onChange={setList} filterVar={() => true} />}- render(<ClassListHarness />)+ 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(onChange).toHaveBeenLastCalledWith([- createTopic(),- createTopic({ id: 'topic-2', name: 'Refunds' }),- expect.objectContaining({ id: expect.any(String), name: '' }),- ])+ expect(screen.getAllByRole('textbox', { name: 'Class description' })).toHaveLength(3)await user.type(screen.getByDisplayValue('Billing questions'), ' updated')- expect(onChange).toHaveBeenLastCalledWith([- createTopic({ name: 'Billing questions updated' }),- createTopic({ id: 'topic-2', name: 'Refunds' }),- expect.objectContaining({ name: '' }),- ])+ 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(removeEdge).toHaveBeenCalledExactlyOnceWith('node-1', 'topic-1')+ 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/ }),)diff --git a/web/app/components/workflow/nodes/question-classifier/components/__tests__/class-list.spec.tsx b/web/app/components/workflow/nodes/question-classifier/components/__tests__/class-list.spec.tsxindex 0de1d8b8108..3baaf2ae42a 100644--- a/web/app/components/workflow/nodes/question-classifier/components/__tests__/class-list.spec.tsx+++ b/web/app/components/workflow/nodes/question-classifier/components/__tests__/class-list.spec.tsx@@ -1,53 +1,17 @@import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'-import { useEdgesInteractions } from '../../../../hooks/use-edges-interactions'+import { renderWorkflowFlowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'import ClassList from '../../../_base/components/branch-list/class-list'-vi.mock('react-sortablejs', () => ({- __esModule: true,- ReactSortable: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,-}))--vi.mock('../../../../hooks/use-edges-interactions', async (importOriginal) => {- const actual = await importOriginal<typeof import('../../../../hooks/use-edges-interactions')>()- return {- ...actual,- useEdgesInteractions: vi.fn(),- }-})-+// Class editing is covered by the adjacent integration suite; this boundary isolates list ordering.vi.mock('../../../_base/components/branch-list/class-item', () => ({- __esModule: true,- default: ({- payload,- onChange,- onRemove,- index,- }: {- payload: Topic- onChange: (value: Topic) => void- onRemove: () => void- index: number- }) => (- <div>- <div>{`${index}:${payload.name}`}</div>- <button- type="button"- onClick={() => onChange({ ...payload, name: `${payload.name} updated` })}- >- change-item- </button>- <button type="button" onClick={onRemove}>- remove-item- </button>- </div>+ default: ({ payload, index, labelId }: { payload: Topic; index: number; labelId: string }) => (+ <div id={labelId}>{`${index}:${payload.name}`}</div>),}))-const mockUseEdgesInteractions = vi.mocked(useEdgesInteractions)-const createTopic = (overrides: Partial<Topic> = {}): Topic => ({id: 'topic-1',name: 'Billing questions',@@ -55,66 +19,6 @@ const createTopic = (overrides: Partial<Topic> = {}): Topic => ({})describe('question-classifier/class-list', () => {- beforeEach(() => {- vi.clearAllMocks()- mockUseEdgesInteractions.mockReturnValue({- handleEdgeDeleteByDeleteBranch: vi.fn(),- } as unknown as ReturnType<typeof useEdgesInteractions>)- })-- it('adds, updates, collapses, and removes classes through the list actions', async () => {- const user = userEvent.setup()- const onChange = vi.fn()- const handleEdgeDeleteByDeleteBranch = vi.fn()- mockUseEdgesInteractions.mockReturnValue({- handleEdgeDeleteByDeleteBranch,- } as unknown as ReturnType<typeof useEdgesInteractions>)-- function EditableClasses() {- const [topics, setTopics] = useState([- createTopic(),- createTopic({ id: 'topic-2', name: 'Refunds' }),- ])- return (- <ClassList- nodeId="node-1"- list={topics}- filterVar={() => true}- onChange={(next) => {- setTopics(next)- onChange(next)- }}- />- )- }- render(<EditableClasses />)-- await user.click(screen.getAllByText('change-item')[0]!)- expect(onChange).toHaveBeenCalledWith(- expect.arrayContaining([expect.objectContaining({ name: 'Billing questions updated' })]),- )-- await user.click(screen.getAllByText('remove-item')[0]!)- expect(handleEdgeDeleteByDeleteBranch).toHaveBeenCalledWith('node-1', 'topic-1')- expect(onChange).toHaveBeenLastCalledWith([createTopic({ id: 'topic-2', name: 'Refunds' })])- expect(screen.queryByText('1:Billing questions updated')).not.toBeInTheDocument()-- await user.click(- screen.getByRole('button', { name: /workflow\.nodes\.questionClassifiers\.class/ }),- )- expect(- screen.queryByText('workflowModels.nodes.questionClassifiers.addClass'),- ).not.toBeInTheDocument()-- await user.click(- screen.getByRole('button', { name: /workflow\.nodes\.questionClassifiers\.class/ }),- )- await user.click(screen.getByText('workflowModels.nodes.questionClassifiers.addClass'))- expect(onChange).toHaveBeenCalledWith(- expect.arrayContaining([expect.objectContaining({ name: '' })]),- )- })-it('confirms keyboard sorting through the branch-aware sort callback', async () => {const user = userEvent.setup()const handleSortTopic = vi.fn()diff --git a/web/app/components/workflow/panel/__tests__/record.spec.tsx b/web/app/components/workflow/panel/__tests__/record.spec.tsxindex 99b56ef661b..c9d2e9ba08d 100644--- a/web/app/components/workflow/panel/__tests__/record.spec.tsx+++ b/web/app/components/workflow/panel/__tests__/record.spec.tsx@@ -1,23 +1,16 @@+import type { EventEmitterValue } from '@/context/event-emitter'import type { WorkflowRunDetailResponse } from '@/models/log'-import { act, screen } from '@testing-library/react'+import { act, screen, waitFor } from '@testing-library/react'+import { EventEmitter } from 'ahooks/lib/useEventEmitter'+import { useReactFlow } from 'reactflow'+import { EventEmitterContext } from '@/context/event-emitter'import { createEdge, createNode } from '../../__tests__/fixtures'-import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'+import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'import Record from '../record'-const mockHandleUpdateWorkflowCanvas = vi.fn()+const WorkflowEventProvider = EventEmitterContext.Providerlet latestGetResultCallback: ((res: WorkflowRunDetailResponse) => void) | undefined-vi.mock('../../hooks/use-workflow-update', async (importOriginal) => {- const actual = await importOriginal<typeof import('../../hooks/use-workflow-update')>()-- return {- ...actual,- useWorkflowUpdate: () => ({- handleUpdateWorkflowCanvas: mockHandleUpdateWorkflowCanvas,- }),- }-})-vi.mock('@/app/components/workflow/run', () => ({default: ({appId,@@ -65,7 +58,6 @@ const createRunDetail = (describe('Record', () => {beforeEach(() => {- vi.clearAllMocks()latestGetResultCallback = undefined})@@ -75,7 +67,7 @@ describe('Record', () => {traceUrl: `/traces/${runId}`,}))- renderWorkflowComponent(<Record />, {+ renderWorkflowFlowComponent(<Record />, {resource: { kind: 'app', appId: 'history-app', mode: 'workflow' },initialStoreState: {historyWorkflowData: {@@ -96,7 +88,7 @@ describe('Record', () => {})it('renders paused history without a finished timestamp', () => {- renderWorkflowComponent(<Record />, {+ renderWorkflowFlowComponent(<Record />, {initialStoreState: {historyWorkflowData: {id: 'run-1',@@ -108,73 +100,59 @@ describe('Record', () => {expect(screen.getByText('Test Run (Paused)')).toBeInTheDocument()})- it('updates the workflow canvas with a fallback viewport when the response omits one', () => {- const nodes = [createNode({ id: 'node-1' })]- const edges = [createEdge({ id: 'edge-1' })]-- renderWorkflowComponent(<Record />, {- initialStoreState: {- historyWorkflowData: {- id: 'run-1',- status: 'succeeded',+ it.each([+ {+ name: 'the default viewport when omitted',+ viewport: undefined,+ expected: { x: 0, y: 0, zoom: 1 },+ },+ {+ name: 'the recorded viewport when supplied',+ viewport: { x: 12, y: 24, zoom: 0.75 },+ expected: { x: 12, y: 24, zoom: 0.75 },+ },+ ])('publishes the initialized run graph and restores $name', async ({ viewport, expected }) => {+ const nodes = [createNode({ id: 'source' }), createNode({ id: 'target' })]+ const edges = [createEdge({ id: 'edge', source: 'source', target: 'target' })]+ const events: EventEmitterValue[] = []+ const eventEmitter = new EventEmitter<EventEmitterValue>()+ let flow: ReturnType<typeof useReactFlow>+ function RunRecord() {+ flow = useReactFlow()+ eventEmitter.useSubscription((event) => events.push(event))+ return <Record />+ }+ renderWorkflowFlowComponent(+ <WorkflowEventProvider value={{ eventEmitter }}>+ <RunRecord />+ </WorkflowEventProvider>,+ {+ initialStoreState: { historyWorkflowData: { id: 'run-1', status: 'succeeded' } },+ reactFlowProps: { fitView: false, defaultViewport: { x: 40, y: 50, zoom: 0.5 } },+ hooksStoreProps: {+ getWorkflowRunAndTraceUrl: () => ({ runUrl: '/runs/run-1', traceUrl: '/traces/run-1' }),},},- hooksStoreProps: {- getWorkflowRunAndTraceUrl: () => ({ runUrl: '/runs/run-1', traceUrl: '/traces/run-1' }),- },- })-- act(() => {- latestGetResultCallback?.(- createRunDetail({- graph: {- nodes,- edges,- },- }),- )- })-- expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledWith({- nodes,- edges,- viewport: { x: 0, y: 0, zoom: 1 },- })- })-- it('uses the response viewport when one is available', () => {- const nodes = [createNode({ id: 'node-1' })]- const edges = [createEdge({ id: 'edge-1' })]- const viewport = { x: 12, y: 24, zoom: 0.75 }-- renderWorkflowComponent(<Record />, {- initialStoreState: {- historyWorkflowData: {- id: 'run-1',- status: 'succeeded',+ )+ act(() => latestGetResultCallback?.(createRunDetail({ graph: { nodes, edges, viewport } })))+ expect(events).toEqual([+ expect.objectContaining({+ type: 'WORKFLOW_DATA_UPDATE',+ payload: {+ nodes: [+ expect.objectContaining({+ id: 'source',+ data: expect.objectContaining({ _connectedSourceHandleIds: ['source'] }),+ }),+ expect.objectContaining({+ id: 'target',+ data: expect.objectContaining({ _connectedTargetHandleIds: ['target'] }),+ }),+ ],+ edges: [expect.objectContaining({ id: 'edge', source: 'source', target: 'target' })],},- },- hooksStoreProps: {- getWorkflowRunAndTraceUrl: () => ({ runUrl: '/runs/run-1', traceUrl: '/traces/run-1' }),- },- })-- act(() => {- latestGetResultCallback?.(- createRunDetail({- graph: {- nodes,- edges,- viewport,- },- }),- )- })-- expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledWith({- nodes,- edges,- viewport,- })+ }),+ ])+ await waitFor(() => expect(flow!.getViewport()).toEqual(expected))})})diff --git a/web/app/components/workflow/variable-inspect/__tests__/trigger.spec.tsx b/web/app/components/workflow/variable-inspect/__tests__/trigger.spec.tsxindex 2e9867054fb..cffce7d7b3d 100644--- a/web/app/components/workflow/variable-inspect/__tests__/trigger.spec.tsx+++ b/web/app/components/workflow/variable-inspect/__tests__/trigger.spec.tsx@@ -1,32 +1,36 @@-import type { NodeWithVar, VarInInspect } from '@/types/workflow'-import { screen } from '@testing-library/react'+import type { WorkflowDraftVariableResponse } from '@dify/contracts/api/console/apps/types.gen'+import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { consoleQuery } from '@/service/console'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import { VarInInspectType } from '@/types/workflow'import { createNode } from '../../__tests__/fixtures'+import { InspectVarsProvider } from '../../__tests__/inspect-vars-provider'import { baseRunningData, renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'import { BlockEnum, NodeRunningStatus, VarType, WorkflowRunningStatus } from '../../types'import VariableInspectTrigger from '../trigger'import { EVENT_WORKFLOW_STOP } from '../types'-type InspectVarsState = {- conversationVars: VarInInspect[]- systemVars: VarInInspect[]- nodesWithInspectVars: NodeWithVar[]-}--const { mockDeleteAllInspectorVars, mockEmit } = vi.hoisted(() => ({- mockDeleteAllInspectorVars: vi.fn(),- mockEmit: vi.fn(),-}))--let inspectVarsState: InspectVarsState--vi.mock('../../hooks/use-inspect-vars-crud', () => ({- default: () => ({- ...inspectVarsState,- deleteAllInspectorVars: mockDeleteAllInspectorVars,- }),-}))+const mockEmit = vi.hoisted(() => vi.fn())+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleResponses, withConsoleClientResponses } =+ await import('@/test/console/service-responses')+ return {+ ...actual,+ consoleClient: withConsoleClientResponses(actual.consoleClient, {+ 'apps.byAppId.workflows.draft.variables.delete': async () => ({}),+ }),+ consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'apps.byAppId.workflows.draft.conversationVariables.get': async () => ({ items: [] }),+ 'apps.byAppId.workflows.draft.systemVariables.get': async () => ({ items: [] }),+ 'workspaces.current.tools.builtin.get': async () => [],+ 'workspaces.current.tools.api.get': async () => [],+ 'workspaces.current.tools.workflow.get': async () => [],+ 'workspaces.current.tools.mcp.get': async () => [],+ }),+ }+})vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({@@ -36,12 +40,14 @@ vi.mock('@/context/event-emitter', () => ({}),}))-const createVariable = (overrides: Partial<VarInInspect> = {}): VarInInspect => ({+const createVariable = (+ overrides: Partial<WorkflowDraftVariableResponse> = {},+): WorkflowDraftVariableResponse => ({id: 'var-1',- type: VarInInspectType.node,+ type: VarInInspectType.conversation,name: 'result',description: '',- selector: ['node-1', 'result'],+ selector: ['conversation', 'result'],value_type: VarType.string,value: 'cached',edited: false,@@ -50,6 +56,8 @@ const createVariable = (overrides: Partial<VarInInspect> = {}): VarInInspect =>full_content: {size_bytes: 0,download_url: '',+ length: 0,+ value_type: VarType.string,},...overrides,})@@ -57,27 +65,33 @@ const createVariable = (overrides: Partial<VarInInspect> = {}): VarInInspect =>const renderTrigger = ({nodes = [createNode()],initialStoreState = {},+ conversationVars = [],}: {nodes?: Array<ReturnType<typeof createNode>>initialStoreState?: Record<string, unknown>+ conversationVars?: WorkflowDraftVariableResponse[]} = {}) => {- return renderWorkflowFlowComponent(<VariableInspectTrigger />, {- nodes,- edges: [],- initialStoreState,- })+ const { queryClient } = createConsoleQueryWrapper()+ queryClient.setQueryData(+ consoleQuery.apps.byAppId.workflows.draft.conversationVariables.get.queryKey({+ input: { params: { app_id: 'app-1' } },+ }),+ { items: conversationVars },+ )+ return renderWorkflowFlowComponent(+ <InspectVarsProvider>+ <VariableInspectTrigger />+ </InspectVarsProvider>,+ {+ queryClient,+ nodes,+ edges: [],+ initialStoreState,+ },+ )}describe('VariableInspectTrigger', () => {- beforeEach(() => {- vi.clearAllMocks()- inspectVarsState = {- conversationVars: [],- systemVars: [],- nodesWithInspectVars: [],- }- })-it('should stay hidden when the variable-inspect panel is already open', () => {renderTrigger({initialStoreState: {@@ -119,18 +133,10 @@ describe('VariableInspectTrigger', () => {it('should clear cached variables and reset the focused node with the keyboard', async () => {const user = userEvent.setup()- inspectVarsState = {+ const { store } = renderTrigger({conversationVars: [- createVariable({- id: 'conversation-var',- type: VarInInspectType.conversation,- }),+ createVariable({ id: 'conversation-var', type: VarInInspectType.conversation }),],- systemVars: [],- nodesWithInspectVars: [],- }-- const { store } = renderTrigger({initialStoreState: {currentFocusNodeId: 'node-2',},@@ -144,10 +150,14 @@ describe('VariableInspectTrigger', () => {).toHaveFocus()await user.keyboard(' ')+ await waitFor(() =>+ expect(+ screen.queryByRole('button', { name: 'workflowDebug.debug.variableInspect.trigger.clear' }),+ ).not.toBeInTheDocument(),+ )expect(- screen.getByText('workflowDebug.debug.variableInspect.trigger.cached'),+ screen.getByRole('button', { name: 'workflowDebug.debug.variableInspect.trigger.normal' }),).toBeInTheDocument()- expect(mockDeleteAllInspectorVars).toHaveBeenCalledTimes(1)expect(store.getState().currentFocusNodeId).toBe('')})