Skip to content

armgit / dify

Public Imported from GitHub
0

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.

test(web): exercise real workflow canvas controls and note actions (#44287)

Stephen Zhou0ba8af5decd6
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx
index 0cabdd492c8..24563901b86 100644
--- a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx
@@ -90,11 +90,6 @@ vi.mock('@/context/permission-state', async () => {
workspacePermissionKeys: [],
}))
})
-vi.mock('@/context/event-emitter', () => ({
- useEventEmitterContextContext: () => ({
- eventEmitter: undefined,
- }),
-}))
const mockUseRouter = mockNavigation.useRouter
const mockUsePathname = mockNavigation.usePathname
diff --git a/web/app/components/rag-pipeline/components/__tests__/publish-toast.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/publish-toast.spec.tsx
index b92076db8db..32c8a97571b 100644
--- a/web/app/components/rag-pipeline/components/__tests__/publish-toast.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/publish-toast.spec.tsx
@@ -1,32 +1,34 @@
-import { render, screen } from '@testing-library/react'
+import { act, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import PublishToast from '../publish-toast'
-let mockPublishedAt = 0
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (selector: (state: { publishedAt: number }) => unknown) =>
- selector({ publishedAt: mockPublishedAt }),
-}))
-
describe('PublishToast', () => {
- beforeEach(() => {
- mockPublishedAt = 0
+ it('does not show the unpublished notice for a published pipeline', () => {
+ renderWorkflowComponent(<PublishToast />, { initialStoreState: { publishedAt: 1 } })
+
+ expect(screen.queryByText('pipeline.publishToast.title')).not.toBeInTheDocument()
})
- it('does not show the unpublished notice for a published pipeline', () => {
- mockPublishedAt = 1
- render(<PublishToast />)
+ it('hides the notice once the pipeline gets published', () => {
+ const { store } = renderWorkflowComponent(<PublishToast />)
+ expect(screen.getByText('pipeline.publishToast.desc')).toBeInTheDocument()
+
+ act(() => store.getState().setPublishedAt(1_700_000_000))
+
expect(screen.queryByText('pipeline.publishToast.title')).not.toBeInTheDocument()
})
it('allows keyboard users to dismiss the notice and keeps it dismissed on rerender', async () => {
const user = userEvent.setup()
- const { rerender } = render(<PublishToast />)
+ const { rerender } = renderWorkflowComponent(<PublishToast />)
expect(screen.getByText('pipeline.publishToast.desc')).toBeInTheDocument()
+
await user.tab()
expect(screen.getByRole('button', { name: 'common.operation.close' })).toHaveFocus()
await user.keyboard('{Enter}')
expect(screen.queryByText('pipeline.publishToast.title')).not.toBeInTheDocument()
+
rerender(<PublishToast />)
expect(screen.queryByText('pipeline.publishToast.title')).not.toBeInTheDocument()
})
diff --git a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
index 40e700738d1..1c3459329e1 100644
--- a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
@@ -45,14 +45,6 @@ vi.mock('@/context/event-emitter', () => ({
}),
}))
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => ({
- getState: () => ({
- pipelineId: 'test-pipeline-id',
- }),
- }),
-}))
-
const mockHandleCheckPluginDependencies = vi.fn()
vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({
usePluginDependencies: () => ({
diff --git a/web/app/components/rag-pipeline/components/panel/input-field/__tests__/hooks.spec.ts b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/hooks.spec.ts
index 1458c37130b..c5da8065f50 100644
--- a/web/app/components/rag-pipeline/components/panel/input-field/__tests__/hooks.spec.ts
+++ b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/hooks.spec.ts
@@ -1,28 +1,27 @@
-import { renderHook } from '@testing-library/react'
+import { act } from '@testing-library/react'
+import { createNode } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'
import { useFloatingRight } from '../hooks'
-const mockGetNodes = vi.fn()
-vi.mock('reactflow', () => ({
- useStore: (
- selector: (s: { getNodes: () => { id: string; data: { selected: boolean } }[] }) => unknown,
- ) => {
- return selector({ getNodes: mockGetNodes })
- },
-}))
-
-const mockNodePanelWidth = 400
-let mockWorkflowCanvasWidth: number | undefined = 1200
-let mockOtherPanelWidth = 0
-
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (selector: (state: Record<string, unknown>) => unknown) => {
- return selector({
- nodePanelWidth: mockNodePanelWidth,
- workflowCanvasWidth: mockWorkflowCanvasWidth,
- otherPanelWidth: mockOtherPanelWidth,
- })
- },
-}))
+const renderFloatingRight = ({
+ target,
+ selected,
+ canvas,
+ other,
+}: {
+ target: number
+ selected: boolean
+ canvas: number | undefined
+ other: number
+}) =>
+ renderWorkflowCanvasHook(() => useFloatingRight(target), {
+ nodes: [createNode({ id: 'node-1', data: { selected } })],
+ initialStoreState: {
+ nodePanelWidth: 400,
+ workflowCanvasWidth: canvas,
+ otherPanelWidth: other,
+ },
+ })
it.each([
{ selected: false, canvas: 1008, other: 0, target: 600, floating: false, width: 600 },
@@ -33,22 +32,37 @@ it.each([
{ selected: false, canvas: undefined, other: 0, target: 400, floating: false, width: 400 },
])(
'positions the input panel for canvas=$canvas selected=$selected other=$other',
- ({ selected, canvas, other, target, floating, width }) => {
- mockGetNodes.mockReturnValue([{ id: 'node-1', data: { selected } }])
- mockWorkflowCanvasWidth = canvas
- mockOtherPanelWidth = other
- const { result } = renderHook(() => useFloatingRight(target))
+ ({ floating, width, ...scenario }) => {
+ const { result } = renderFloatingRight(scenario)
+
expect(result.current).toEqual({ floatingRight: floating, floatingRightWidth: width })
},
)
it('stops floating when resizing leaves enough room beside the selected node', () => {
- mockGetNodes.mockReturnValue([{ id: 'node-1', data: { selected: true } }])
- mockWorkflowCanvasWidth = 1200
- mockOtherPanelWidth = 0
- const { result, rerender } = renderHook(() => useFloatingRight(600))
+ const { result, store } = renderFloatingRight({
+ target: 600,
+ selected: true,
+ canvas: 1200,
+ other: 0,
+ })
expect(result.current).toEqual({ floatingRight: true, floatingRightWidth: 400 })
- mockWorkflowCanvasWidth = 1600
- rerender()
+
+ act(() => store.setState({ workflowCanvasWidth: 1600 }))
+
+ expect(result.current).toEqual({ floatingRight: false, floatingRightWidth: 600 })
+})
+
+it('reclaims the node panel space when the node is deselected', () => {
+ const { result, setCanvas } = renderFloatingRight({
+ target: 600,
+ selected: true,
+ canvas: 1200,
+ other: 0,
+ })
+ expect(result.current.floatingRight).toBe(true)
+
+ act(() => setCanvas({ nodes: [createNode({ id: 'node-1', data: { selected: false } })] }))
+
expect(result.current).toEqual({ floatingRight: false, floatingRightWidth: 600 })
})
diff --git a/web/app/components/rag-pipeline/components/panel/test-run/__tests__/header.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/__tests__/header.spec.tsx
index c4235d4f4fa..88556d382c2 100644
--- a/web/app/components/rag-pipeline/components/panel/test-run/__tests__/header.spec.tsx
+++ b/web/app/components/rag-pipeline/components/panel/test-run/__tests__/header.spec.tsx
@@ -1,60 +1,32 @@
-import { render, screen } from '@testing-library/react'
+import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store/workflow'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { createRagPipelineSliceSlice } from '../../../../store'
import Header from '../header'
-const { mockSetIsPreparingDataSource, mockHandleCancelDebugAndPreviewPanel, mockWorkflowStore } =
- vi.hoisted(() => ({
- mockSetIsPreparingDataSource: vi.fn(),
- mockHandleCancelDebugAndPreviewPanel: vi.fn(),
- mockWorkflowStore: {
- getState: vi.fn(() => ({
- isPreparingDataSource: true,
- setIsPreparingDataSource: vi.fn(),
- })),
- },
- }))
-
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => mockWorkflowStore,
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-workflow-panel-interactions', () => ({
- useWorkflowInteractions: () => ({
- handleCancelDebugAndPreviewPanel: mockHandleCancelDebugAndPreviewPanel,
- }),
-}))
-
-describe('TestRun header', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockWorkflowStore.getState.mockReturnValue({
- isPreparingDataSource: true,
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- })
- })
-
- it('should render the title and reset preparing state on close', async () => {
- const user = userEvent.setup()
- render(<Header />)
-
- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
-
- expect(screen.getByText('datasetPipeline.testRun.title')).toBeInTheDocument()
- expect(mockSetIsPreparingDataSource).toHaveBeenCalledWith(false)
- expect(mockHandleCancelDebugAndPreviewPanel).toHaveBeenCalledTimes(1)
+const renderHeader = (isPreparingDataSource: boolean) =>
+ renderWorkflowFlowComponent(<Header />, {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },
+ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice as InjectWorkflowStoreSliceFn,
+ initialStoreState: { isPreparingDataSource, showDebugAndPreviewPanel: true },
})
- it('should only cancel the panel when the datasource preparation flag is false', async () => {
- const user = userEvent.setup()
- mockWorkflowStore.getState.mockReturnValue({
- isPreparingDataSource: false,
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- })
-
- render(<Header />)
- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
-
- expect(mockSetIsPreparingDataSource).not.toHaveBeenCalled()
- expect(mockHandleCancelDebugAndPreviewPanel).toHaveBeenCalledTimes(1)
- })
+describe('TestRun header', () => {
+ it.each([true, false])(
+ 'closes the test run panel and leaves datasource preparation (preparing=%s)',
+ async (isPreparingDataSource) => {
+ const user = userEvent.setup()
+ const { store } = renderHeader(isPreparingDataSource)
+
+ expect(screen.getByText('datasetPipeline.testRun.title')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
+
+ expect(store.getState()).toMatchObject({
+ isPreparingDataSource: false,
+ showDebugAndPreviewPanel: false,
+ workflowRunningData: undefined,
+ })
+ },
+ )
})
diff --git a/web/app/components/rag-pipeline/components/panel/test-run/header.tsx b/web/app/components/rag-pipeline/components/panel/test-run/header.tsx
index 4f9ea601b80..521375b50f1 100644
--- a/web/app/components/rag-pipeline/components/panel/test-run/header.tsx
+++ b/web/app/components/rag-pipeline/components/panel/test-run/header.tsx
@@ -16,7 +16,7 @@ const Header = () => {
const { isPreparingDataSource, setIsPreparingDataSource } = workflowStore.getState()
if (isPreparingDataSource) setIsPreparingDataSource?.(false)
handleCancelDebugAndPreviewPanel()
- }, [workflowStore])
+ }, [workflowStore, handleCancelDebugAndPreviewPanel])
return (
<div className="flex items-center gap-x-2 pt-4 pr-3 pl-4">
diff --git a/web/app/components/rag-pipeline/components/panel/test-run/result/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/result/__tests__/index.spec.tsx
index 5a4e07053a0..2f3e75612d4 100644
--- a/web/app/components/rag-pipeline/components/panel/test-run/result/__tests__/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/panel/test-run/result/__tests__/index.spec.tsx
@@ -1,24 +1,15 @@
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createNodeTracing } from '@/app/components/workflow/__tests__/fixtures'
+import {
+ baseRunningData,
+ renderWorkflowComponent,
+} from '@/app/components/workflow/__tests__/workflow-test-env'
+import { WorkflowRunningStatus } from '@/app/components/workflow/types'
import { ChunkingMode } from '@/models/datasets'
import Result from '../index'
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({
- workflowRunningData: {
- result: {
- status: 'succeeded',
- outputs: {
- chunk_structure: ChunkingMode.text,
- preview: [{ content: 'Processed document' }],
- },
- },
- tracing: [{ id: 'trace-1' }],
- },
- }),
-}))
-
+// The detail and tracing panels are independently tested run components.
vi.mock('@/app/components/workflow/run/result-panel', () => ({
default: () => <div>Result detail</div>,
}))
@@ -30,7 +21,20 @@ vi.mock('@/app/components/workflow/run/tracing-panel', () => ({
describe('Result', () => {
it('switches between preview, detail, and tracing', async () => {
const user = userEvent.setup()
- render(<Result />)
+ renderWorkflowComponent(<Result />, {
+ initialStoreState: {
+ workflowRunningData: baseRunningData({
+ result: {
+ status: WorkflowRunningStatus.Succeeded,
+ outputs: {
+ chunk_structure: ChunkingMode.text,
+ preview: [{ content: 'Processed document' }],
+ },
+ },
+ tracing: [createNodeTracing({ id: 'trace-1' })],
+ }),
+ },
+ })
expect(screen.getByText('Processed document')).toBeInTheDocument()
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx
index f86958ff9a1..a577ece83ff 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx
@@ -1,100 +1,112 @@
-import { fireEvent, render, screen } from '@testing-library/react'
+import type { ReactNode } from 'react'
+import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store/workflow'
+import { act, fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import {
+ baseRunningData,
+ renderWorkflowComponent,
+} from '@/app/components/workflow/__tests__/workflow-test-env'
+import { fullWorkflowAccessControl } from '@/app/components/workflow/hooks-store/store'
+import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'
+import { useEventEmitterContextContext } from '@/context/event-emitter'
+import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
+import { createRagPipelineSliceSlice } from '../../../store'
import { RunMode } from '../run-mode'
+// Start and stop are provided by the pipeline hooks through the hooks store.
const mockHandleWorkflowStartRunInWorkflow = vi.fn()
const mockHandleStopRun = vi.fn()
-const mockSetIsPreparingDataSource = vi.fn()
-const mockSetShowDebugAndPreviewPanel = vi.fn()
-
-let mockWorkflowRunningData: { task_id: string; result: { status: string } } | undefined
-let mockIsPreparingDataSource = false
-vi.mock('@/app/components/workflow/hooks/use-workflow-run', () => ({
- useWorkflowRun: () => ({ handleStopRun: mockHandleStopRun }),
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-workflow-start-run', () => ({
- useWorkflowStartRun: () => ({
- handleWorkflowStartRunInWorkflow: mockHandleWorkflowStartRunInWorkflow,
- }),
-}))
-
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (selector: (state: Record<string, unknown>) => unknown) => {
- const state = {
- workflowRunningData: mockWorkflowRunningData,
- isPreparingDataSource: mockIsPreparingDataSource,
- }
- return selector(state)
- },
- useWorkflowStore: () => ({
- getState: () => ({
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- setShowDebugAndPreviewPanel: mockSetShowDebugAndPreviewPanel,
- }),
- }),
-}))
-
-vi.mock('@/app/components/workflow/hooks-store', () => ({
- useHooksStore: (selector: (state: { accessControl: { canRun: boolean } }) => unknown) =>
- selector({
- accessControl: { canRun: true },
- }),
-}))
-
-vi.mock('@/context/event-emitter', () => ({
- useEventEmitterContextContext: () => ({
- eventEmitter: { useSubscription: vi.fn() },
- }),
-}))
+
+let emitWorkflowEvent: ((event: { type: string }) => void) | undefined
+const EmitterProbe = ({ children }: { children: ReactNode }) => {
+ const { eventEmitter } = useEventEmitterContextContext()
+ emitWorkflowEvent = (event) => eventEmitter?.emit(event as never)
+ return children
+}
+
+const pressRunShortcut = () => {
+ const event = new KeyboardEvent('keydown', {
+ key: 'r',
+ code: 'KeyR',
+ altKey: true,
+ bubbles: true,
+ })
+ // Happy DOM treats Alt as AltGraph; this event represents the plain Alt key.
+ vi.spyOn(event, 'getModifierState').mockImplementation((key) => key === 'Alt')
+ fireEvent(document.body, event)
+ fireEvent.keyUp(document.body, { key: 'r', code: 'KeyR', altKey: true })
+}
+
+const renderRunMode = ({
+ initialStoreState = {},
+ canRun = true,
+}: { initialStoreState?: Record<string, unknown>; canRun?: boolean } = {}) =>
+ renderWorkflowComponent(
+ <EventEmitterContextProvider>
+ <EmitterProbe>
+ <RunMode />
+ </EmitterProbe>
+ </EventEmitterContextProvider>,
+ {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },
+ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice as InjectWorkflowStoreSliceFn,
+ initialStoreState,
+ hooksStoreProps: {
+ handleWorkflowStartRunInWorkflow: mockHandleWorkflowStartRunInWorkflow,
+ handleStopRun: mockHandleStopRun,
+ accessControl: { ...fullWorkflowAccessControl, canRun },
+ },
+ },
+ )
describe('RunMode', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockWorkflowRunningData = undefined
- mockIsPreparingDataSource = false
})
describe('Idle state', () => {
- it('should call start run when button clicked', async () => {
+ it('starts a test run from the button', async () => {
const user = userEvent.setup()
- render(<RunMode />)
+ renderRunMode()
await user.click(screen.getByRole('button', { name: /pipeline.common.testRun/ }))
- expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalled()
+ expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalledOnce()
})
- it('should run through the enabled application shortcut', () => {
- render(<RunMode />)
+ it('starts a test run through the application shortcut', () => {
+ renderRunMode()
- const event = new KeyboardEvent('keydown', {
- key: 'r',
- code: 'KeyR',
- altKey: true,
- bubbles: true,
- })
- // Happy DOM treats Alt as AltGraph; this event represents the plain Alt key.
- vi.spyOn(event, 'getModifierState').mockImplementation((key) => key === 'Alt')
- fireEvent(document.body, event)
- fireEvent.keyUp(document.body, { key: 'r', code: 'KeyR', altKey: true })
+ pressRunShortcut()
expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalledOnce()
})
+
+ it('ignores the run shortcut for users without run access', () => {
+ renderRunMode({ canRun: false })
+
+ expect(
+ screen.queryByRole('button', { name: /pipeline.common.testRun/ }),
+ ).not.toBeInTheDocument()
+ pressRunShortcut()
+
+ expect(mockHandleWorkflowStartRunInWorkflow).not.toHaveBeenCalled()
+ })
})
describe('Running state', () => {
- beforeEach(() => {
- mockWorkflowRunningData = {
+ const running = {
+ workflowRunningData: baseRunningData({
task_id: 'task-1',
- result: { status: 'running' },
- }
- })
+ result: { status: WorkflowRunningStatus.Running },
+ }),
+ }
- it('should call handleStopRun with task_id when stop clicked', async () => {
+ it('stops the current task from the stop button', async () => {
const user = userEvent.setup()
- render(<RunMode />)
+ renderRunMode({ initialStoreState: running })
await user.click(
screen.getByRole('button', { name: 'workflowDebug.debug.variableInspect.trigger.stop' }),
@@ -102,40 +114,49 @@ describe('RunMode', () => {
expect(screen.getByRole('button', { name: 'pipeline.common.processing' })).toBeDisabled()
expect(mockHandleWorkflowStartRunInWorkflow).not.toHaveBeenCalled()
- expect(mockHandleStopRun).toHaveBeenCalledWith('task-1')
+ expect(mockHandleStopRun).toHaveBeenCalledExactlyOnceWith('task-1')
})
- })
- describe('After run completed', () => {
- it('should show reRun text when previous run data exists', async () => {
- const user = userEvent.setup()
- mockWorkflowRunningData = {
- task_id: 'task-1',
- result: { status: 'succeeded' },
- }
- render(<RunMode />)
+ it('stops the current task when another panel requests a workflow stop', () => {
+ renderRunMode({ initialStoreState: running })
- await user.click(screen.getByRole('button', { name: /pipeline.common.reRun/ }))
- expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalledOnce()
+ act(() => emitWorkflowEvent?.({ type: EVENT_WORKFLOW_STOP }))
+
+ expect(mockHandleStopRun).toHaveBeenCalledExactlyOnceWith('task-1')
})
})
- describe('Preparing data source state', () => {
- beforeEach(() => {
- mockIsPreparingDataSource = true
+ it('offers a rerun once a previous run has finished', async () => {
+ const user = userEvent.setup()
+ renderRunMode({
+ initialStoreState: {
+ workflowRunningData: baseRunningData({
+ task_id: 'task-1',
+ result: { status: WorkflowRunningStatus.Succeeded },
+ }),
+ },
})
- it('should cancel preparing when close clicked', async () => {
- const user = userEvent.setup()
- render(<RunMode />)
+ await user.click(screen.getByRole('button', { name: /pipeline.common.reRun/ }))
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalledOnce()
+ })
- expect(
- screen.getByRole('button', { name: 'pipeline.common.preparingDataSource' }),
- ).toBeDisabled()
- expect(mockSetIsPreparingDataSource).toHaveBeenCalledWith(false)
- expect(mockSetShowDebugAndPreviewPanel).toHaveBeenCalledWith(false)
+ it('closes datasource preparation and the run panel on cancel', async () => {
+ const user = userEvent.setup()
+ const { store } = renderRunMode({
+ initialStoreState: { isPreparingDataSource: true, showDebugAndPreviewPanel: true },
+ })
+
+ expect(
+ screen.getByRole('button', { name: 'pipeline.common.preparingDataSource' }),
+ ).toBeDisabled()
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+
+ expect(store.getState()).toMatchObject({
+ isPreparingDataSource: false,
+ showDebugAndPreviewPanel: false,
})
+ expect(screen.getByRole('button', { name: /pipeline.common.testRun/ })).toBeEnabled()
})
})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts
index f76d61ee86e..9bf96603c28 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts
@@ -1,10 +1,9 @@
-import type { ReactNode } from 'react'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store/workflow'
import { act, waitFor } from '@testing-library/react'
-import { createElement } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'
import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'
-import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'
+import { createRagPipelineSliceSlice } from '../../store'
import { useDSLByCanEdit } from '../use-DSL'
const toastMocks = vi.hoisted(() => ({
@@ -43,11 +42,6 @@ vi.mock('../use-nodes-sync-draft', () => ({
useNodesSyncDraftByCanEdit: () => ({ doSyncWorkflowDraft: mockDoSyncWorkflowDraft }),
}))
-const mockGetState = vi.fn()
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => ({ getState: mockGetState }),
-}))
-
const mockExportPipelineConfig = vi.fn()
vi.mock('@/service/console', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/console')>()),
@@ -72,38 +66,27 @@ vi.mock('@/utils/download', () => ({
downloadBlob: (...args: unknown[]) => mockDownloadBlob(...args),
}))
-let queryClient: QueryClient
-const wrapper = ({ children }: { children: ReactNode }) =>
- createElement(QueryClientProvider, { client: queryClient }, children)
+const renderDSL = (canEdit: boolean) =>
+ renderWorkflowCanvasHook(() => useDSLByCanEdit(canEdit), {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
+ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice as InjectWorkflowStoreSliceFn,
+ initialStoreState: { knowledgeName: 'Test Knowledge Base' },
+ })
describe('useDSLByCanEdit', () => {
beforeEach(() => {
vi.clearAllMocks()
- queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
-
- mockGetState.mockReturnValue({
- pipelineId: 'test-pipeline-id',
- knowledgeName: 'Test Knowledge Base',
- })
-
mockDoSyncWorkflowDraft.mockResolvedValue(undefined)
mockExportPipelineConfig.mockResolvedValue({ data: 'yaml-content' })
mockFetchWorkflowDraft.mockResolvedValue({ environment_variables: [] })
})
- afterEach(() => {
- queryClient.clear()
- })
-
it('does not export a stale draft after synchronization reports a failure', async () => {
mockDoSyncWorkflowDraft.mockImplementation(async (_options, callback) => {
callback.onError()
return null
})
- const { result } = renderHook(() => useDSLByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- wrapper,
- })
+ const { result } = renderDSL(true)
await act(async () => {
expect(await result.current.handleExportDSL()).toBe(false)
})
@@ -115,10 +98,7 @@ describe('useDSLByCanEdit', () => {
it('allows export when draft synchronization is skipped for read-only access', async () => {
mockDoSyncWorkflowDraft.mockResolvedValue(null)
- const { result } = renderHook(() => useDSLByCanEdit(false), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- wrapper,
- })
+ const { result } = renderDSL(false)
await act(async () => {
expect(await result.current.handleExportDSL()).toBe(true)
})
@@ -129,10 +109,7 @@ describe('useDSLByCanEdit', () => {
it.each([false, true])(
'exports YAML with include secrets=%s and the pipeline filename',
async (include) => {
- const { result } = renderHook(() => useDSLByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- wrapper,
- })
+ const { result } = renderDSL(true)
await act(async () => {
expect(await result.current.handleExportDSL(include)).toBe(true)
@@ -158,10 +135,7 @@ describe('useDSLByCanEdit', () => {
it('should handle export error', async () => {
mockExportPipelineConfig.mockRejectedValue(new Error('Export failed'))
- const { result } = renderHook(() => useDSLByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- wrapper,
- })
+ const { result } = renderDSL(true)
await act(async () => {
expect(await result.current.handleExportDSL()).toBe(false)
@@ -180,10 +154,7 @@ describe('useDSLByCanEdit', () => {
it('should call handleExportDSL directly when no secret variables', async () => {
mockFetchWorkflowDraft.mockResolvedValue({ environment_variables: [] })
- const { result } = renderHook(() => useDSLByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- wrapper,
- })
+ const { result } = renderDSL(true)
await act(async () => {
await result.current.exportCheck()
@@ -208,10 +179,7 @@ describe('useDSLByCanEdit', () => {
],
})
- const { result } = renderHook(() => useDSLByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- wrapper,
- })
+ const { result } = renderDSL(true)
await act(async () => {
await result.current.exportCheck()
@@ -232,10 +200,7 @@ describe('useDSLByCanEdit', () => {
it('should handle export check error', async () => {
mockFetchWorkflowDraft.mockRejectedValue(new Error('Fetch failed'))
- const { result } = renderHook(() => useDSLByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- wrapper,
- })
+ const { result } = renderDSL(true)
await act(async () => {
await result.current.exportCheck()
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-file-settings.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-file-settings.spec.ts
deleted file mode 100644
index af8e686cc7f..00000000000
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-file-settings.spec.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { renderHook } from '@testing-library/react'
-import { useFileSettings } from '../use-file-settings'
-
-let mockFileUploadConfig = { max_size: 10 }
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (selector: (state: { fileUploadConfig: typeof mockFileUploadConfig }) => unknown) =>
- selector({ fileUploadConfig: mockFileUploadConfig }),
-}))
-
-it('combines pipeline upload limits with the disabled image settings and follows config changes', () => {
- mockFileUploadConfig = { max_size: 10 }
- const { result, rerender } = renderHook(() => useFileSettings())
- expect(result.current).toEqual({
- image: {
- enabled: false,
- detail: 'high',
- number_limits: 3,
- transfer_methods: ['local_file', 'remote_url'],
- },
- fileUploadConfig: { max_size: 10 },
- })
- mockFileUploadConfig = { max_size: 20 }
- rerender()
- expect(result.current.fileUploadConfig).toEqual({ max_size: 20 })
-})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts
index a147367b4ef..b7b3b5a1814 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -1,32 +1,12 @@
-import { act } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'
+import type { Edge, EnvironmentVariable, Node } from '@/app/components/workflow/types'
+import type { RAGPipelineVariables } from '@/models/pipeline'
+import { act } from '@testing-library/react'
+import { createEdge, 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 { createHttpError } from '@/service/http-error'
import { useNodesSyncDraft } from '../use-nodes-sync-draft'
-const mockGetNodes = vi.fn()
-const mockStoreGetState = vi.fn()
-
-vi.mock('reactflow', () => ({
- useStoreApi: () => ({
- getState: mockStoreGetState,
- }),
-}))
-
-const mockWorkflowStoreGetState = vi.fn()
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => ({
- getState: mockWorkflowStoreGetState,
- }),
-}))
-
-const mockGetNodesReadOnly = vi.fn()
-vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({
- useNodesReadOnly: () => ({
- getNodesReadOnly: mockGetNodesReadOnly,
- }),
-}))
-
const mockSyncWorkflowDraft = vi.fn()
// Stand in for the draft sync request at the client boundary: record the request it sends
// and validate rejections against the contract, as the console link does.
@@ -69,84 +49,102 @@ vi.mock('@/service/fetch', async (importOriginal) => ({
postWithKeepalive: (...args: unknown[]) => mockPostWithKeepalive(...args),
}))
-describe('useNodesSyncDraft', () => {
- beforeEach(() => {
- vi.clearAllMocks()
-
- mockStoreGetState.mockReturnValue({
- getNodes: mockGetNodes,
- edges: [],
- transform: [0, 0, 1],
- })
-
- mockGetNodes.mockReturnValue([
- { id: 'node-1', data: { type: 'start', _temp: true }, position: { x: 0, y: 0 } },
- { id: 'node-2', data: { type: 'end' }, position: { x: 100, y: 0 } },
- ])
-
- mockWorkflowStoreGetState.mockReturnValue({
- pipelineId: 'test-pipeline-id',
- environmentVariables: [],
- syncWorkflowDraftHash: 'test-hash',
- ragPipelineVariables: [],
- setSyncWorkflowDraftHash: vi.fn(),
- setDraftUpdatedAt: vi.fn(),
- })
+const startNode = createNode({ id: 'node-1', data: { type: BlockEnum.Start, title: 'Start' } })
+const savedStartData = { type: BlockEnum.Start, title: 'Start', desc: '' }
+const draftUrl = '/rag/pipelines/test-pipeline-id/workflows/draft'
+
+const renderPipelineDraftSync = ({
+ nodes = [startNode],
+ edges = [],
+ transform,
+ canvasReadOnly = false,
+ syncWorkflowDraftHash = 'test-hash',
+ environmentVariables = [],
+ ragPipelineVariables = [],
+}: {
+ nodes?: Node[]
+ edges?: Edge[]
+ transform?: [number, number, number]
+ canvasReadOnly?: boolean
+ syncWorkflowDraftHash?: string
+ environmentVariables?: EnvironmentVariable[]
+ ragPipelineVariables?: RAGPipelineVariables
+} = {}) =>
+ renderWorkflowCanvasHook(() => useNodesSyncDraft(), {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
+ nodes,
+ edges,
+ transform,
+ initialStoreState: {
+ canvasReadOnly,
+ syncWorkflowDraftHash,
+ environmentVariables,
+ ragPipelineVariables,
+ },
+ })
- mockGetNodesReadOnly.mockReturnValue(false)
- mockSyncWorkflowDraft.mockResolvedValue({
- hash: 'new-hash',
- updated_at: '2024-01-01T00:00:00Z',
- })
+const draftNotSyncError = () =>
+ createHttpError(new Response(null, { status: 409 }), {
+ code: 'draft_workflow_not_sync',
+ message: 'Workflow not synced.',
+ status: 409,
})
- afterEach(() => {
- vi.clearAllMocks()
+describe('useNodesSyncDraft', () => {
+ beforeEach(() => {
+ mockSyncWorkflowDraft.mockResolvedValue({ hash: 'new-hash', updated_at: 1_704_067_200 })
})
it.each(['page close', 'queued sync'] as const)(
'sends the complete sanitized draft on %s without changing the canvas',
async (mode) => {
- const node = {
+ const node = createNode({
id: 'node-1',
- data: { type: 'start', _privateData: 'secret' },
- position: { x: 0, y: 0 },
- }
- const temp = {
+ data: { type: BlockEnum.Start, title: 'Start', _privateData: 'secret' },
+ })
+ const temp = createNode({
id: 'temp',
- data: { type: 'start', _isTempNode: true },
position: { x: 50, y: 0 },
- }
- const edge = {
+ data: { type: BlockEnum.Start, _isTempNode: true },
+ })
+ const edge = createEdge({
id: 'edge-1',
source: 'node-1',
target: 'node-2',
- data: { _hidden: true, visible: false },
- }
- mockGetNodes.mockReturnValue([node, temp])
- mockStoreGetState.mockReturnValue({
- getNodes: mockGetNodes,
- edges: [edge],
- transform: [100, 200, 1.5],
+ data: { _hidden: true, isInIteration: false },
})
- const environmentVariables = [
- { id: 'env', name: 'URL', value_type: 'string', value: 'https://example.com' },
+ const environmentVariables: EnvironmentVariable[] = [
+ {
+ id: 'env',
+ name: 'URL',
+ value_type: 'string',
+ value: 'https://example.com',
+ description: '',
+ },
]
- const ragPipelineVariables = [{ variable: 'input', type: 'text-input' }]
- mockWorkflowStoreGetState.mockReturnValue({
+ const ragPipelineVariables = [
+ { variable: 'input', type: 'text-input', label: 'Input', belong_to_node_id: 'shared' },
+ ] as RAGPipelineVariables
+ const { result, store } = renderPipelineDraftSync({
+ nodes: [node, temp],
+ edges: [edge],
+ transform: [100, 200, 1.5],
environmentVariables,
ragPipelineVariables,
- syncWorkflowDraftHash: 'test-hash',
- setSyncWorkflowDraftHash: vi.fn(),
- setDraftUpdatedAt: vi.fn(),
- })
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
})
const payload = {
graph: {
- nodes: [{ ...node, data: { type: 'start' } }],
- edges: [{ ...edge, data: { visible: false } }],
+ nodes: [expect.objectContaining({ id: 'node-1', data: savedStartData })],
+ edges: [
+ {
+ ...edge,
+ data: {
+ sourceType: BlockEnum.Start,
+ targetType: BlockEnum.Code,
+ isInIteration: false,
+ },
+ },
+ ],
viewport: { x: 100, y: 200, zoom: 1.5 },
},
environment_variables: environmentVariables,
@@ -155,291 +153,143 @@ describe('useNodesSyncDraft', () => {
}
if (mode === 'page close') {
act(() => result.current.syncWorkflowDraftWhenPageClose())
- expect(mockPostWithKeepalive).toHaveBeenCalledExactlyOnceWith(
- '/api/rag/pipelines/test-pipeline-id/workflows/draft',
- payload,
- )
+ expect(mockPostWithKeepalive).toHaveBeenCalledExactlyOnceWith(`/api${draftUrl}`, payload)
} else {
await act(async () => {
await result.current.doSyncWorkflowDraft()
})
expect(mockSyncWorkflowDraft).toHaveBeenCalledExactlyOnceWith({
- url: '/rag/pipelines/test-pipeline-id/workflows/draft',
+ url: draftUrl,
params: payload,
})
+ expect(store.getState()).toMatchObject({
+ syncWorkflowDraftHash: 'new-hash',
+ draftUpdatedAt: 1_704_067_200_000,
+ })
}
- expect(node.data._privateData).toBe('secret')
- expect(edge.data._hidden).toBe(true)
+ expect(node.data).toHaveProperty('_privateData', 'secret')
+ expect(edge.data).toHaveProperty('_hidden', true)
},
)
- describe('syncWorkflowDraftWhenPageClose', () => {
- it('should not call postWithKeepalive when nodes are read only', () => {
- mockGetNodesReadOnly.mockReturnValue(true)
-
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
- })
+ it.each([
+ { scenario: 'the canvas is read-only', canvasReadOnly: true, nodes: [startNode] },
+ { scenario: 'the canvas has no nodes', canvasReadOnly: false, nodes: [] },
+ {
+ scenario: 'the canvas only has temporary nodes',
+ canvasReadOnly: false,
+ nodes: [createNode({ data: { type: BlockEnum.Start, _isTempNode: true } })],
+ },
+ ])('does not persist the draft when $scenario', async ({ canvasReadOnly, nodes }) => {
+ const { result } = renderPipelineDraftSync({ canvasReadOnly, nodes })
- expect(mockPostWithKeepalive).not.toHaveBeenCalled()
+ await act(async () => {
+ result.current.syncWorkflowDraftWhenPageClose()
+ await result.current.doSyncWorkflowDraft()
})
- it('should not call postWithKeepalive when nodes array is empty', () => {
- mockGetNodes.mockReturnValue([])
-
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
- })
+ expect(mockPostWithKeepalive).not.toHaveBeenCalled()
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ })
- expect(mockPostWithKeepalive).not.toHaveBeenCalled()
+ it('captures the graph before a queued sync runs after the canvas is torn down', async () => {
+ const draftEdge = createEdge({ id: 'edge-1', source: 'node-1', target: 'node-2' })
+ const { result, setCanvas } = renderPipelineDraftSync({
+ edges: [draftEdge],
+ transform: [10, 20, 1.5],
})
+ let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
- it('should filter out temp nodes', () => {
- mockGetNodes.mockReturnValue([
- { id: 'node-1', data: { type: 'start', _isTempNode: true }, position: { x: 0, y: 0 } },
- ])
-
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
- })
-
- expect(mockPostWithKeepalive).not.toHaveBeenCalled()
+ act(() => {
+ syncPromise = result.current.doSyncWorkflowDraft()
+ // ReactFlow clears its store immediately after the page starts unmounting.
+ setCanvas({ nodes: [], edges: [], transform: [0, 0, 1] })
})
- })
-
- describe('doSyncWorkflowDraft', () => {
- it('should not sync when nodes are read only', async () => {
- mockGetNodesReadOnly.mockReturnValue(true)
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.doSyncWorkflowDraft()
- })
-
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ await act(async () => {
+ await syncPromise
})
- it('should capture the graph before a queued sync runs after the canvas is torn down', async () => {
- const draftNode = {
- id: 'node-1',
- data: { type: 'start' },
- position: { x: 0, y: 0 },
- }
- const draftEdge = {
- id: 'edge-1',
- source: 'node-1',
- target: 'node-2',
- data: { visible: true },
- }
- mockGetNodes.mockReturnValue([draftNode])
- mockStoreGetState.mockReturnValue({
- getNodes: mockGetNodes,
- edges: [draftEdge],
- transform: [10, 20, 1.5],
- })
-
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
-
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft()
-
- // Simulate ReactFlow clearing its store immediately after the page starts unmounting.
- mockGetNodes.mockReturnValue([])
- mockStoreGetState.mockReturnValue({
- getNodes: mockGetNodes,
- edges: [],
- transform: [0, 0, 1],
- })
- })
-
- await act(async () => {
- await syncPromise
- })
-
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- graph: {
- nodes: [draftNode],
- edges: [draftEdge],
- viewport: { x: 10, y: 20, zoom: 1.5 },
- },
- }),
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ graph: {
+ nodes: [expect.objectContaining({ id: 'node-1', data: savedStartData })],
+ edges: [draftEdge],
+ viewport: { x: 10, y: 20, zoom: 1.5 },
+ },
}),
- )
- })
-
- it('should use the latest hash when sending a previously captured queued graph', async () => {
- const workflowState = {
- pipelineId: 'test-pipeline-id',
- environmentVariables: [],
- syncWorkflowDraftHash: 'initial-hash',
- ragPipelineVariables: [],
- setSyncWorkflowDraftHash: vi.fn(),
- setDraftUpdatedAt: vi.fn(),
- }
- workflowState.setSyncWorkflowDraftHash.mockImplementation((hash: string) => {
- workflowState.syncWorkflowDraftHash = hash
- })
- mockWorkflowStoreGetState.mockImplementation(() => workflowState)
- mockGetNodes.mockReturnValue([
- { id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },
- ])
- mockSyncWorkflowDraft
- .mockResolvedValueOnce({ hash: 'hash-after-first-sync', updated_at: 'first-update' })
- .mockResolvedValueOnce({ hash: 'hash-after-second-sync', updated_at: 'second-update' })
-
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
- let firstSync!: ReturnType<typeof result.current.doSyncWorkflowDraft>
- let secondSync!: ReturnType<typeof result.current.doSyncWorkflowDraft>
-
- act(() => {
- firstSync = result.current.doSyncWorkflowDraft()
- secondSync = result.current.doSyncWorkflowDraft()
- })
-
- await act(async () => {
- await Promise.all([firstSync, secondSync])
- })
+ }),
+ )
+ })
- expect(mockSyncWorkflowDraft).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({
- params: expect.objectContaining({ hash: 'initial-hash' }),
- }),
- )
- expect(mockSyncWorkflowDraft).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- params: expect.objectContaining({ hash: 'hash-after-first-sync' }),
- }),
- )
+ it('uses the latest hash when sending a previously captured queued graph', async () => {
+ mockSyncWorkflowDraft
+ .mockResolvedValueOnce({ hash: 'hash-after-first-sync', updated_at: 1 })
+ .mockResolvedValueOnce({ hash: 'hash-after-second-sync', updated_at: 2 })
+ const { result, store } = renderPipelineDraftSync({ syncWorkflowDraftHash: 'initial-hash' })
+ let firstSync!: ReturnType<typeof result.current.doSyncWorkflowDraft>
+ let secondSync!: ReturnType<typeof result.current.doSyncWorkflowDraft>
+
+ act(() => {
+ firstSync = result.current.doSyncWorkflowDraft()
+ secondSync = result.current.doSyncWorkflowDraft()
})
- it('should call onError callback when sync fails', async () => {
- mockGetNodesReadOnly.mockReturnValue(false)
- mockGetNodes.mockReturnValue([
- { id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },
- ])
- mockSyncWorkflowDraft.mockRejectedValue(new Error('Sync failed'))
- const onError = vi.fn()
- const onSuccess = vi.fn()
- const onSettled = vi.fn()
-
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false, { onError, onSuccess, onSettled })
- })
-
- expect(onError).toHaveBeenCalled()
- expect(onSuccess).not.toHaveBeenCalled()
- expect(onSettled).toHaveBeenCalledOnce()
+ await act(async () => {
+ await Promise.all([firstSync, secondSync])
})
- it('should update hash and draft updated at on success', async () => {
- const onSuccess = vi.fn()
- const onSettled = vi.fn()
- const onError = vi.fn()
- const mockSetSyncWorkflowDraftHash = vi.fn()
- const mockSetDraftUpdatedAt = vi.fn()
-
- mockGetNodesReadOnly.mockReturnValue(false)
- mockGetNodes.mockReturnValue([
- { id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },
- ])
- mockWorkflowStoreGetState.mockReturnValue({
- pipelineId: 'test-pipeline-id',
- environmentVariables: [],
- syncWorkflowDraftHash: 'test-hash',
- ragPipelineVariables: [],
- setSyncWorkflowDraftHash: mockSetSyncWorkflowDraftHash,
- setDraftUpdatedAt: mockSetDraftUpdatedAt,
- })
+ expect(mockSyncWorkflowDraft).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ params: expect.objectContaining({ hash: 'initial-hash' }) }),
+ )
+ expect(mockSyncWorkflowDraft).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ params: expect.objectContaining({ hash: 'hash-after-first-sync' }),
+ }),
+ )
+ expect(store.getState().syncWorkflowDraftHash).toBe('hash-after-second-sync')
+ })
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ it('reports success and failure through the sync callbacks', async () => {
+ const callbacks = { onError: vi.fn(), onSuccess: vi.fn(), onSettled: vi.fn() }
+ mockSyncWorkflowDraft.mockRejectedValueOnce(new Error('Sync failed'))
+ const { result, store } = renderPipelineDraftSync()
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false, { onSuccess, onSettled, onError })
- })
-
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('new-hash')
- expect(mockSetDraftUpdatedAt).toHaveBeenCalledWith('2024-01-01T00:00:00Z')
- expect(onSuccess).toHaveBeenCalledOnce()
- expect(onSettled).toHaveBeenCalledOnce()
- expect(onError).not.toHaveBeenCalled()
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, callbacks)
})
- it('should handle draft not sync error', async () => {
- mockGetNodesReadOnly.mockReturnValue(false)
- mockGetNodes.mockReturnValue([
- { id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },
- ])
+ expect(callbacks.onError).toHaveBeenCalledOnce()
+ expect(callbacks.onSuccess).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
+ expect(store.getState().syncWorkflowDraftHash).toBe('test-hash')
- const mockJsonError = createHttpError(new Response(null, { status: 409 }), {
- code: 'draft_workflow_not_sync',
- message: 'Workflow not synced.',
- status: 409,
- })
- mockSyncWorkflowDraft.mockRejectedValue(mockJsonError)
-
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false)
- })
-
- expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalled()
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, callbacks)
})
- it('should not refresh when notRefreshWhenSyncError is true', async () => {
- mockGetNodesReadOnly.mockReturnValue(false)
- mockGetNodes.mockReturnValue([
- { id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },
- ])
-
- const mockJsonError = createHttpError(new Response(null, { status: 409 }), {
- code: 'draft_workflow_not_sync',
- message: 'Workflow not synced.',
- status: 409,
- })
- mockSyncWorkflowDraft.mockRejectedValue(mockJsonError)
+ expect(callbacks.onSuccess).toHaveBeenCalledOnce()
+ expect(callbacks.onSettled).toHaveBeenCalledTimes(2)
+ expect(store.getState().syncWorkflowDraftHash).toBe('new-hash')
+ })
- const { result } = renderHook(() => useNodesSyncDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ it.each([
+ { notRefreshWhenSyncError: false, refreshes: 1 },
+ { notRefreshWhenSyncError: true, refreshes: 0 },
+ ])(
+ 'refreshes an out-of-date draft $refreshes time(s) when notRefreshWhenSyncError=$notRefreshWhenSyncError',
+ async ({ notRefreshWhenSyncError, refreshes }) => {
+ mockSyncWorkflowDraft.mockRejectedValue(draftNotSyncError())
+ const { result } = renderPipelineDraftSync()
await act(async () => {
- await result.current.doSyncWorkflowDraft(true)
+ await result.current.doSyncWorkflowDraft(notRefreshWhenSyncError)
})
- expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
- })
- })
+ expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledTimes(refreshes)
+ },
+ )
})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts
deleted file mode 100644
index 29cf4852635..00000000000
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts
+++ /dev/null
@@ -1,293 +0,0 @@
-import { act, waitFor } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'
-import { createHttpError } from '@/service/http-error'
-import { createDeferred } from '@/test/deferred'
-import { usePipelineInit } from '../use-pipeline-init'
-
-const mockWorkflowStoreGetState = vi.fn()
-const mockWorkflowStoreSetState = vi.fn()
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => ({
- getState: mockWorkflowStoreGetState,
- setState: mockWorkflowStoreSetState,
- }),
-}))
-
-const mockUseDatasetDetailContextWithSelector = vi.fn()
-vi.mock('@/context/dataset-detail', () => ({
- useDatasetDetailContextWithSelector: (selector: (state: Record<string, unknown>) => unknown) =>
- mockUseDatasetDetailContextWithSelector(selector),
-}))
-
-const mockFetchWorkflowDraft = vi.fn()
-const mockSyncWorkflowDraft = vi.fn()
-vi.mock('@/service/workflow', () => ({
- fetchWorkflowDraft: (url: string) => mockFetchWorkflowDraft(url),
- syncWorkflowDraft: (params: unknown) => mockSyncWorkflowDraft(params),
-}))
-
-vi.mock('../use-pipeline-config', () => ({
- usePipelineConfig: vi.fn(),
-}))
-
-vi.mock('../use-pipeline-template', () => ({
- usePipelineTemplate: () => ({
- nodes: [{ id: 'template-node' }],
- edges: [],
- }),
-}))
-
-describe('usePipelineInit', () => {
- const mockSetEnvSecrets = vi.fn()
- const mockSetEnvironmentVariables = vi.fn()
- const mockSetSyncWorkflowDraftHash = vi.fn()
- const mockSetDraftUpdatedAt = vi.fn()
- const mockSetToolPublished = vi.fn()
- const mockSetRagPipelineVariables = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
-
- mockWorkflowStoreGetState.mockReturnValue({
- setEnvSecrets: mockSetEnvSecrets,
- setEnvironmentVariables: mockSetEnvironmentVariables,
- setSyncWorkflowDraftHash: mockSetSyncWorkflowDraftHash,
- setDraftUpdatedAt: mockSetDraftUpdatedAt,
- setToolPublished: mockSetToolPublished,
- setRagPipelineVariables: mockSetRagPipelineVariables,
- })
-
- mockUseDatasetDetailContextWithSelector.mockImplementation(
- (selector: (state: Record<string, unknown>) => unknown) => {
- const state = {
- dataset: {
- pipeline_id: 'test-pipeline-id',
- name: 'Test Knowledge',
- icon_info: { icon: 'test-icon', icon_type: 'emoji' },
- },
- }
- return selector(state)
- },
- )
-
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: {
- nodes: [{ id: 'node-1' }],
- edges: [],
- viewport: { x: 0, y: 0, zoom: 1 },
- },
- hash: 'test-hash',
- updated_at: '2024-01-01T00:00:00Z',
- tool_published: true,
- environment_variables: [],
- rag_pipeline_variables: [],
- })
- })
-
- afterEach(() => {
- vi.restoreAllMocks()
- })
-
- describe('hook initialization', () => {
- it('should initialize the knowledge presentation metadata', () => {
- renderHook(() => usePipelineInit(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
- knowledgeName: 'Test Knowledge',
- knowledgeIcon: {
- icon: 'test-icon',
- icon_type: 'emoji',
- icon_background: undefined,
- icon_url: undefined,
- },
- })
- })
- })
-
- describe('data fetching', () => {
- it('loads the graph and draft metadata only after initialization resolves', async () => {
- const response = {
- graph: { nodes: [{ id: 'node-1' }], edges: [], viewport: { x: 0, y: 0, zoom: 1 } },
- hash: 'test-hash',
- updated_at: '2024-01-01T00:00:00Z',
- tool_published: true,
- environment_variables: [],
- rag_pipeline_variables: [],
- }
- const pending = createDeferred<typeof response>()
- mockFetchWorkflowDraft.mockReturnValue(pending.promise)
- const { result } = renderHook(() => usePipelineInit(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
- expect(result.current).toEqual({ data: undefined, isLoading: true })
- expect(mockFetchWorkflowDraft).toHaveBeenCalledExactlyOnceWith(
- '/rag/pipelines/test-pipeline-id/workflows/draft',
- )
- expect(mockWorkflowStoreSetState).not.toHaveBeenCalledWith({ isWorkflowDataLoaded: true })
- await act(async () => pending.resolve(response))
- await waitFor(() => expect(result.current).toEqual({ data: response, isLoading: false }))
- expect(mockSetDraftUpdatedAt).toHaveBeenCalledWith(response.updated_at)
- expect(mockSetToolPublished).toHaveBeenCalledWith(true)
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('test-hash')
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({ isWorkflowDataLoaded: true })
- })
- })
-
- describe('environment variables handling', () => {
- it('should mask secret values in environment variables', async () => {
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: { nodes: [], edges: [], viewport: {} },
- hash: 'test-hash',
- updated_at: '2024-01-01T00:00:00Z',
- tool_published: false,
- environment_variables: [
- { id: 'env-1', value_type: 'secret', value: 'secret-value' },
- { id: 'env-2', value_type: 'string', value: 'plain-value' },
- ],
- rag_pipeline_variables: [],
- })
-
- renderHook(() => usePipelineInit(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await waitFor(() =>
- expect(mockSetEnvSecrets).toHaveBeenCalledWith({ 'env-1': 'secret-value' }),
- )
- await waitFor(() => {
- expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([
- { id: 'env-1', value_type: 'secret', value: '[__HIDDEN__]' },
- { id: 'env-2', value_type: 'string', value: 'plain-value' },
- ])
- })
- })
-
- it('should handle empty environment variables', async () => {
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: { nodes: [], edges: [], viewport: {} },
- hash: 'test-hash',
- updated_at: '2024-01-01T00:00:00Z',
- tool_published: false,
- environment_variables: [],
- rag_pipeline_variables: [],
- })
-
- renderHook(() => usePipelineInit(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await waitFor(() => {
- expect(mockSetEnvSecrets).toHaveBeenCalledWith({})
- expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([])
- })
- })
- })
-
- describe('rag pipeline variables handling', () => {
- it('should set rag pipeline variables', async () => {
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: { nodes: [], edges: [], viewport: {} },
- hash: 'test-hash',
- updated_at: '2024-01-01T00:00:00Z',
- tool_published: false,
- environment_variables: [],
- rag_pipeline_variables: [{ variable: 'query', type: 'text-input' }],
- })
-
- renderHook(() => usePipelineInit(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await waitFor(() => {
- expect(mockSetRagPipelineVariables).toHaveBeenCalledWith([
- { variable: 'query', type: 'text-input' },
- ])
- })
- })
-
- it('should handle undefined rag pipeline variables', async () => {
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: { nodes: [], edges: [], viewport: {} },
- hash: 'test-hash',
- updated_at: '2024-01-01T00:00:00Z',
- tool_published: false,
- environment_variables: [],
- rag_pipeline_variables: undefined,
- })
-
- renderHook(() => usePipelineInit(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await waitFor(() => {
- expect(mockSetRagPipelineVariables).toHaveBeenCalledWith([])
- })
- })
- })
-
- describe('draft not exist error handling', () => {
- it('should create initial workflow when draft does not exist', async () => {
- const mockJsonError = createHttpError(new Response(null, { status: 404 }), {
- code: 'draft_workflow_not_exist',
- message: 'Draft workflow not exist.',
- status: 404,
- })
- mockFetchWorkflowDraft.mockRejectedValueOnce(mockJsonError)
- mockSyncWorkflowDraft.mockResolvedValue({ updated_at: '2024-01-02T00:00:00Z' })
-
- mockFetchWorkflowDraft.mockResolvedValueOnce({
- graph: { nodes: [], edges: [], viewport: {} },
- hash: 'new-hash',
- updated_at: '2024-01-02T00:00:00Z',
- tool_published: false,
- environment_variables: [],
- rag_pipeline_variables: [],
- })
-
- const { result } = renderHook(() => usePipelineInit(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await waitFor(() => {
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
- notInitialWorkflow: true,
- shouldAutoOpenStartNodeSelector: true,
- })
- })
- await waitFor(() => expect(result.current.isLoading).toBe(false))
- expect(mockSyncWorkflowDraft).toHaveBeenCalledExactlyOnceWith({
- url: '/rag/pipelines/test-pipeline-id/workflows/draft',
- params: {
- graph: { nodes: [{ id: 'template-node' }], edges: [] },
- environment_variables: [],
- },
- })
- expect(mockFetchWorkflowDraft).toHaveBeenCalledTimes(2)
- expect(result.current.data?.hash).toBe('new-hash')
- })
- })
-
- describe('missing presentation metadata', () => {
- it('loads the editor pipeline when dataset presentation metadata is missing', async () => {
- mockUseDatasetDetailContextWithSelector.mockImplementation(
- (selector: (state: Record<string, unknown>) => unknown) => {
- const state = { dataset: undefined }
- return selector(state)
- },
- )
-
- renderHook(() => usePipelineInit(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await waitFor(() => {
- expect(mockFetchWorkflowDraft).toHaveBeenCalledWith(
- '/rag/pipelines/test-pipeline-id/workflows/draft',
- )
- })
- })
- })
-})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsx b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsx
new file mode 100644
index 00000000000..1bae28121ab
--- /dev/null
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsx
@@ -0,0 +1,156 @@
+import type { DatasetDetailWithPartialMembersResponse as DataSet } from '@dify/contracts/api/console/datasets/types.gen'
+import type { ReactNode } from 'react'
+import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store/workflow'
+import { act, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'
+import DatasetDetailContext from '@/context/dataset-detail'
+import { createHttpError } from '@/service/http-error'
+import { createDeferred } from '@/test/deferred'
+import { createRagPipelineSliceSlice } from '../../store'
+import { usePipelineInit } from '../use-pipeline-init'
+
+const mockFetchWorkflowDraft = vi.fn()
+const mockSyncWorkflowDraft = vi.fn()
+vi.mock('@/service/workflow', () => ({
+ fetchWorkflowDraft: (url: string) => mockFetchWorkflowDraft(url),
+ syncWorkflowDraft: (params: unknown) => mockSyncWorkflowDraft(params),
+}))
+
+// Default block/publish/upload config queries are covered by use-pipeline-config.spec.
+vi.mock('../use-pipeline-config', () => ({
+ usePipelineConfig: vi.fn(),
+}))
+
+const createDraft = (overrides: Record<string, unknown> = {}) => ({
+ graph: { nodes: [], edges: [], viewport: { x: 0, y: 0, zoom: 1 } },
+ hash: 'test-hash',
+ updated_at: 1_704_067_200,
+ tool_published: true,
+ environment_variables: [],
+ rag_pipeline_variables: [],
+ ...overrides,
+})
+
+const knowledgeDataset = {
+ name: 'Test Knowledge',
+ icon_info: { icon: 'test-icon', icon_type: 'emoji' },
+} as unknown as DataSet
+
+const renderPipelineInit = ({ dataset }: { dataset?: DataSet } = { dataset: knowledgeDataset }) =>
+ renderWorkflowCanvasHook(() => usePipelineInit(), {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
+ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice as InjectWorkflowStoreSliceFn,
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <DatasetDetailContext.Provider value={{ dataset }}>{children}</DatasetDetailContext.Provider>
+ ),
+ })
+
+describe('usePipelineInit', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockFetchWorkflowDraft.mockResolvedValue(createDraft())
+ })
+
+ it('shows the dataset name and icon in the pipeline editor', () => {
+ const { store } = renderPipelineInit()
+
+ expect(store.getState()).toMatchObject({
+ knowledgeName: 'Test Knowledge',
+ knowledgeIcon: { icon: 'test-icon', icon_type: 'emoji' },
+ })
+ })
+
+ it('still loads the draft when the dataset has no presentation metadata', async () => {
+ const { result, store } = renderPipelineInit({})
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false))
+ expect(store.getState().knowledgeName).toBeUndefined()
+ })
+
+ it('stays loading until the draft arrives, then loads draft metadata into the editor', async () => {
+ const draft = createDraft({
+ rag_pipeline_variables: [{ variable: 'query', type: 'text-input' }],
+ })
+ const pending = createDeferred<typeof draft>()
+ mockFetchWorkflowDraft.mockReturnValue(pending.promise)
+ const { result, store } = renderPipelineInit()
+
+ expect(result.current).toEqual({ data: undefined, isLoading: true })
+ expect(mockFetchWorkflowDraft).toHaveBeenCalledExactlyOnceWith(
+ '/rag/pipelines/test-pipeline-id/workflows/draft',
+ )
+ expect(store.getState().isWorkflowDataLoaded).toBe(false)
+
+ await act(async () => pending.resolve(draft))
+
+ await waitFor(() => expect(result.current).toEqual({ data: draft, isLoading: false }))
+ expect(store.getState()).toMatchObject({
+ isWorkflowDataLoaded: true,
+ draftUpdatedAt: draft.updated_at * 1000,
+ toolPublished: true,
+ syncWorkflowDraftHash: 'test-hash',
+ ragPipelineVariables: draft.rag_pipeline_variables,
+ })
+ })
+
+ it('keeps secret environment values out of the visible variables', async () => {
+ mockFetchWorkflowDraft.mockResolvedValue(
+ createDraft({
+ environment_variables: [
+ { id: 'env-1', value_type: 'secret', value: 'secret-value' },
+ { id: 'env-2', value_type: 'string', value: 'plain-value' },
+ ],
+ }),
+ )
+ const { result, store } = renderPipelineInit()
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false))
+ expect(store.getState()).toMatchObject({
+ envSecrets: { 'env-1': 'secret-value' },
+ environmentVariables: [
+ { id: 'env-1', value_type: 'secret', value: '[__HIDDEN__]' },
+ { id: 'env-2', value_type: 'string', value: 'plain-value' },
+ ],
+ })
+ })
+
+ it('treats missing pipeline variables as an empty list', async () => {
+ mockFetchWorkflowDraft.mockResolvedValue(createDraft({ rag_pipeline_variables: undefined }))
+ const { result, store } = renderPipelineInit()
+ act(() => store.setState({ ragPipelineVariables: [{ variable: 'stale' }] } as never))
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false))
+ expect(store.getState().ragPipelineVariables).toEqual([])
+ })
+
+ it('creates the knowledge base template draft when the pipeline has no draft yet', async () => {
+ mockFetchWorkflowDraft.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 404 }), {
+ code: 'draft_workflow_not_exist',
+ message: 'Draft workflow not exist.',
+ status: 404,
+ }),
+ )
+ mockFetchWorkflowDraft.mockResolvedValueOnce(createDraft({ hash: 'new-hash' }))
+ mockSyncWorkflowDraft.mockResolvedValue({ updated_at: 1_704_153_600 })
+ const { result, store } = renderPipelineInit()
+
+ await waitFor(() => expect(result.current.data?.hash).toBe('new-hash'))
+ expect(store.getState()).toMatchObject({
+ notInitialWorkflow: true,
+ shouldAutoOpenStartNodeSelector: true,
+ isWorkflowDataLoaded: true,
+ })
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledExactlyOnceWith({
+ url: '/rag/pipelines/test-pipeline-id/workflows/draft',
+ params: {
+ graph: {
+ nodes: [expect.objectContaining({ id: 'knowledgeBase' })],
+ edges: [],
+ },
+ environment_variables: [],
+ },
+ })
+ })
+})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts
index 0f97a4f65a7..8dd25878a55 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts
@@ -1,19 +1,13 @@
-import { waitFor } from '@testing-library/react'
-import { act } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store/workflow'
+import { act, waitFor } from '@testing-library/react'
import { createNode } from '@/app/components/workflow/__tests__/fixtures'
-import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'
+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum } from '@/app/components/workflow/types'
import { createDeferred } from '@/test/deferred'
+import { createRagPipelineSliceSlice } from '../../store'
import { usePipelineRefreshDraft } from '../use-pipeline-refresh-draft'
-const mockWorkflowStoreGetState = vi.fn()
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => ({
- getState: mockWorkflowStoreGetState,
- }),
-}))
-
+// Canvas replacement is delivered through the workflow event bus, owned by its own suite.
const mockHandleUpdateWorkflowCanvas = vi.fn()
vi.mock('@/app/components/workflow/hooks/use-workflow-update', () => ({
useWorkflowUpdate: () => ({
@@ -26,152 +20,90 @@ vi.mock('@/service/workflow', () => ({
fetchWorkflowDraft: (url: string) => mockFetchWorkflowDraft(url),
}))
-describe('usePipelineRefreshDraft', () => {
- const mockSetSyncWorkflowDraftHash = vi.fn()
- const mockSetIsSyncingWorkflowDraft = vi.fn()
- const mockSetEnvironmentVariables = vi.fn()
- const mockSetEnvSecrets = vi.fn()
- const mockSetRagPipelineVariables = vi.fn()
+const createDraft = (overrides: Record<string, unknown> = {}) => ({
+ graph: {
+ nodes: [createNode({ id: 'source', data: { type: BlockEnum.DataSource } })],
+ edges: [],
+ viewport: { x: 10, y: 20, zoom: 1.5 },
+ },
+ hash: 'new-hash',
+ environment_variables: [],
+ rag_pipeline_variables: [],
+ ...overrides,
+})
- beforeEach(() => {
- vi.clearAllMocks()
+const renderRefreshDraft = () =>
+ renderWorkflowCanvasHook(() => usePipelineRefreshDraft(), {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
+ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice as InjectWorkflowStoreSliceFn,
+ initialStoreState: { syncWorkflowDraftHash: 'old-hash' },
+ })
- mockWorkflowStoreGetState.mockReturnValue({
- pipelineId: 'test-pipeline-id',
- setSyncWorkflowDraftHash: mockSetSyncWorkflowDraftHash,
- setIsSyncingWorkflowDraft: mockSetIsSyncingWorkflowDraft,
- setEnvironmentVariables: mockSetEnvironmentVariables,
- setEnvSecrets: mockSetEnvSecrets,
- setRagPipelineVariables: mockSetRagPipelineVariables,
+describe('usePipelineRefreshDraft', () => {
+ it('marks the draft as syncing until the server draft replaces the canvas and pipeline state', async () => {
+ const draft = createDraft({
+ rag_pipeline_variables: [{ variable: 'query', type: 'text-input' }],
})
+ const pending = createDeferred<typeof draft>()
+ mockFetchWorkflowDraft.mockReturnValue(pending.promise)
+ const { result, store } = renderRefreshDraft()
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: {
- nodes: [createNode({ id: 'node-1', data: { type: BlockEnum.DataSource } })],
- edges: [],
- viewport: { x: 0, y: 0, zoom: 1 },
- },
- hash: 'new-hash',
- environment_variables: [],
- rag_pipeline_variables: [],
- })
- })
+ act(() => result.current.handleRefreshWorkflowDraft())
- afterEach(() => {
- vi.clearAllMocks()
- })
+ expect(mockFetchWorkflowDraft).toHaveBeenCalledExactlyOnceWith(
+ '/rag/pipelines/test-pipeline-id/workflows/draft',
+ )
+ expect(store.getState().isSyncingWorkflowDraft).toBe(true)
+ expect(mockHandleUpdateWorkflowCanvas).not.toHaveBeenCalled()
- describe('handleRefreshWorkflowDraft', () => {
- it('refreshes graph and input variables after the draft resolves', async () => {
- const response = {
- graph: {
- nodes: [createNode({ id: 'source', data: { type: BlockEnum.DataSource } })],
- edges: [],
- viewport: { x: 10, y: 20, zoom: 1.5 },
- },
- hash: 'new-hash',
- environment_variables: [],
- rag_pipeline_variables: [{ variable: 'query', type: 'text-input' }],
- }
- const pending = createDeferred<typeof response>()
- mockFetchWorkflowDraft.mockReturnValue(pending.promise)
- const { result } = renderHook(() => usePipelineRefreshDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
- act(() => result.current.handleRefreshWorkflowDraft())
- expect(mockFetchWorkflowDraft).toHaveBeenCalledExactlyOnceWith(
- '/rag/pipelines/test-pipeline-id/workflows/draft',
- )
- expect(mockSetIsSyncingWorkflowDraft).toHaveBeenLastCalledWith(true)
- expect(mockHandleUpdateWorkflowCanvas).not.toHaveBeenCalled()
- await act(async () => pending.resolve(response))
- await waitFor(() => expect(mockSetIsSyncingWorkflowDraft).toHaveBeenLastCalledWith(false))
- expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledExactlyOnceWith(response.graph)
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('new-hash')
- expect(mockSetRagPipelineVariables).toHaveBeenCalledWith(response.rag_pipeline_variables)
+ await act(async () => pending.resolve(draft))
+
+ await waitFor(() => expect(store.getState().isSyncingWorkflowDraft).toBe(false))
+ expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledExactlyOnceWith(draft.graph)
+ expect(store.getState()).toMatchObject({
+ syncWorkflowDraftHash: 'new-hash',
+ ragPipelineVariables: draft.rag_pipeline_variables,
})
+ })
- it('should mask secret values in environment variables', async () => {
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: {
- nodes: [],
- edges: [],
- viewport: { x: 0, y: 0, zoom: 1 },
- },
- hash: 'new-hash',
+ it('keeps secret environment values out of the visible variables', async () => {
+ mockFetchWorkflowDraft.mockResolvedValue(
+ createDraft({
environment_variables: [
{ id: 'env-1', value_type: 'secret', value: 'secret-value' },
{ id: 'env-2', value_type: 'string', value: 'plain-value' },
],
- })
-
- const { result } = renderHook(() => usePipelineRefreshDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- act(() => {
- result.current.handleRefreshWorkflowDraft()
- })
-
- await waitFor(() =>
- expect(mockSetEnvSecrets).toHaveBeenCalledWith({ 'env-1': 'secret-value' }),
- )
- await waitFor(() => {
- expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([
- { id: 'env-1', value_type: 'secret', value: '[__HIDDEN__]' },
- { id: 'env-2', value_type: 'string', value: 'plain-value' },
- ])
- })
+ }),
+ )
+ const { result, store } = renderRefreshDraft()
+
+ act(() => result.current.handleRefreshWorkflowDraft())
+
+ await waitFor(() => expect(store.getState().isSyncingWorkflowDraft).toBe(false))
+ expect(store.getState()).toMatchObject({
+ envSecrets: { 'env-1': 'secret-value' },
+ environmentVariables: [
+ { id: 'env-1', value_type: 'secret', value: '[__HIDDEN__]' },
+ { id: 'env-2', value_type: 'string', value: 'plain-value' },
+ ],
})
+ })
- it('should handle empty environment variables', async () => {
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: {
- nodes: [],
- edges: [],
- viewport: { x: 0, y: 0, zoom: 1 },
- },
- hash: 'new-hash',
- environment_variables: [],
- })
-
- const { result } = renderHook(() => usePipelineRefreshDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- act(() => {
- result.current.handleRefreshWorkflowDraft()
- })
-
- await waitFor(() => {
- expect(mockSetEnvSecrets).toHaveBeenCalledWith({})
- expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([])
+ it('clears environment state when the draft has no environment variables', async () => {
+ mockFetchWorkflowDraft.mockResolvedValue(createDraft({ environment_variables: undefined }))
+ const { result, store } = renderRefreshDraft()
+ act(() => {
+ store.setState({
+ envSecrets: { stale: 'value' },
+ environmentVariables: [
+ { id: 'stale', name: 'STALE', value_type: 'string', value: 'x', description: '' },
+ ],
})
})
- it('should handle undefined environment variables', async () => {
- mockFetchWorkflowDraft.mockResolvedValue({
- graph: {
- nodes: [],
- edges: [],
- viewport: { x: 0, y: 0, zoom: 1 },
- },
- hash: 'new-hash',
- environment_variables: undefined,
- })
-
- const { result } = renderHook(() => usePipelineRefreshDraft(), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ act(() => result.current.handleRefreshWorkflowDraft())
- act(() => {
- result.current.handleRefreshWorkflowDraft()
- })
-
- await waitFor(() => {
- expect(mockSetEnvSecrets).toHaveBeenCalledWith({})
- expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([])
- })
- })
+ await waitFor(() => expect(store.getState().isSyncingWorkflowDraft).toBe(false))
+ expect(store.getState()).toMatchObject({ envSecrets: {}, environmentVariables: [] })
})
})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts
index 1314e0d1d59..6a5e118cae2 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts
@@ -1,78 +1,56 @@
+import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store/workflow'
+import type { EnvironmentVariable } from '@/app/components/workflow/types'
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
-import { act } from 'react'
+import { act } from '@testing-library/react'
+import { useNodes } from 'reactflow'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'
-import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { BlockEnum, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { createDeferred } from '@/test/deferred'
+import { createRagPipelineSliceSlice } from '../../store'
import { usePipelineRunByCanEdit } from '../use-pipeline-run'
-const mockStoreGetState = vi.fn()
-const mockGetViewport = vi.fn()
-vi.mock('reactflow', () => ({
- useStoreApi: () => ({
- getState: mockStoreGetState,
- }),
- useReactFlow: () => ({
- getViewport: mockGetViewport,
- }),
-}))
-
-const mockUseStore = vi.fn()
-const mockWorkflowStoreGetState = vi.fn()
-const mockWorkflowStoreSetState = vi.fn()
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (selector: (state: Record<string, unknown>) => unknown) => mockUseStore(selector),
- useWorkflowStore: () => ({
- getState: mockWorkflowStoreGetState,
- setState: mockWorkflowStoreSetState,
- }),
-}))
-
+// Draft persistence, canvas replacement and run-event reducers all have their own suites.
const mockDoSyncWorkflowDraft = vi.fn()
vi.mock('../use-nodes-sync-draft', () => ({
- useNodesSyncDraftByCanEdit: () => ({
- doSyncWorkflowDraft: mockDoSyncWorkflowDraft,
- }),
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({
- useSetWorkflowVarsWithValue: () => ({
- fetchInspectVars: vi.fn(),
- }),
+ useNodesSyncDraftByCanEdit: () => ({ doSyncWorkflowDraft: mockDoSyncWorkflowDraft }),
}))
const mockHandleUpdateWorkflowCanvas = vi.fn()
vi.mock('@/app/components/workflow/hooks/use-workflow-update', () => ({
- useWorkflowUpdate: () => ({
- handleUpdateWorkflowCanvas: mockHandleUpdateWorkflowCanvas,
- }),
+ useWorkflowUpdate: () => ({ handleUpdateWorkflowCanvas: mockHandleUpdateWorkflowCanvas }),
}))
-const mockTextChunk = vi.fn()
-const mockTextReplace = vi.fn()
+const runEvents = vi.hoisted(() => ({
+ handleWorkflowStarted: vi.fn(),
+ handleWorkflowFinished: vi.fn(),
+ handleWorkflowFailed: vi.fn(),
+ handleWorkflowNodeStarted: vi.fn(),
+ handleWorkflowNodeFinished: vi.fn(),
+ handleWorkflowNodeIterationStarted: vi.fn(),
+ handleWorkflowNodeIterationNext: vi.fn(),
+ handleWorkflowNodeIterationFinished: vi.fn(),
+ handleWorkflowNodeLoopStarted: vi.fn(),
+ handleWorkflowNodeLoopNext: vi.fn(),
+ handleWorkflowNodeLoopFinished: vi.fn(),
+ handleWorkflowNodeRetry: vi.fn(),
+ handleWorkflowAgentLog: vi.fn(),
+ handleWorkflowTextChunk: vi.fn(),
+ handleWorkflowTextReplace: vi.fn(),
+}))
vi.mock('@/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event', () => ({
- useWorkflowRunEvent: () => ({
- handleWorkflowStarted: vi.fn(),
- handleWorkflowFinished: vi.fn(),
- handleWorkflowFailed: vi.fn(),
- handleWorkflowNodeStarted: vi.fn(),
- handleWorkflowNodeFinished: vi.fn(),
- handleWorkflowNodeIterationStarted: vi.fn(),
- handleWorkflowNodeIterationNext: vi.fn(),
- handleWorkflowNodeIterationFinished: vi.fn(),
- handleWorkflowNodeLoopStarted: vi.fn(),
- handleWorkflowNodeLoopNext: vi.fn(),
- handleWorkflowNodeLoopFinished: vi.fn(),
- handleWorkflowNodeRetry: vi.fn(),
- handleWorkflowAgentLog: vi.fn(),
- handleWorkflowTextChunk: mockTextChunk,
- handleWorkflowTextReplace: mockTextReplace,
- }),
+ useWorkflowRunEvent: () => runEvents,
+}))
+
+const mockFetchInspectVars = vi.fn()
+vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({
+ useSetWorkflowVarsWithValue: () => ({ fetchInspectVars: mockFetchInspectVars }),
}))
const mockSsePost = vi.fn()
vi.mock('@/service/base', () => ({
- ssePost: (url: string, ...args: unknown[]) => mockSsePost(url, ...args),
+ ssePost: (...args: unknown[]) => mockSsePost(...args),
}))
const mockStopWorkflowRun = vi.fn()
@@ -87,645 +65,303 @@ vi.mock('@/service/use-workflow', () => ({
useInvalidateWorkflowRunHistory: () => mockInvalidateRunHistory,
}))
-describe('usePipelineRunByCanEdit', () => {
- const mockSetNodes = vi.fn()
- const mockGetNodes = vi.fn()
- const mockSetBackupDraft = vi.fn()
- const mockSetEnvironmentVariables = vi.fn()
- const mockSetRagPipelineVariables = vi.fn()
- const mockSetWorkflowRunningData = vi.fn()
+type PipelineRun = ReturnType<typeof usePipelineRunByCanEdit>
+type IOtherOptions = NonNullable<Parameters<PipelineRun['handleRun']>[1]>
- beforeEach(() => {
- vi.clearAllMocks()
+const RUN_HISTORY_URL = '/rag/pipelines/test-pipeline-id/workflow-runs'
- const mockWorkflowContainer = document.createElement('div')
- mockWorkflowContainer.id = 'workflow-container'
- Object.defineProperty(mockWorkflowContainer, 'clientWidth', { value: 1000 })
- Object.defineProperty(mockWorkflowContainer, 'clientHeight', { value: 800 })
- document.body.appendChild(mockWorkflowContainer)
-
- mockStoreGetState.mockReturnValue({
- getNodes: mockGetNodes,
- setNodes: mockSetNodes,
- edges: [],
- })
+const envVar = (id: string, value: string): EnvironmentVariable => ({
+ id,
+ name: id.toUpperCase(),
+ value,
+ value_type: 'string',
+ description: '',
+})
- mockGetNodes.mockReturnValue([
- {
- id: 'node-1',
- data: { type: 'start', selected: true, _runningStatus: WorkflowRunningStatus.Running },
- },
- ])
-
- mockGetViewport.mockReturnValue({ x: 0, y: 0, zoom: 1 })
-
- mockWorkflowStoreGetState.mockReturnValue({
- pipelineId: 'test-pipeline-id',
- backupDraft: undefined,
- environmentVariables: [],
- setBackupDraft: mockSetBackupDraft,
- setEnvironmentVariables: mockSetEnvironmentVariables,
- setRagPipelineVariables: mockSetRagPipelineVariables,
- setWorkflowRunningData: mockSetWorkflowRunningData,
- })
+const renderPipelineRun = (initialStoreState: Record<string, unknown> = {}) =>
+ renderWorkflowCanvasHook(() => ({ run: usePipelineRunByCanEdit(true), nodes: useNodes() }), {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
+ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice as InjectWorkflowStoreSliceFn,
+ nodes: [
+ createNode({
+ id: 'source',
+ selected: true,
+ data: {
+ type: BlockEnum.DataSource,
+ selected: true,
+ _runningStatus: WorkflowRunningStatus.Succeeded,
+ },
+ }),
+ createNode({ id: 'kb', data: { type: BlockEnum.KnowledgeBase } }),
+ ],
+ edges: [createEdge({ id: 'source-kb', source: 'source', target: 'kb' })],
+ initialStoreState,
+ })
- mockUseStore.mockImplementation((selector: (state: Record<string, unknown>) => unknown) => {
- return selector({ pipelineId: 'test-pipeline-id' })
- })
+const startRun = async (run: PipelineRun, callback?: IOtherOptions) => {
+ await act(async () => {
+ await run.handleRun({ inputs: { query: 'test' } }, callback)
+ })
+ return mockSsePost.mock.calls.at(-1)![2] as Required<IOtherOptions>
+}
+describe('usePipelineRunByCanEdit', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
mockDoSyncWorkflowDraft.mockResolvedValue(undefined)
+ const container = document.createElement('div')
+ container.id = 'workflow-container'
+ Object.defineProperty(container, 'clientWidth', { value: 1000 })
+ Object.defineProperty(container, 'clientHeight', { value: 800 })
+ document.body.appendChild(container)
})
afterEach(() => {
- const container = document.getElementById('workflow-container')
- if (container) {
- document.body.removeChild(container)
- }
- vi.clearAllMocks()
+ document.getElementById('workflow-container')?.remove()
})
- describe('handleBackupDraft', () => {
- it('should backup draft when no backup exists', () => {
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ describe('draft backup', () => {
+ it('snapshots the current canvas once and persists the draft', () => {
+ const env = [envVar('env-1', 'value')]
+ const { result, store } = renderPipelineRun({ environmentVariables: env })
- act(() => {
- result.current.handleBackupDraft()
- })
+ act(() => result.current.run.handleBackupDraft())
+ const firstBackup = store.getState().backupDraft
+ act(() => result.current.run.handleBackupDraft())
- expect(mockSetBackupDraft).toHaveBeenCalledExactlyOnceWith({
- nodes: mockGetNodes(),
- edges: [],
+ expect(firstBackup).toMatchObject({
+ nodes: [expect.objectContaining({ id: 'source' }), expect.objectContaining({ id: 'kb' })],
+ edges: [expect.objectContaining({ id: 'source-kb' })],
+ // useReactFlow().getViewport needs a mounted d3 zoom; the hook-only canvas reports the default.
viewport: { x: 0, y: 0, zoom: 1 },
- environmentVariables: [],
- })
- expect(mockDoSyncWorkflowDraft).toHaveBeenCalled()
- })
-
- it('should not backup draft when backup already exists', () => {
- mockWorkflowStoreGetState.mockReturnValue({
- pipelineId: 'test-pipeline-id',
- backupDraft: { nodes: [], edges: [], viewport: {}, environmentVariables: [] },
- environmentVariables: [],
- setBackupDraft: mockSetBackupDraft,
- setEnvironmentVariables: mockSetEnvironmentVariables,
- setRagPipelineVariables: mockSetRagPipelineVariables,
- setWorkflowRunningData: mockSetWorkflowRunningData,
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
+ environmentVariables: env,
})
-
- act(() => {
- result.current.handleBackupDraft()
- })
-
- expect(mockSetBackupDraft).not.toHaveBeenCalled()
+ expect(store.getState().backupDraft).toBe(firstBackup)
+ expect(mockDoSyncWorkflowDraft).toHaveBeenCalledOnce()
})
- })
- describe('handleLoadBackupDraft', () => {
- it('should load backup draft when exists', () => {
+ it('restores the backup canvas and environment, then discards the backup', () => {
const backupDraft = {
- nodes: [{ id: 'backup-node' }],
- edges: [{ id: 'backup-edge' }],
+ nodes: [createNode({ id: 'backup-node' })],
+ edges: [],
viewport: { x: 100, y: 100, zoom: 1.5 },
- environmentVariables: [{ key: 'ENV', value: 'test' }],
+ environmentVariables: [envVar('env-1', 'from-backup')],
}
+ const { result, store } = renderPipelineRun({ backupDraft })
- mockWorkflowStoreGetState.mockReturnValue({
- pipelineId: 'test-pipeline-id',
- backupDraft,
- environmentVariables: [],
- setBackupDraft: mockSetBackupDraft,
- setEnvironmentVariables: mockSetEnvironmentVariables,
- setRagPipelineVariables: mockSetRagPipelineVariables,
- setWorkflowRunningData: mockSetWorkflowRunningData,
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ act(() => result.current.run.handleLoadBackupDraft())
- act(() => {
- result.current.handleLoadBackupDraft()
- })
-
- expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledWith({
+ expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledExactlyOnceWith({
nodes: backupDraft.nodes,
edges: backupDraft.edges,
viewport: backupDraft.viewport,
})
- expect(mockSetEnvironmentVariables).toHaveBeenCalledWith(backupDraft.environmentVariables)
- expect(mockSetBackupDraft).toHaveBeenCalledWith(undefined)
- })
-
- it('should not load when no backup exists', () => {
- mockWorkflowStoreGetState.mockReturnValue({
- pipelineId: 'test-pipeline-id',
+ expect(store.getState()).toMatchObject({
+ environmentVariables: backupDraft.environmentVariables,
backupDraft: undefined,
- environmentVariables: [],
- setBackupDraft: mockSetBackupDraft,
- setEnvironmentVariables: mockSetEnvironmentVariables,
- setRagPipelineVariables: mockSetRagPipelineVariables,
- setWorkflowRunningData: mockSetWorkflowRunningData,
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
})
-
- act(() => {
- result.current.handleLoadBackupDraft()
- })
-
- expect(mockHandleUpdateWorkflowCanvas).not.toHaveBeenCalled()
})
- })
- describe('handleStopRun', () => {
- it('should call stop workflow run service', () => {
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ it('leaves the canvas alone when there is no backup to restore', () => {
+ const { result } = renderPipelineRun()
- act(() => {
- result.current.handleStopRun('task-123')
- })
+ act(() => result.current.run.handleLoadBackupDraft())
- expect(mockStopWorkflowRun).toHaveBeenCalledWith(
- '/rag/pipelines/test-pipeline-id/workflow-runs/tasks/task-123/stop',
- )
+ expect(mockHandleUpdateWorkflowCanvas).not.toHaveBeenCalled()
})
})
- describe('handleRestoreFromPublishedWorkflow', () => {
- it('should restore workflow from published version', () => {
+ describe('restore from published workflow', () => {
+ it('loads the published graph unselected along with its variables', () => {
const publishedWorkflow = {
graph: {
- nodes: [{ id: 'pub-node', data: { type: 'start' } }],
- edges: [{ id: 'pub-edge' }],
+ nodes: [createNode({ id: 'pub-node', selected: true, data: { selected: true } })],
+ edges: [],
viewport: { x: 50, y: 50, zoom: 1 },
},
- environment_variables: [{ key: 'PUB_ENV', value: 'pub' }],
+ environment_variables: [envVar('pub', 'published')],
rag_pipeline_variables: [{ variable: 'input', type: 'text-input' }],
- }
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- act(() => {
- result.current.handleRestoreFromPublishedWorkflow(
- publishedWorkflow as unknown as FetchWorkflowDraftResponse,
- )
- })
-
- expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledWith({
- nodes: [{ id: 'pub-node', data: { type: 'start', selected: false }, selected: false }],
- edges: publishedWorkflow.graph.edges,
+ } as unknown as FetchWorkflowDraftResponse
+ const { result, store } = renderPipelineRun()
+
+ act(() => result.current.run.handleRestoreFromPublishedWorkflow(publishedWorkflow))
+
+ expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledExactlyOnceWith({
+ nodes: [
+ expect.objectContaining({
+ id: 'pub-node',
+ selected: false,
+ data: expect.objectContaining({ selected: false }),
+ }),
+ ],
+ edges: [],
viewport: publishedWorkflow.graph.viewport,
})
- expect(mockSetEnvironmentVariables).toHaveBeenCalledWith(
- publishedWorkflow.environment_variables,
- )
- expect(mockSetRagPipelineVariables).toHaveBeenCalledWith(
- publishedWorkflow.rag_pipeline_variables,
- )
+ expect(store.getState()).toMatchObject({
+ environmentVariables: publishedWorkflow.environment_variables,
+ ragPipelineVariables: publishedWorkflow.rag_pipeline_variables,
+ })
})
- it('should handle empty environment and rag pipeline variables', () => {
- const publishedWorkflow = {
- graph: {
- nodes: [],
- edges: [],
- viewport: { x: 0, y: 0, zoom: 1 },
- },
- environment_variables: undefined,
- rag_pipeline_variables: undefined,
- }
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
+ it('clears variables the published version does not define', () => {
+ const { result, store } = renderPipelineRun({
+ environmentVariables: [envVar('stale', 'x')],
+ ragPipelineVariables: [{ variable: 'stale' }],
})
- act(() => {
- result.current.handleRestoreFromPublishedWorkflow(
- publishedWorkflow as unknown as FetchWorkflowDraftResponse,
- )
- })
+ act(() =>
+ result.current.run.handleRestoreFromPublishedWorkflow({
+ graph: { nodes: [], edges: [], viewport: { x: 0, y: 0, zoom: 1 } },
+ } as unknown as FetchWorkflowDraftResponse),
+ )
- expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([])
- expect(mockSetRagPipelineVariables).toHaveBeenCalledWith([])
+ expect(store.getState()).toMatchObject({ environmentVariables: [], ragPipelineVariables: [] })
})
})
- describe('handleRun', () => {
- it('waits for draft sync, clears stale selection and starts the requested run', async () => {
+ describe('running', () => {
+ it('resets canvas run state, saves the draft, then streams the run', async () => {
const pending = createDeferred<void>()
mockDoSyncWorkflowDraft.mockReturnValue(pending.promise)
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
+ const { result, store } = renderPipelineRun({
+ historyWorkflowData: { id: 'old-run' },
})
- let running: Promise<void>
+ let running!: Promise<void>
act(() => {
- running = result.current.handleRun({ inputs: { query: 'test' } })
+ running = result.current.run.handleRun({ inputs: { query: 'test' } })
+ })
+
+ expect(result.current.nodes.find((node) => node.id === 'source')?.data).toMatchObject({
+ selected: false,
+ _runningStatus: undefined,
})
- expect(mockSetNodes).toHaveBeenCalledExactlyOnceWith([
- { id: 'node-1', data: { type: 'start', selected: false, _runningStatus: undefined } },
- ])
expect(mockSsePost).not.toHaveBeenCalled()
+
await act(async () => {
pending.resolve()
await running
})
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({ historyWorkflowData: undefined })
+
+ expect(store.getState()).toMatchObject({
+ historyWorkflowData: undefined,
+ workflowRunningData: {
+ result: { status: WorkflowRunningStatus.Running },
+ tracing: [],
+ resultText: '',
+ },
+ })
expect(mockSsePost).toHaveBeenCalledExactlyOnceWith(
'/rag/pipelines/test-pipeline-id/workflows/draft/run',
{ body: { inputs: { query: 'test' } } },
expect.any(Object),
)
-
- expect(mockSetWorkflowRunningData).toHaveBeenCalledWith({
- result: {
- inputs_truncated: false,
- process_data_truncated: false,
- outputs_truncated: false,
- status: WorkflowRunningStatus.Running,
- },
- tracing: [],
- resultText: '',
- })
- })
-
- it('should call onWorkflowStarted callback when provided', async () => {
- const onWorkflowStarted = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onWorkflowStarted })
- })
-
- await act(async () => {
- capturedCallbacks.onWorkflowStarted?.({ task_id: 'task-1' })
- })
-
- expect(onWorkflowStarted).toHaveBeenCalledWith({ task_id: 'task-1' })
- expect(mockInvalidateRunHistory).toHaveBeenCalled()
- })
-
- it('should call onWorkflowFinished callback when provided', async () => {
- const onWorkflowFinished = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onWorkflowFinished })
- })
-
- await act(async () => {
- capturedCallbacks.onWorkflowFinished?.({ status: 'succeeded' })
- })
-
- expect(onWorkflowFinished).toHaveBeenCalledWith({ status: 'succeeded' })
- expect(mockInvalidateRunHistory).toHaveBeenCalled()
- })
-
- it('should call onError callback when provided', async () => {
- const onError = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onError })
- })
-
- await act(async () => {
- capturedCallbacks.onError?.({ message: 'error' })
- })
-
- expect(onError).toHaveBeenCalledWith({ message: 'error' })
- expect(mockInvalidateRunHistory).toHaveBeenCalled()
- })
-
- it('should call onNodeStarted callback when provided', async () => {
- const onNodeStarted = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onNodeStarted })
- })
-
- await act(async () => {
- capturedCallbacks.onNodeStarted?.({ node_id: 'node-1' })
- })
-
- expect(onNodeStarted).toHaveBeenCalledWith({ node_id: 'node-1' })
- })
-
- it('should call onNodeFinished callback when provided', async () => {
- const onNodeFinished = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onNodeFinished })
- })
-
- await act(async () => {
- capturedCallbacks.onNodeFinished?.({ node_id: 'node-1' })
- })
-
- expect(onNodeFinished).toHaveBeenCalledWith({ node_id: 'node-1' })
- })
-
- it('should call onIterationStart callback when provided', async () => {
- const onIterationStart = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onIterationStart })
- })
-
- await act(async () => {
- capturedCallbacks.onIterationStart?.({ iteration_id: 'iter-1' })
- })
-
- expect(onIterationStart).toHaveBeenCalledWith({ iteration_id: 'iter-1' })
- })
-
- it('should call onIterationNext callback when provided', async () => {
- const onIterationNext = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onIterationNext })
- })
-
- await act(async () => {
- capturedCallbacks.onIterationNext?.({ index: 1 })
- })
-
- expect(onIterationNext).toHaveBeenCalledWith({ index: 1 })
})
- it('should call onIterationFinish callback when provided', async () => {
- const onIterationFinish = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onIterationFinish })
- })
-
- await act(async () => {
- capturedCallbacks.onIterationFinish?.({ iteration_id: 'iter-1' })
- })
-
- expect(onIterationFinish).toHaveBeenCalledWith({ iteration_id: 'iter-1' })
- })
-
- it('should call onLoopStart callback when provided', async () => {
- const onLoopStart = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onLoopStart })
- })
-
- await act(async () => {
- capturedCallbacks.onLoopStart?.({ loop_id: 'loop-1' })
- })
-
- expect(onLoopStart).toHaveBeenCalledWith({ loop_id: 'loop-1' })
- })
-
- it('should call onLoopNext callback when provided', async () => {
- const onLoopNext = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ it.each([
+ ['onWorkflowStarted', 'handleWorkflowStarted'],
+ ['onWorkflowFinished', 'handleWorkflowFinished'],
+ ['onError', 'handleWorkflowFailed'],
+ ['onNodeStarted', 'handleWorkflowNodeStarted'],
+ ['onNodeFinished', 'handleWorkflowNodeFinished'],
+ ['onIterationStart', 'handleWorkflowNodeIterationStarted'],
+ ['onIterationNext', 'handleWorkflowNodeIterationNext'],
+ ['onIterationFinish', 'handleWorkflowNodeIterationFinished'],
+ ['onLoopStart', 'handleWorkflowNodeLoopStarted'],
+ ['onLoopNext', 'handleWorkflowNodeLoopNext'],
+ ['onLoopFinish', 'handleWorkflowNodeLoopFinished'],
+ ['onNodeRetry', 'handleWorkflowNodeRetry'],
+ ['onAgentLog', 'handleWorkflowAgentLog'],
+ ] as const)(
+ 'applies %s to the canvas and forwards it to the caller',
+ async (event, handler) => {
+ const callerCallback = vi.fn()
+ const { result } = renderPipelineRun()
+ const stream = await startRun(result.current.run, { [event]: callerCallback })
+ const payload = { event }
+
+ act(() => (stream[event] as (params: unknown) => void)(payload))
+
+ expect(runEvents[handler]).toHaveBeenCalledOnce()
+ expect(runEvents[handler].mock.calls[0]![0]).toBe(event === 'onError' ? undefined : payload)
+ expect(callerCallback).toHaveBeenCalledExactlyOnceWith(payload)
+ },
+ )
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onLoopNext })
- })
+ it('positions started nodes against the workflow container size', async () => {
+ const { result } = renderPipelineRun()
+ const stream = await startRun(result.current.run)
- await act(async () => {
- capturedCallbacks.onLoopNext?.({ index: 2 })
- })
+ act(() => stream.onNodeStarted({ node_id: 'kb' } as never))
- expect(onLoopNext).toHaveBeenCalledWith({ index: 2 })
+ expect(runEvents.handleWorkflowNodeStarted).toHaveBeenCalledWith(
+ { node_id: 'kb' },
+ { clientWidth: 1000, clientHeight: 800 },
+ )
})
- it('should call onLoopFinish callback when provided', async () => {
- const onLoopFinish = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
+ it.each([
+ ['onTextChunk', 'handleWorkflowTextChunk'],
+ ['onTextReplace', 'handleWorkflowTextReplace'],
+ ] as const)('applies %s to the run output', async (event, handler) => {
+ const { result } = renderPipelineRun()
+ const stream = await startRun(result.current.run)
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onLoopFinish })
- })
+ act(() => (stream[event] as (params: unknown) => void)({ text: 'chunk' }))
- await act(async () => {
- capturedCallbacks.onLoopFinish?.({ loop_id: 'loop-1' })
- })
-
- expect(onLoopFinish).toHaveBeenCalledWith({ loop_id: 'loop-1' })
+ expect(runEvents[handler]).toHaveBeenCalledExactlyOnceWith({ text: 'chunk' })
})
- it('should call onNodeRetry callback when provided', async () => {
- const onNodeRetry = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
+ it('refreshes run history on lifecycle events and inspect data when the run finishes', async () => {
+ const { result } = renderPipelineRun()
+ const stream = await startRun(result.current.run)
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
+ act(() => stream.onWorkflowStarted({} as never))
+ expect(mockInvalidateRunHistory).toHaveBeenLastCalledWith(RUN_HISTORY_URL)
+ expect(mockFetchInspectVars).not.toHaveBeenCalled()
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ act(() => stream.onWorkflowFinished({} as never))
+ expect(mockFetchInspectVars).toHaveBeenCalledExactlyOnceWith({})
+ expect(mockInvalidAllLastRun).toHaveBeenCalledOnce()
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onNodeRetry })
- })
-
- await act(async () => {
- capturedCallbacks.onNodeRetry?.({ node_id: 'node-1', retry: 1 })
- })
-
- expect(onNodeRetry).toHaveBeenCalledWith({ node_id: 'node-1', retry: 1 })
+ act(() => stream.onError({} as never))
+ expect(mockInvalidateRunHistory).toHaveBeenCalledTimes(3)
})
- it('should call onAgentLog callback when provided', async () => {
- const onAgentLog = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ it('passes other stream callbacks through untouched', async () => {
+ const onData = vi.fn()
+ const { result } = renderPipelineRun()
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, { onAgentLog })
- })
+ const stream = await startRun(result.current.run, { onData } as IOtherOptions)
- await act(async () => {
- capturedCallbacks.onAgentLog?.({ message: 'agent log' })
- })
-
- expect(onAgentLog).toHaveBeenCalledWith({ message: 'agent log' })
+ expect(stream.onData).toBe(onData)
})
+ })
- it('should handle onTextChunk callback', async () => {
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} })
- })
-
- await act(async () => {
- capturedCallbacks.onTextChunk?.({ text: 'chunk' })
- })
-
- expect(mockTextChunk).toHaveBeenCalledExactlyOnceWith({ text: 'chunk' })
- })
-
- it('should handle onTextReplace callback', async () => {
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
+ describe('stopping', () => {
+ it('stops the server task and aborts the open stream', async () => {
+ const { result } = renderPipelineRun()
+ const stream = await startRun(result.current.run)
+ const controller = new AbortController()
+ stream.getAbortController(controller)
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
-
- await act(async () => {
- await result.current.handleRun({ inputs: {} })
- })
-
- await act(async () => {
- capturedCallbacks.onTextReplace?.({ text: 'replaced' })
- })
+ act(() => result.current.run.handleStopRun('task-123'))
- expect(mockTextReplace).toHaveBeenCalledExactlyOnceWith({ text: 'replaced' })
+ expect(mockStopWorkflowRun).toHaveBeenCalledExactlyOnceWith(
+ '/rag/pipelines/test-pipeline-id/workflow-runs/tasks/task-123/stop',
+ )
+ expect(controller.signal.aborted).toBe(true)
})
- it('should pass rest callback to ssePost', async () => {
- const customCallback = vi.fn()
- let capturedCallbacks: Record<string, (params: unknown) => void> = {}
-
- mockSsePost.mockImplementation((_url, _body, callbacks) => {
- capturedCallbacks = callbacks
- })
-
- const { result } = renderHook(() => usePipelineRunByCanEdit(true), {
- resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },
- })
+ it('aborts the previous stream when a new run starts', async () => {
+ const { result } = renderPipelineRun()
+ const firstStream = await startRun(result.current.run)
+ const firstController = new AbortController()
+ firstStream.getAbortController(firstController)
- await act(async () => {
- await result.current.handleRun({ inputs: {} }, {
- onData: customCallback,
- } as unknown as Parameters<typeof result.current.handleRun>[1])
- })
+ await startRun(result.current.run)
- expect(capturedCallbacks.onData).toBe(customCallback)
+ expect(firstController.signal.aborted).toBe(true)
})
})
})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-start-run.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-start-run.spec.ts
index df61c86ec6f..e8baf4a2c60 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-start-run.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-start-run.spec.ts
@@ -1,26 +1,15 @@
-import { renderHook } from '@testing-library/react'
-import { act } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store/workflow'
+import { act } from '@testing-library/react'
+import {
+ baseRunningData,
+ renderWorkflowCanvasHook,
+} from '@/app/components/workflow/__tests__/workflow-test-env'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
import { createDeferred } from '@/test/deferred'
+import { createRagPipelineSliceSlice } from '../../store'
import { usePipelineStartRunByCanEdit } from '../use-pipeline-start-run'
-const mockWorkflowStoreGetState = vi.fn()
-const mockWorkflowStoreSetState = vi.fn()
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => ({
- getState: mockWorkflowStoreGetState,
- setState: mockWorkflowStoreSetState,
- }),
-}))
-
-const mockHandleCancelDebugAndPreviewPanel = vi.fn()
-vi.mock('@/app/components/workflow/hooks/use-workflow-panel-interactions', () => ({
- useWorkflowInteractions: () => ({
- handleCancelDebugAndPreviewPanel: mockHandleCancelDebugAndPreviewPanel,
- }),
-}))
-
+// Draft persistence has its own suite; here it only gates when the run panel opens.
const mockDoSyncWorkflowDraft = vi.fn()
vi.mock('../use-nodes-sync-draft', () => ({
useNodesSyncDraftByCanEdit: () => ({
@@ -28,154 +17,100 @@ vi.mock('../use-nodes-sync-draft', () => ({
}),
}))
-vi.mock('../use-input-field-panel', () => ({
- useInputFieldPanel: () => ({
- closeAllInputFieldPanels: vi.fn(),
- }),
-}))
+const renderStartRun = (initialStoreState: Record<string, unknown> = {}) =>
+ renderWorkflowCanvasHook(() => usePipelineStartRunByCanEdit(true), {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },
+ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice as InjectWorkflowStoreSliceFn,
+ initialStoreState,
+ })
describe('usePipelineStartRunByCanEdit', () => {
- const mockSetIsPreparingDataSource = vi.fn()
- const mockSetShowEnvPanel = vi.fn()
- const mockSetShowDebugAndPreviewPanel = vi.fn()
-
beforeEach(() => {
- vi.clearAllMocks()
+ mockDoSyncWorkflowDraft.mockResolvedValue(undefined)
+ })
- mockWorkflowStoreGetState.mockReturnValue({
- workflowRunningData: undefined,
+ it('saves the draft before opening datasource preparation in the run panel', async () => {
+ const pending = createDeferred<void>()
+ mockDoSyncWorkflowDraft.mockReturnValue(pending.promise)
+ const { result, store } = renderStartRun({
+ showEnvPanel: true,
+ showInputFieldPanel: true,
+ showInputFieldPreviewPanel: true,
+ })
+
+ let running!: Promise<void>
+ act(() => {
+ running = result.current.handleWorkflowStartRunInWorkflow()
+ })
+
+ expect(store.getState()).toMatchObject({
+ showEnvPanel: false,
+ showInputFieldPanel: false,
+ showInputFieldPreviewPanel: false,
isPreparingDataSource: false,
showDebugAndPreviewPanel: false,
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- setShowEnvPanel: mockSetShowEnvPanel,
- setShowDebugAndPreviewPanel: mockSetShowDebugAndPreviewPanel,
})
- mockDoSyncWorkflowDraft.mockResolvedValue(undefined)
- })
+ await act(async () => {
+ pending.resolve()
+ await running
+ })
- afterEach(() => {
- vi.clearAllMocks()
+ expect(mockDoSyncWorkflowDraft).toHaveBeenCalledOnce()
+ expect(store.getState()).toMatchObject({
+ isPreparingDataSource: true,
+ showDebugAndPreviewPanel: true,
+ })
})
- describe('handleWorkflowStartRunInWorkflow', () => {
- it('should not proceed when workflow is already running', async () => {
- mockWorkflowStoreGetState.mockReturnValue({
- workflowRunningData: {
- result: { status: WorkflowRunningStatus.Running },
- },
- isPreparingDataSource: false,
- showDebugAndPreviewPanel: false,
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- setShowEnvPanel: mockSetShowEnvPanel,
- setShowDebugAndPreviewPanel: mockSetShowDebugAndPreviewPanel,
- })
-
- const { result } = renderHook(() => usePipelineStartRunByCanEdit(true))
-
- await act(async () => {
- await result.current.handleWorkflowStartRunInWorkflow()
- })
-
- expect(mockSetShowEnvPanel).not.toHaveBeenCalled()
- expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(mockWorkflowStoreSetState).not.toHaveBeenCalled()
+ it('ignores a start request while a run is in progress', async () => {
+ const runningData = baseRunningData({ result: { status: WorkflowRunningStatus.Running } })
+ const { result, store } = renderStartRun({
+ workflowRunningData: runningData,
+ showEnvPanel: true,
})
- it('should set preparing data source when not preparing and has running data', async () => {
- mockWorkflowStoreGetState.mockReturnValue({
- workflowRunningData: {
- result: { status: WorkflowRunningStatus.Succeeded },
- },
- isPreparingDataSource: false,
- showDebugAndPreviewPanel: false,
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- setShowEnvPanel: mockSetShowEnvPanel,
- setShowDebugAndPreviewPanel: mockSetShowDebugAndPreviewPanel,
- })
-
- const { result } = renderHook(() => usePipelineStartRunByCanEdit(true))
-
- await act(async () => {
- await result.current.handleWorkflowStartRunInWorkflow()
- })
-
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
- isPreparingDataSource: true,
- workflowRunningData: undefined,
- })
+ await act(async () => {
+ await result.current.handleWorkflowStartRunInWorkflow()
})
- it('should cancel debug panel when already showing', async () => {
- mockWorkflowStoreGetState.mockReturnValue({
- workflowRunningData: undefined,
- isPreparingDataSource: false,
- showDebugAndPreviewPanel: true,
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- setShowEnvPanel: mockSetShowEnvPanel,
- setShowDebugAndPreviewPanel: mockSetShowDebugAndPreviewPanel,
- })
-
- const { result } = renderHook(() => usePipelineStartRunByCanEdit(true))
+ expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(store.getState()).toMatchObject({
+ workflowRunningData: runningData,
+ showEnvPanel: true,
+ })
+ })
- await act(async () => {
- await result.current.handleWorkflowStartRunInWorkflow()
- })
+ it('returns a finished run to datasource preparation', async () => {
+ const { result, store } = renderStartRun({
+ workflowRunningData: baseRunningData({ result: { status: WorkflowRunningStatus.Succeeded } }),
+ })
- expect(mockSetIsPreparingDataSource).toHaveBeenCalledWith(false)
- expect(mockHandleCancelDebugAndPreviewPanel).toHaveBeenCalled()
+ await act(async () => {
+ await result.current.handleWorkflowStartRunInWorkflow()
})
- it('should wait for draft synchronization before showing datasource preparation', async () => {
- const pending = createDeferred<void>()
- mockDoSyncWorkflowDraft.mockReturnValue(pending.promise)
- mockWorkflowStoreGetState.mockReturnValue({
- workflowRunningData: undefined,
- isPreparingDataSource: false,
- showDebugAndPreviewPanel: false,
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- setShowEnvPanel: mockSetShowEnvPanel,
- setShowDebugAndPreviewPanel: mockSetShowDebugAndPreviewPanel,
- })
-
- const { result } = renderHook(() => usePipelineStartRunByCanEdit(true))
-
- let running: Promise<void>
- act(() => {
- running = result.current.handleWorkflowStartRunInWorkflow()
- })
- expect(mockSetShowEnvPanel).toHaveBeenCalledWith(false)
- expect(mockSetIsPreparingDataSource).not.toHaveBeenCalled()
- expect(mockSetShowDebugAndPreviewPanel).not.toHaveBeenCalled()
- await act(async () => {
- pending.resolve()
- await running
- })
-
- expect(mockDoSyncWorkflowDraft).toHaveBeenCalledOnce()
- expect(mockSetIsPreparingDataSource).toHaveBeenCalledWith(true)
- expect(mockSetShowDebugAndPreviewPanel).toHaveBeenCalledWith(true)
+ expect(store.getState()).toMatchObject({
+ isPreparingDataSource: true,
+ workflowRunningData: undefined,
})
+ expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()
})
- describe('handleStartWorkflowRun', () => {
- it('should call handleWorkflowStartRunInWorkflow', async () => {
- mockWorkflowStoreGetState.mockReturnValue({
- workflowRunningData: undefined,
- isPreparingDataSource: false,
- showDebugAndPreviewPanel: false,
- setIsPreparingDataSource: mockSetIsPreparingDataSource,
- setShowEnvPanel: mockSetShowEnvPanel,
- setShowDebugAndPreviewPanel: mockSetShowDebugAndPreviewPanel,
- })
-
- const { result } = renderHook(() => usePipelineStartRunByCanEdit(true))
+ it('closes an open run panel instead of starting another run', async () => {
+ const { result, store } = renderStartRun({
+ showDebugAndPreviewPanel: true,
+ isPreparingDataSource: true,
+ })
- await act(async () => {
- result.current.handleStartWorkflowRun()
- })
+ act(() => {
+ result.current.handleStartWorkflowRun()
+ })
- expect(mockSetShowEnvPanel).toHaveBeenCalledWith(false)
+ expect(store.getState()).toMatchObject({
+ isPreparingDataSource: false,
+ showDebugAndPreviewPanel: false,
})
+ expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
index d21ba5b7a89..f694a6e9a24 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
@@ -58,12 +58,6 @@ vi.mock('@/context/event-emitter', () => ({
}),
}))
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => ({
- getState: () => ({ pipelineId: 'test-pipeline-id' }),
- }),
-}))
-
vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({
usePluginDependencies: () => ({
handleCheckPluginDependencies: mockHandleCheckPluginDependencies,
diff --git a/web/app/components/rag-pipeline/hooks/use-DSL.ts b/web/app/components/rag-pipeline/hooks/use-DSL.ts
index 9236f8c8642..40d57657de8 100644
--- a/web/app/components/rag-pipeline/hooks/use-DSL.ts
+++ b/web/app/components/rag-pipeline/hooks/use-DSL.ts
@@ -79,7 +79,7 @@ const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
} catch {
toast.error(t(($) => $.exportFailed, { ns: 'app' }))
}
- }, [eventEmitter, handleExportDSL, t, workflowStore])
+ }, [eventEmitter, handleExportDSL, t, pipelineId])
return {
exportCheck,
handleExportDSL,
diff --git a/web/app/components/rag-pipeline/hooks/use-get-run-and-trace-url.ts b/web/app/components/rag-pipeline/hooks/use-get-run-and-trace-url.ts
index 79d2c852d87..12f8d9bdf3d 100644
--- a/web/app/components/rag-pipeline/hooks/use-get-run-and-trace-url.ts
+++ b/web/app/components/rag-pipeline/hooks/use-get-run-and-trace-url.ts
@@ -1,11 +1,9 @@
import { useAtomValue } from 'jotai'
import { useCallback } from 'react'
import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'
-import { useWorkflowStore } from '@/app/components/workflow/store'
export const useGetRunAndTraceUrl = () => {
const { pipelineId } = useAtomValue(knowledgePipelineIdentityAtom)
- const workflowStore = useWorkflowStore()
const getWorkflowRunAndTraceUrl = useCallback(
(runId: string) => {
return {
@@ -13,7 +11,7 @@ export const useGetRunAndTraceUrl = () => {
traceUrl: `/rag/pipelines/${pipelineId}/workflow-runs/${runId}/node-executions`,
}
},
- [workflowStore],
+ [pipelineId],
)
return {
diff --git a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts b/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts
index decc3529631..3325a441565 100644
--- a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts
+++ b/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts
@@ -64,7 +64,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
},
}
}
- }, [store, workflowStore])
+ }, [store, workflowStore, pipelineId])
const syncWorkflowDraftWhenPageClose = useCallback(() => {
if (getNodesReadOnly()) return
diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.ts
index 58457aeb1f8..1d10548614d 100644
--- a/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.ts
+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.ts
@@ -52,7 +52,7 @@ export const usePipelineRefreshDraft = () => {
setRagPipelineVariables?.(response.rag_pipeline_variables || [])
})
.finally(() => setIsSyncingWorkflowDraft(false))
- }, [handleUpdateWorkflowCanvas, workflowStore])
+ }, [handleUpdateWorkflowCanvas, workflowStore, pipelineId])
return {
handleRefreshWorkflowDraft,
diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
index 1026b5a8112..1fcdb6eee22 100644
--- a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
@@ -256,6 +256,7 @@ const usePipelineRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
handleWorkflowAgentLog,
handleWorkflowTextChunk,
handleWorkflowTextReplace,
+ pipelineId,
],
)
@@ -267,7 +268,7 @@ const usePipelineRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
abortControllerRef.current = null
},
- [workflowStore],
+ [pipelineId],
)
const handleRestoreFromPublishedWorkflow = useCallback(
diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.tsx b/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.tsx
index 79a47adb54b..6b49cb47b5b 100644
--- a/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.tsx
+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.tsx
@@ -46,7 +46,12 @@ const usePipelineStartRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
await doSyncWorkflowDraft()
setIsPreparingDataSource?.(true)
setShowDebugAndPreviewPanel(true)
- }, [workflowStore, handleCancelDebugAndPreviewPanel, doSyncWorkflowDraft])
+ }, [
+ workflowStore,
+ handleCancelDebugAndPreviewPanel,
+ doSyncWorkflowDraft,
+ closeAllInputFieldPanels,
+ ])
const handleStartWorkflowRun = useCallback(() => {
handleWorkflowStartRunInWorkflow()
diff --git a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
index 54936f654e0..df68ef3fed8 100644
--- a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
+++ b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
@@ -6,7 +6,6 @@ import { useTranslation } from 'react-i18next'
import { WORKFLOW_DATA_UPDATE } from '@/app/components/workflow/constants'
import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'
import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'
-import { useWorkflowStore } from '@/app/components/workflow/store'
import { initialEdges, initialNodes } from '@/app/components/workflow/utils'
import { toast } from '@/app/notifications'
import { useEventEmitterContextContext } from '@/context/event-emitter'
@@ -29,7 +28,6 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam
const { t } = useTranslation(['workflow'] as const)
const { eventEmitter } = useEventEmitterContextContext()
const { pipelineId } = useAtomValue(knowledgePipelineIdentityAtom)
- const workflowStore = useWorkflowStore()
const { handleCheckPluginDependencies } = usePluginDependencies()
const { mutateAsync: importDSL } = useMutation(
consoleQuery.rag.pipelines.imports.post.mutationOptions(),
@@ -151,7 +149,7 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam
}, [
currentFile,
fileContent,
- workflowStore,
+ pipelineId,
importDSL,
completeImport,
showVersionMismatch,
diff --git a/web/app/components/snippets/components/__tests__/snippet-run-panel.spec.tsx b/web/app/components/snippets/components/__tests__/snippet-run-panel.spec.tsx
index 5ee177f42d0..a17ce4ebc4e 100644
--- a/web/app/components/snippets/components/__tests__/snippet-run-panel.spec.tsx
+++ b/web/app/components/snippets/components/__tests__/snippet-run-panel.spec.tsx
@@ -7,16 +7,20 @@ import { WorkflowRunningStatus } from '@/app/components/workflow/types'
import { PipelineInputVarType } from '@/models/pipeline'
import SnippetRunPanel from '../snippet-run-panel'
-const renderWorkflowComponent = (
- ui: Parameters<typeof renderWithWorkflowStore>[0],
- options?: Parameters<typeof renderWithWorkflowStore>[1],
-) => renderWithWorkflowStore(<ReactFlowProvider>{ui}</ReactFlowProvider>, options)
-
const workflowHookMocks = vi.hoisted(() => ({
- handleCancelDebugAndPreviewPanel: vi.fn(),
handleRun: vi.fn(),
}))
+const renderWorkflowComponent = (
+ ui: Parameters<typeof renderWithWorkflowStore>[0],
+ options?: Parameters<typeof renderWithWorkflowStore>[1],
+) =>
+ renderWithWorkflowStore(<ReactFlowProvider>{ui}</ReactFlowProvider>, {
+ ...options,
+ // The snippet run stream comes from the snippet hooks through the hooks store.
+ hooksStoreProps: { handleRun: workflowHookMocks.handleRun },
+ })
+
const toastMocks = vi.hoisted(() => ({
success: vi.fn(),
error: vi.fn(),
@@ -33,18 +37,6 @@ vi.mock('@/app/notifications', () => ({
toast: toastMocks,
}))
-vi.mock('@/app/components/workflow/hooks/use-workflow-panel-interactions', () => ({
- useWorkflowInteractions: () => ({
- handleCancelDebugAndPreviewPanel: workflowHookMocks.handleCancelDebugAndPreviewPanel,
- }),
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-workflow-run', () => ({
- useWorkflowRun: () => ({
- handleRun: workflowHookMocks.handleRun,
- }),
-}))
-
vi.mock('@/app/components/workflow/run/result-text', () => ({
default: ({ outputs, onClick }: { outputs?: string; onClick: () => void }) => (
<button type="button" onClick={onClick}>
@@ -94,14 +86,14 @@ describe('SnippetRunPanel', () => {
it('closes the panel from its close action', async () => {
const user = userEvent.setup()
- renderWorkflowComponent(<SnippetRunPanel fields={[]} />, {
- initialStoreState: { previewPanelWidth: 480 },
+ const { store } = renderWorkflowComponent(<SnippetRunPanel fields={[]} />, {
+ initialStoreState: { previewPanelWidth: 480, showDebugAndPreviewPanel: true },
})
const closeButton = screen.getByRole('button', { name: 'common.operation.close' })
await user.click(closeButton)
- expect(workflowHookMocks.handleCancelDebugAndPreviewPanel).toHaveBeenCalledOnce()
+ expect(store.getState().showDebugAndPreviewPanel).toBe(false)
})
it('disables result tabs until a workflow run is available', async () => {
diff --git a/web/app/components/snippets/components/snippet-header/__tests__/run-mode.spec.tsx b/web/app/components/snippets/components/snippet-header/__tests__/run-mode.spec.tsx
index 39ff412845d..dc07d05536f 100644
--- a/web/app/components/snippets/components/snippet-header/__tests__/run-mode.spec.tsx
+++ b/web/app/components/snippets/components/snippet-header/__tests__/run-mode.spec.tsx
@@ -26,21 +26,16 @@ const renderRunMode = (text?: string, workflowRunningData?: ReturnType<typeof ba
<EventSource />
<RunMode text={text} />
</EventEmitterProvider>,
- { initialStoreState: { workflowRunningData } },
+ {
+ initialStoreState: { workflowRunningData },
+ // Start and stop come from the snippet hooks through the hooks store.
+ hooksStoreProps: {
+ handleWorkflowStartRunInWorkflow: workflowHookMocks.handleWorkflowStartRunInWorkflow,
+ handleStopRun: workflowHookMocks.handleStopRun,
+ },
+ },
)
-vi.mock('@/app/components/workflow/hooks/use-workflow-run', () => ({
- useWorkflowRun: () => ({
- handleStopRun: workflowHookMocks.handleStopRun,
- }),
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-workflow-start-run', () => ({
- useWorkflowStartRun: () => ({
- handleWorkflowStartRunInWorkflow: workflowHookMocks.handleWorkflowStartRunInWorkflow,
- }),
-}))
-
describe('RunMode', () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts
index ac36dd014a8..6e7e79ba27a 100644
--- a/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/snippets/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -1,48 +1,20 @@
import type { InputVar } from '@/models/pipeline'
import { ORPCError } from '@orpc/client'
-import { act, renderHook, waitFor } from '@testing-library/react'
+import { act, waitFor } from '@testing-library/react'
+import { createEdge, 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 { PipelineInputVarType } from '@/models/pipeline'
import { createDeferred } from '@/test/deferred'
import { useSnippetDraftStore } from '../../draft-store'
import { useNodesSyncDraft } from '../use-nodes-sync-draft'
const mockRefreshDraft = vi.fn()
-const mockGetNodes = vi.fn()
-const mockGetNodesReadOnly = vi.fn()
-const mockUseNodesReadOnlyByCanEdit = vi.fn()
const mockPostWithKeepalive = vi.fn()
const mockSyncDraftWorkflow = vi.fn()
-const mockSetDraftUpdatedAt = vi.fn()
-const mockSetSyncWorkflowDraftHash = vi.fn()
-
-let reactFlowState: {
- getNodes: typeof mockGetNodes
- edges: Array<Record<string, unknown>>
- transform: [number, number, number]
-}
-
-let workflowStoreState: {
- syncWorkflowDraftHash: string | null
- setDraftUpdatedAt: typeof mockSetDraftUpdatedAt
- setSyncWorkflowDraftHash: typeof mockSetSyncWorkflowDraftHash
-}
-
-vi.mock('reactflow', () => ({
- useStoreApi: () => ({ getState: () => reactFlowState }),
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({
- useNodesReadOnlyByCanEdit: (canEdit: boolean) => mockUseNodesReadOnlyByCanEdit(canEdit),
-}))
-
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => ({
- getState: () => workflowStoreState,
- }),
-}))
// Rejections pass through the console link's contract error validation, as in production.
-vi.mock('@/service/console', async () => {
+vi.mock('@/service/console', async (importOriginal) => {
const { snippets } = await import('@dify/contracts/api/console/snippets/orpc.gen')
const { validateDefinedErrors } = await import('@/service/console/defined-errors')
const validate = validateDefinedErrors({ snippets })
@@ -53,14 +25,21 @@ vi.mock('@/service/console', async () => {
path: ['snippets', 'bySnippetId', 'workflows', 'draft', 'post'],
next: () => mockSyncDraftWorkflow(...args),
})
- return { consoleClient: { snippets: { bySnippetId: { workflows: { draft: { post } } } } } }
+ return {
+ ...(await importOriginal<typeof import('@/service/console')>()),
+ consoleClient: { snippets: { bySnippetId: { workflows: { draft: { post } } } } },
+ }
})
-vi.mock('@/service/fetch', () => ({
+vi.mock('@/service/fetch', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/fetch')>()),
postWithKeepalive: (...args: unknown[]) => mockPostWithKeepalive(...args),
}))
-vi.mock('@/config', () => ({ API_PREFIX: '/api' }))
+vi.mock('@/config', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/config')>()),
+ API_PREFIX: '/api',
+}))
vi.mock('../use-snippet-refresh-draft', () => ({
useSnippetRefreshDraft: () => ({
@@ -75,32 +54,40 @@ const createInputField = (variable: string): InputVar => ({
required: false,
})
+const canvasNode = createNode({
+ id: 'node-1',
+ data: { type: BlockEnum.Start, title: 'Start', _temp: 'drop' },
+})
+const canvasEdge = createEdge({ id: 'edge-1', source: 'node-1', target: 'node-2' })
+const savedGraph = {
+ nodes: [
+ expect.objectContaining({
+ id: 'node-1',
+ position: { x: 0, y: 0 },
+ data: { type: BlockEnum.Start, title: 'Start', desc: '' },
+ }),
+ ],
+ edges: [canvasEdge],
+ viewport: { x: 12, y: 24, zoom: 1.5 },
+}
+
+const renderSnippetDraftSync = () =>
+ renderWorkflowCanvasHook(() => useNodesSyncDraft('snippet-1'), {
+ resource: { kind: 'snippet', snippetId: 'snippet-1' },
+ nodes: [canvasNode],
+ edges: [canvasEdge],
+ transform: [12, 24, 1.5],
+ initialStoreState: { syncWorkflowDraftHash: 'draft-hash' },
+ })
+
describe('snippet/use-nodes-sync-draft', () => {
beforeEach(() => {
vi.resetAllMocks()
useSnippetDraftStore.getState().reset()
- reactFlowState = {
- getNodes: mockGetNodes,
- edges: [{ id: 'edge-1', source: 'node-1', target: 'node-2', data: { stable: true } }],
- transform: [12, 24, 1.5],
- }
- workflowStoreState = {
- syncWorkflowDraftHash: 'draft-hash',
- setDraftUpdatedAt: mockSetDraftUpdatedAt,
- setSyncWorkflowDraftHash: mockSetSyncWorkflowDraftHash,
- }
- mockUseNodesReadOnlyByCanEdit.mockReturnValue({ getNodesReadOnly: mockGetNodesReadOnly })
- mockGetNodesReadOnly.mockReturnValue(false)
- mockGetNodes.mockReturnValue([
- { id: 'node-1', position: { x: 0, y: 0 }, data: { title: 'Start', _temp: 'drop' } },
- ])
mockSyncDraftWorkflow.mockResolvedValue({
hash: 'next-hash',
updated_at: 123,
})
- mockSetSyncWorkflowDraftHash.mockImplementation((hash: string) => {
- workflowStoreState.syncWorkflowDraftHash = hash
- })
useSnippetDraftStore.getState().setInputFields([createInputField('topic')])
})
@@ -123,7 +110,7 @@ describe('snippet/use-nodes-sync-draft', () => {
}),
)
const callback = { onError: vi.fn(), onSuccess: vi.fn(), onSettled: vi.fn() }
- const { result } = renderHook(() => useNodesSyncDraft('snippet-1'))
+ const { result, store } = renderSnippetDraftSync()
await act(async () => {
expect(await result.current.doSyncWorkflowDraft(skipRefresh, callback)).toBeUndefined()
@@ -133,7 +120,7 @@ describe('snippet/use-nodes-sync-draft', () => {
expect(callback.onError).toHaveBeenCalledOnce()
expect(callback.onSuccess).not.toHaveBeenCalled()
expect(callback.onSettled).toHaveBeenCalledOnce()
- expect(mockSetSyncWorkflowDraftHash).not.toHaveBeenCalled()
+ expect(store.getState().syncWorkflowDraftHash).toBe('draft-hash')
expect(useSnippetDraftStore.getState().inputFields).toEqual([createInputField('topic')])
await act(async () => {
@@ -142,12 +129,15 @@ describe('snippet/use-nodes-sync-draft', () => {
expect(callback.onSuccess).toHaveBeenCalledOnce()
expect(callback.onSettled).toHaveBeenCalledTimes(2)
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('next-hash')
+ expect(store.getState()).toMatchObject({
+ syncWorkflowDraftHash: 'next-hash',
+ draftUpdatedAt: 123_000,
+ })
},
)
it('should include current input_fields when syncing the draft graph', async () => {
- const { result } = renderHook(() => useNodesSyncDraft('snippet-1'))
+ const { result } = renderSnippetDraftSync()
await act(async () => {
await result.current.doSyncWorkflowDraft()
@@ -156,11 +146,7 @@ describe('snippet/use-nodes-sync-draft', () => {
expect(mockSyncDraftWorkflow).toHaveBeenCalledWith({
params: { snippet_id: 'snippet-1' },
body: {
- graph: {
- nodes: [{ id: 'node-1', position: { x: 0, y: 0 }, data: { title: 'Start' } }],
- edges: [{ id: 'edge-1', source: 'node-1', target: 'node-2', data: { stable: true } }],
- viewport: { x: 12, y: 24, zoom: 1.5 },
- },
+ graph: savedGraph,
input_fields: [createInputField('topic')],
hash: 'draft-hash',
},
@@ -168,7 +154,7 @@ describe('snippet/use-nodes-sync-draft', () => {
})
it('should include the latest graph when syncing input fields', async () => {
- const { result } = renderHook(() => useNodesSyncDraft('snippet-1'))
+ const { result } = renderSnippetDraftSync()
const nextFields = [createInputField('summary')]
await act(async () => {
@@ -178,11 +164,7 @@ describe('snippet/use-nodes-sync-draft', () => {
expect(mockSyncDraftWorkflow).toHaveBeenCalledWith({
params: { snippet_id: 'snippet-1' },
body: {
- graph: {
- nodes: [{ id: 'node-1', position: { x: 0, y: 0 }, data: { title: 'Start' } }],
- edges: [{ id: 'edge-1', source: 'node-1', target: 'node-2', data: { stable: true } }],
- viewport: { x: 12, y: 24, zoom: 1.5 },
- },
+ graph: savedGraph,
input_fields: nextFields,
hash: 'draft-hash',
},
@@ -192,26 +174,36 @@ describe('snippet/use-nodes-sync-draft', () => {
it('queues saves across hook instances while preserving captured graphs and advancing the hash', async () => {
const firstSave = createDeferred<{ hash: string; updated_at: number }>()
mockSyncDraftWorkflow.mockReturnValueOnce(firstSave.promise)
- const { result: firstHook } = renderHook(() => useNodesSyncDraft('snippet-1'))
- const { result: secondHook } = renderHook(() => useNodesSyncDraft('snippet-1'))
- let first!: ReturnType<typeof firstHook.current.doSyncWorkflowDraft>
- let second!: ReturnType<typeof secondHook.current.doSyncWorkflowDraft>
+ const { result, setCanvas, store } = renderWorkflowCanvasHook(
+ () => [useNodesSyncDraft('snippet-1'), useNodesSyncDraft('snippet-1')] as const,
+ {
+ resource: { kind: 'snippet', snippetId: 'snippet-1' },
+ nodes: [canvasNode],
+ edges: [canvasEdge],
+ transform: [12, 24, 1.5],
+ initialStoreState: { syncWorkflowDraftHash: 'draft-hash' },
+ },
+ )
+ const [firstHook, secondHook] = result.current
+ let first!: ReturnType<typeof firstHook.doSyncWorkflowDraft>
+ let second!: ReturnType<typeof secondHook.doSyncWorkflowDraft>
act(() => {
- first = firstHook.current.doSyncWorkflowDraft()
+ first = firstHook.doSyncWorkflowDraft()
})
await waitFor(() => expect(mockSyncDraftWorkflow).toHaveBeenCalledOnce())
- const queuedNode = { id: 'queued-node', position: { x: 2, y: 3 }, data: { title: 'Queued' } }
- mockGetNodes.mockReturnValue([queuedNode])
- reactFlowState.edges = []
- reactFlowState.transform = [20, 30, 1.2]
+ const queuedNode = createNode({
+ id: 'queued-node',
+ position: { x: 2, y: 3 },
+ data: { type: BlockEnum.Code, title: 'Queued' },
+ })
+ setCanvas({ nodes: [queuedNode], edges: [], transform: [20, 30, 1.2] })
act(() => {
- second = secondHook.current.doSyncWorkflowDraft()
+ second = secondHook.doSyncWorkflowDraft()
})
expect(mockSyncDraftWorkflow).toHaveBeenCalledOnce()
// Changes made after enqueueing must not replace the captured graph.
- mockGetNodes.mockReturnValue([])
- reactFlowState.transform = [0, 0, 1]
+ setCanvas({ nodes: [], transform: [0, 0, 1] })
await act(async () => {
firstSave.resolve({ hash: 'hash-after-first', updated_at: 123 })
await Promise.all([first, second])
@@ -224,29 +216,47 @@ describe('snippet/use-nodes-sync-draft', () => {
expect(mockSyncDraftWorkflow).toHaveBeenNthCalledWith(2, {
params: { snippet_id: 'snippet-1' },
body: {
- graph: { nodes: [queuedNode], edges: [], viewport: { x: 20, y: 30, zoom: 1.2 } },
+ graph: {
+ nodes: [
+ expect.objectContaining({
+ id: 'queued-node',
+ data: { type: BlockEnum.Code, title: 'Queued', desc: '' },
+ }),
+ ],
+ edges: [],
+ viewport: { x: 20, y: 30, zoom: 1.2 },
+ },
input_fields: [createInputField('topic')],
hash: 'hash-after-first',
},
})
- expect(workflowStoreState.syncWorkflowDraftHash).toBe('next-hash')
+ expect(store.getState().syncWorkflowDraftHash).toBe('next-hash')
})
it('should send input_fields together with graph on page close', () => {
- const { result } = renderHook(() => useNodesSyncDraft('snippet-1'))
+ const { result } = renderSnippetDraftSync()
act(() => {
result.current.syncWorkflowDraftWhenPageClose()
})
expect(mockPostWithKeepalive).toHaveBeenCalledWith('/api/snippets/snippet-1/workflows/draft', {
- graph: {
- nodes: [{ id: 'node-1', position: { x: 0, y: 0 }, data: { title: 'Start' } }],
- edges: [{ id: 'edge-1', source: 'node-1', target: 'node-2', data: { stable: true } }],
- viewport: { x: 12, y: 24, zoom: 1.5 },
- },
+ graph: savedGraph,
input_fields: [createInputField('topic')],
hash: 'draft-hash',
})
})
+
+ it('does not persist the draft while the canvas is read-only', async () => {
+ const { result, store } = renderSnippetDraftSync()
+ act(() => store.setState({ canvasReadOnly: true }))
+
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft()
+ result.current.syncWorkflowDraftWhenPageClose()
+ })
+
+ expect(mockSyncDraftWorkflow).not.toHaveBeenCalled()
+ expect(mockPostWithKeepalive).not.toHaveBeenCalled()
+ })
})
diff --git a/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts b/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts
index 436dcc97290..3eedfac3463 100644
--- a/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts
+++ b/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts
@@ -1,123 +1,331 @@
+import type { FetchWorkflowDraftResponse } from '@/types/workflow'
import { act } from '@testing-library/react'
+import { useNodes } from 'reactflow'
+import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
import {
baseRunningData,
- renderWorkflowHook as renderHook,
+ renderWorkflowCanvasHook,
} from '@/app/components/workflow/__tests__/workflow-test-env'
-import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { BlockEnum, WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { createDeferred } from '@/test/deferred'
import { useSnippetRun } from '../use-snippet-run'
-const mocks = vi.hoisted(() => {
- return {
- reactFlowStoreState: {
- getNodes: vi.fn(() => []),
- setNodes: vi.fn(),
- edges: [],
- },
- mockGetViewport: vi.fn(() => ({ x: 0, y: 0, zoom: 1 })),
- mockDoSyncWorkflowDraft: vi.fn(),
- mockHandleUpdateWorkflowCanvas: vi.fn(),
- mockFetchInspectVars: vi.fn(),
- mockInvalidateAllLastRun: vi.fn(),
- mockInvalidateRunHistory: vi.fn(),
- mockSsePost: vi.fn(),
- mockStopWorkflowRun: vi.fn(),
- runEventHandlers: {
- handleWorkflowStarted: vi.fn(),
- handleWorkflowFinished: vi.fn(),
- handleWorkflowFailed: vi.fn(),
- handleWorkflowNodeStarted: vi.fn(),
- handleWorkflowNodeFinished: vi.fn(),
- handleWorkflowNodeIterationStarted: vi.fn(),
- handleWorkflowNodeIterationNext: vi.fn(),
- handleWorkflowNodeIterationFinished: vi.fn(),
- handleWorkflowNodeLoopStarted: vi.fn(),
- handleWorkflowNodeLoopNext: vi.fn(),
- handleWorkflowNodeLoopFinished: vi.fn(),
- handleWorkflowNodeRetry: vi.fn(),
- handleWorkflowAgentLog: vi.fn(),
- handleWorkflowTextChunk: vi.fn(),
- handleWorkflowTextReplace: vi.fn(),
- },
- }
-})
-
-vi.mock('reactflow', async (importOriginal) => ({
- ...(await importOriginal<typeof import('reactflow')>()),
- useStoreApi: () => ({
- getState: () => mocks.reactFlowStoreState,
- }),
- useReactFlow: () => ({
- getViewport: mocks.mockGetViewport,
- }),
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({
- useSetWorkflowVarsWithValue: () => ({
- fetchInspectVars: mocks.mockFetchInspectVars,
- }),
+// Draft persistence, canvas replacement and run-event reducers all have their own suites.
+const mockDoSyncWorkflowDraft = vi.fn()
+vi.mock('../use-nodes-sync-draft', () => ({
+ useNodesSyncDraft: () => ({ doSyncWorkflowDraft: mockDoSyncWorkflowDraft }),
}))
+const mockHandleUpdateWorkflowCanvas = vi.fn()
vi.mock('@/app/components/workflow/hooks/use-workflow-update', () => ({
- useWorkflowUpdate: () => ({
- handleUpdateWorkflowCanvas: mocks.mockHandleUpdateWorkflowCanvas,
- }),
+ useWorkflowUpdate: () => ({ handleUpdateWorkflowCanvas: mockHandleUpdateWorkflowCanvas }),
}))
+const runEvents = vi.hoisted(() => ({
+ handleWorkflowStarted: vi.fn(),
+ handleWorkflowFinished: vi.fn(),
+ handleWorkflowFailed: vi.fn(),
+ handleWorkflowNodeStarted: vi.fn(),
+ handleWorkflowNodeFinished: vi.fn(),
+ handleWorkflowNodeIterationStarted: vi.fn(),
+ handleWorkflowNodeIterationNext: vi.fn(),
+ handleWorkflowNodeIterationFinished: vi.fn(),
+ handleWorkflowNodeLoopStarted: vi.fn(),
+ handleWorkflowNodeLoopNext: vi.fn(),
+ handleWorkflowNodeLoopFinished: vi.fn(),
+ handleWorkflowNodeRetry: vi.fn(),
+ handleWorkflowAgentLog: vi.fn(),
+ handleWorkflowTextChunk: vi.fn(),
+ handleWorkflowTextReplace: vi.fn(),
+}))
vi.mock('@/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event', () => ({
- useWorkflowRunEvent: () => mocks.runEventHandlers,
+ useWorkflowRunEvent: () => runEvents,
}))
-vi.mock('@/service/base', () => ({
- ssePost: mocks.mockSsePost,
+const mockFetchInspectVars = vi.fn()
+vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({
+ useSetWorkflowVarsWithValue: () => ({ fetchInspectVars: mockFetchInspectVars }),
}))
-vi.mock('@/service/use-workflow', () => ({
- useInvalidateAllLastRun: () => mocks.mockInvalidateAllLastRun,
- useInvalidateWorkflowRunHistory: () => mocks.mockInvalidateRunHistory,
+const mockSsePost = vi.fn()
+vi.mock('@/service/base', () => ({
+ ssePost: (...args: unknown[]) => mockSsePost(...args),
}))
+const mockStopWorkflowRun = vi.fn()
vi.mock('@/service/workflow', () => ({
- stopWorkflowRun: mocks.mockStopWorkflowRun,
+ stopWorkflowRun: (url: string) => mockStopWorkflowRun(url),
}))
-vi.mock('../use-nodes-sync-draft', () => ({
- useNodesSyncDraft: () => ({
- doSyncWorkflowDraft: mocks.mockDoSyncWorkflowDraft,
- }),
+const mockInvalidAllLastRun = vi.fn()
+const mockInvalidateRunHistory = vi.fn()
+vi.mock('@/service/use-workflow', () => ({
+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,
+ useInvalidateWorkflowRunHistory: () => mockInvalidateRunHistory,
}))
+type SnippetRun = ReturnType<typeof useSnippetRun>
+type RunOptions = NonNullable<Parameters<SnippetRun['handleRun']>[1]>
+type RunPayload = Parameters<SnippetRun['handleRun']>[0]
+
+const RUN_PAYLOAD = { inputs: { query: 'test' } } as RunPayload
+
+const renderSnippetRun = (initialStoreState: Record<string, unknown> = {}) =>
+ renderWorkflowCanvasHook(() => ({ run: useSnippetRun(), nodes: useNodes() }), {
+ resource: { kind: 'snippet', snippetId: 'snippet-1' },
+ nodes: [
+ createNode({
+ id: 'start',
+ selected: true,
+ data: {
+ type: BlockEnum.Start,
+ selected: true,
+ _runningStatus: WorkflowRunningStatus.Succeeded,
+ },
+ }),
+ createNode({ id: 'llm', data: { type: BlockEnum.LLM } }),
+ ],
+ edges: [createEdge({ id: 'start-llm', source: 'start', target: 'llm' })],
+ initialStoreState,
+ })
+
+const startRun = async (run: SnippetRun, callback?: RunOptions) => {
+ await act(async () => {
+ await run.handleRun(RUN_PAYLOAD, callback)
+ })
+ return mockSsePost.mock.calls.at(-1)![2] as Required<RunOptions>
+}
+
describe('useSnippetRun', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockDoSyncWorkflowDraft.mockResolvedValue(undefined)
+ const container = document.createElement('div')
+ container.id = 'workflow-container'
+ Object.defineProperty(container, 'clientWidth', { value: 1000 })
+ Object.defineProperty(container, 'clientHeight', { value: 800 })
+ document.body.appendChild(container)
+ })
+
+ afterEach(() => {
+ document.getElementById('workflow-container')?.remove()
+ })
+
+ describe('draft backup', () => {
+ it('snapshots the current canvas once without environment variables', () => {
+ const { result, store } = renderSnippetRun()
+
+ act(() => result.current.run.handleBackupDraft())
+ const firstBackup = store.getState().backupDraft
+ act(() => result.current.run.handleBackupDraft())
+
+ expect(firstBackup).toMatchObject({
+ nodes: [expect.objectContaining({ id: 'start' }), expect.objectContaining({ id: 'llm' })],
+ edges: [expect.objectContaining({ id: 'start-llm' })],
+ environmentVariables: [],
+ })
+ expect(store.getState().backupDraft).toBe(firstBackup)
+ expect(mockDoSyncWorkflowDraft).toHaveBeenCalledOnce()
+ })
+
+ it('restores the backup canvas and discards the backup', () => {
+ const backupDraft = {
+ nodes: [createNode({ id: 'backup-node' })],
+ edges: [],
+ viewport: { x: 100, y: 100, zoom: 1.5 },
+ environmentVariables: [],
+ }
+ const { result, store } = renderSnippetRun({ backupDraft })
+
+ act(() => result.current.run.handleLoadBackupDraft())
+
+ expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledExactlyOnceWith({
+ nodes: backupDraft.nodes,
+ edges: [],
+ viewport: backupDraft.viewport,
+ })
+ expect(store.getState().backupDraft).toBeUndefined()
+ })
+
+ it('leaves the canvas alone when there is no backup to restore', () => {
+ const { result } = renderSnippetRun()
+
+ act(() => result.current.run.handleLoadBackupDraft())
+
+ expect(mockHandleUpdateWorkflowCanvas).not.toHaveBeenCalled()
+ })
})
- it('stops a snippet workflow with the provided task id', () => {
- const { result, store } = renderHook(() => useSnippetRun(), {
- resource: { kind: 'snippet', snippetId: 'snippet-1' },
- initialStoreState: { workflowRunningData: baseRunningData({ task_id: 'task-from-store' }) },
+ it('loads a published snippet graph unselected', () => {
+ const { result } = renderSnippetRun()
+
+ act(() =>
+ result.current.run.handleRestoreFromPublishedWorkflow({
+ graph: {
+ nodes: [createNode({ id: 'pub-node', selected: true, data: { selected: true } })],
+ edges: [],
+ viewport: { x: 50, y: 50, zoom: 1 },
+ },
+ } as unknown as FetchWorkflowDraftResponse),
+ )
+
+ expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledExactlyOnceWith({
+ nodes: [
+ expect.objectContaining({
+ id: 'pub-node',
+ selected: false,
+ data: expect.objectContaining({ selected: false }),
+ }),
+ ],
+ edges: [],
+ viewport: { x: 50, y: 50, zoom: 1 },
})
+ })
+
+ describe('running', () => {
+ it('resets canvas run state, saves the draft, then streams the snippet run', async () => {
+ const pending = createDeferred<void>()
+ mockDoSyncWorkflowDraft.mockReturnValue(pending.promise)
+ const { result, store } = renderSnippetRun({ historyWorkflowData: { id: 'old-run' } })
+
+ let running!: Promise<void>
+ act(() => {
+ running = result.current.run.handleRun(RUN_PAYLOAD)
+ })
- act(() => {
- result.current.handleStopRun('task-1')
+ expect(result.current.nodes.find((node) => node.id === 'start')?.data).toMatchObject({
+ selected: false,
+ _runningStatus: undefined,
+ })
+ expect(mockSsePost).not.toHaveBeenCalled()
+
+ await act(async () => {
+ pending.resolve()
+ await running
+ })
+
+ expect(store.getState()).toMatchObject({
+ historyWorkflowData: undefined,
+ workflowRunningData: { result: { status: WorkflowRunningStatus.Running }, tracing: [] },
+ })
+ expect(mockSsePost).toHaveBeenCalledExactlyOnceWith(
+ '/snippets/snippet-1/workflows/draft/run',
+ { body: RUN_PAYLOAD },
+ expect.any(Object),
+ )
})
- expect(mocks.mockStopWorkflowRun).toHaveBeenCalledWith(
- '/snippets/snippet-1/workflow-runs/tasks/task-1/stop',
+ it.each([
+ ['onWorkflowStarted', 'handleWorkflowStarted'],
+ ['onWorkflowFinished', 'handleWorkflowFinished'],
+ ['onError', 'handleWorkflowFailed'],
+ ['onNodeStarted', 'handleWorkflowNodeStarted'],
+ ['onNodeFinished', 'handleWorkflowNodeFinished'],
+ ['onIterationStart', 'handleWorkflowNodeIterationStarted'],
+ ['onIterationNext', 'handleWorkflowNodeIterationNext'],
+ ['onIterationFinish', 'handleWorkflowNodeIterationFinished'],
+ ['onLoopStart', 'handleWorkflowNodeLoopStarted'],
+ ['onLoopNext', 'handleWorkflowNodeLoopNext'],
+ ['onLoopFinish', 'handleWorkflowNodeLoopFinished'],
+ ['onNodeRetry', 'handleWorkflowNodeRetry'],
+ ['onAgentLog', 'handleWorkflowAgentLog'],
+ ] as const)(
+ 'applies %s to the canvas and forwards it to the caller',
+ async (event, handler) => {
+ const callerCallback = vi.fn()
+ const { result } = renderSnippetRun()
+ const stream = await startRun(result.current.run, { [event]: callerCallback })
+ const payload = { event }
+
+ act(() => (stream[event] as (params: unknown) => void)(payload))
+
+ expect(runEvents[handler]).toHaveBeenCalledOnce()
+ expect(runEvents[handler].mock.calls[0]![0]).toBe(event === 'onError' ? undefined : payload)
+ expect(callerCallback).toHaveBeenCalledExactlyOnceWith(payload)
+ },
)
- expect(store.getState().workflowRunningData?.result.status).toBe(WorkflowRunningStatus.Stopped)
+
+ it.each([
+ ['onTextChunk', 'handleWorkflowTextChunk'],
+ ['onTextReplace', 'handleWorkflowTextReplace'],
+ ] as const)('applies %s to the run output', async (event, handler) => {
+ const { result } = renderSnippetRun()
+ const stream = await startRun(result.current.run)
+
+ act(() => (stream[event] as (params: unknown) => void)({ text: 'chunk' }))
+
+ expect(runEvents[handler]).toHaveBeenCalledExactlyOnceWith({ text: 'chunk' })
+ })
+
+ it('positions started nodes against the workflow container size', async () => {
+ const { result } = renderSnippetRun()
+ const stream = await startRun(result.current.run)
+
+ act(() => stream.onNodeStarted({ node_id: 'llm' } as never))
+
+ expect(runEvents.handleWorkflowNodeStarted).toHaveBeenCalledWith(
+ { node_id: 'llm' },
+ { clientWidth: 1000, clientHeight: 800 },
+ )
+ })
+
+ it('refreshes run history on lifecycle events and inspect data when the run finishes', async () => {
+ const { result } = renderSnippetRun()
+ const stream = await startRun(result.current.run)
+
+ act(() => stream.onWorkflowStarted({} as never))
+ expect(mockInvalidateRunHistory).toHaveBeenLastCalledWith('/snippets/snippet-1/workflow-runs')
+ expect(mockFetchInspectVars).not.toHaveBeenCalled()
+
+ act(() => stream.onWorkflowFinished({} as never))
+ expect(mockFetchInspectVars).toHaveBeenCalledExactlyOnceWith({})
+ expect(mockInvalidAllLastRun).toHaveBeenCalledOnce()
+
+ act(() => stream.onError({} as never))
+ expect(mockInvalidateRunHistory).toHaveBeenCalledTimes(3)
+ })
})
- it('does not fall back to the workflow running task id when stop is called without one', () => {
- const { result, store } = renderHook(() => useSnippetRun(), {
- resource: { kind: 'snippet', snippetId: 'snippet-1' },
- initialStoreState: { workflowRunningData: baseRunningData({ task_id: 'task-from-store' }) },
+ describe('stopping', () => {
+ it('stops the server task, aborts the open stream and marks the run stopped', async () => {
+ const { result, store } = renderSnippetRun()
+ const stream = await startRun(result.current.run)
+ const controller = new AbortController()
+ stream.getAbortController(controller)
+
+ act(() => result.current.run.handleStopRun('task-1'))
+
+ expect(mockStopWorkflowRun).toHaveBeenCalledExactlyOnceWith(
+ '/snippets/snippet-1/workflow-runs/tasks/task-1/stop',
+ )
+ expect(controller.signal.aborted).toBe(true)
+ expect(store.getState().workflowRunningData?.result.status).toBe(
+ WorkflowRunningStatus.Stopped,
+ )
})
- act(() => {
- result.current.handleStopRun('')
+ it('does not fall back to the stored task id when stop is called without one', () => {
+ const { result, store } = renderSnippetRun({
+ workflowRunningData: baseRunningData({ task_id: 'task-from-store' }),
+ })
+
+ act(() => result.current.run.handleStopRun(''))
+
+ expect(mockStopWorkflowRun).not.toHaveBeenCalled()
+ expect(store.getState().workflowRunningData?.result.status).toBe(
+ WorkflowRunningStatus.Stopped,
+ )
})
- expect(mocks.mockStopWorkflowRun).not.toHaveBeenCalled()
- expect(store.getState().workflowRunningData?.result.status).toBe(WorkflowRunningStatus.Stopped)
+ it('aborts the previous stream when a new run starts', async () => {
+ const { result } = renderSnippetRun()
+ const firstStream = await startRun(result.current.run)
+ const firstController = new AbortController()
+ firstStream.getAbortController(firstController)
+
+ await startRun(result.current.run)
+
+ expect(firstController.signal.aborted).toBe(true)
+ })
})
})
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
index 929af7f581f..ba303aa51df 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -1,85 +1,32 @@
import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'
-import type { WorkflowSliceShape } from '@/app/components/workflow/store/workflow/workflow-slice'
+import type { Features } from '@/app/components/base/features/types'
+import type { Shape } from '@/app/components/workflow/store/workflow'
+import type { Edge, Node } from '@/app/components/workflow/types'
import type { EnvironmentVariablePatch } from '@/service/workflow'
-import { noop } from '@tanstack/react-query'
import { act } from '@testing-library/react'
+import { createElement } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { renderEditorHook as renderHookWithConsoleQuery } from '@/app/components/workflow/editor-resource/__tests__/render'
+import { FeaturesContext } from '@/app/components/base/features/context'
+import { createFeaturesStore } from '@/app/components/base/features/store'
+import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
import { BlockEnum } from '@/app/components/workflow/types'
import { markAppDeletionFailed, markAppDeletionStarted } from '@/service/app-deletion'
-import { consoleQuery } from '@/service/console'
import { createHttpError } from '@/service/http-error'
-import { createConsoleQueryClient } from '@/test/console/query-data'
+import { createConsoleQueryWrapper, seedAppDetail } from '@/test/console/query-data'
import { createAppDetailFixture } from '@/test/fixtures/app'
import { useNodesSyncDraft } from '../use-nodes-sync-draft'
-const mockGetNodes = vi.fn()
const mockPostWithKeepalive = vi.fn()
-const mockSetSyncWorkflowDraftHash = vi.fn()
-const mockSetDraftUpdatedAt = vi.fn()
-const mockGetNodesReadOnly = vi.fn()
const mockCollaborationIsConnected = vi.fn()
const mockCollaborationGetIsLeader = vi.fn()
const mockCollaborationRequestWorkflowSync = vi.fn()
const mockCollaborationCanPersistLocalGraph = vi.fn()
const mockCollaborationCanFlushGraphOnPageClose = vi.fn()
const mockCollaborationCanUseLocalDraftFallback = vi.fn()
-const mockSetShowConfirm = vi.fn<(confirmation: WorkflowSliceShape['showConfirm']) => void>()
-let isCollaborationEnabled = false
-let appMode: AppMode | undefined
-
-let reactFlowState: {
- getNodes: typeof mockGetNodes
- edges: Array<Record<string, unknown>>
- transform: [number, number, number]
-}
-
-let workflowStoreState: {
- appId: string
- isWorkflowDataLoaded: boolean
- syncWorkflowDraftHash: string | null
- conversationVariables: Array<Record<string, unknown>>
- setSyncWorkflowDraftHash: typeof mockSetSyncWorkflowDraftHash
- setDraftUpdatedAt: typeof mockSetDraftUpdatedAt
- showConfirm: WorkflowSliceShape['showConfirm']
- setShowConfirm: typeof mockSetShowConfirm
-}
-
-let featuresState: {
- features: {
- opening: { enabled: boolean; opening_statement: string; suggested_questions: string[] }
- suggested: Record<string, unknown>
- text2speech: Record<string, unknown>
- speech2text: Record<string, unknown>
- citation: Record<string, unknown>
- moderation: Record<string, unknown>
- file: Record<string, unknown>
- }
-}
-
-vi.mock('reactflow', async (importOriginal) => ({
- ...(await importOriginal<typeof import('reactflow')>()),
- useStoreApi: () => ({ getState: () => reactFlowState }),
-}))
-
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (selector: (state: typeof workflowStoreState) => unknown) =>
- selector(workflowStoreState),
- useWorkflowStore: () => ({
- getState: () => workflowStoreState,
- }),
-}))
-
-vi.mock('@/app/components/base/features/hooks', () => ({
- useFeaturesStore: () => ({
- getState: () => featuresState,
- }),
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({
- useNodesReadOnly: () => ({ getNodesReadOnly: mockGetNodesReadOnly }),
-}))
+// The realtime collaboration session is an external connection boundary.
vi.mock('@/app/components/workflow/collaboration/core/collaboration-manager', () => ({
collaborationManager: {
isConnected: (...args: unknown[]) => mockCollaborationIsConnected(...args),
@@ -133,1100 +80,922 @@ vi.mock('../use-workflow-refresh-draft', () => ({
useWorkflowRefreshDraft: () => ({ handleRefreshWorkflowDraft: mockHandleRefreshWorkflowDraft }),
}))
-const renderUseNodesSyncDraft = () => {
- const queryClient = createConsoleQueryClient()
- const appId = workflowStoreState.appId
- const appQueryKey = consoleQuery.apps.byAppId.get.queryKey({
- input: { params: { app_id: appId } },
+type SyncDraftCanvas = {
+ nodes?: Node[]
+ edges?: Edge[]
+ transform?: [number, number, number]
+ appMode?: AppMode
+ isCollaborationEnabled?: boolean
+ features?: Features
+ initialStoreState?: Partial<Shape>
+}
+
+const startNode = createNode({
+ id: 'n1',
+ data: { type: BlockEnum.Start, title: 'Start' },
+})
+const savedStartNode = expect.objectContaining({
+ id: 'n1',
+ position: { x: 0, y: 0 },
+ data: { type: BlockEnum.Start, title: 'Start', desc: '' },
+})
+const draftRequest = (params: unknown) => ({ url: '/apps/app-1/workflows/draft', params })
+
+const renderSyncDraft = <R>(
+ hook: () => R,
+ {
+ nodes = [startNode],
+ edges = [],
+ transform,
+ appMode = 'workflow',
+ isCollaborationEnabled = false,
+ features,
+ initialStoreState,
+ }: SyncDraftCanvas = {},
+) => {
+ const featuresStore = createFeaturesStore(features ? { features } : undefined)
+ const { queryClient } = createConsoleQueryWrapper({
+ systemFeatures: { enable_collaboration_mode: isCollaborationEnabled },
})
- if (appMode)
- queryClient.setQueryData(appQueryKey, createAppDetailFixture({ id: appId, mode: appMode }))
- else
- void queryClient
- .query({
- queryKey: appQueryKey,
- queryFn: () => new Promise<ReturnType<typeof createAppDetailFixture>>(() => {}),
- })
- .catch(noop)
+ seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: appMode }))
- return renderHookWithConsoleQuery(() => useNodesSyncDraft(), {
+ return renderWorkflowCanvasHook(hook, {
queryClient,
- systemFeatures: { enable_collaboration_mode: isCollaborationEnabled },
+ resource: {
+ kind: 'app',
+ appId: 'app-1',
+ mode: appMode === 'advanced-chat' ? 'advanced-chat' : 'workflow',
+ },
+ nodes,
+ edges,
+ transform,
+ initialStoreState: {
+ isWorkflowDataLoaded: true,
+ syncWorkflowDraftHash: 'hash-123',
+ ...initialStoreState,
+ },
+ wrapper: ({ children }) =>
+ createElement(FeaturesContext.Provider, { value: featuresStore }, children),
})
}
+const renderUseNodesSyncDraft = (canvas?: SyncDraftCanvas) =>
+ renderSyncDraft(() => useNodesSyncDraft(), canvas)
+
+const startEmptySave = (
+ result: { current: ReturnType<typeof useNodesSyncDraft> },
+ ...args: Parameters<ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']>
+) => {
+ let syncPromise!: ReturnType<ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']>
+ act(() => {
+ syncPromise = result.current.doSyncWorkflowDraft(...args)
+ })
+ return syncPromise
+}
+
+const draftNotSyncError = () =>
+ createHttpError(new Response(null, { status: 409 }), {
+ code: 'draft_workflow_not_sync',
+ message: 'Workflow not synced.',
+ status: 409,
+ })
+
+const useCollaborationSession = ({
+ connected,
+ leader,
+ canPersistLocalGraph = true,
+ canFlushGraphOnPageClose = true,
+ canUseLocalDraftFallback = false,
+}: {
+ connected: boolean
+ leader: boolean
+ canPersistLocalGraph?: boolean
+ canFlushGraphOnPageClose?: boolean
+ canUseLocalDraftFallback?: boolean
+}) => {
+ mockCollaborationIsConnected.mockReturnValue(connected)
+ mockCollaborationGetIsLeader.mockReturnValue(leader)
+ mockCollaborationCanPersistLocalGraph.mockReturnValue(canPersistLocalGraph)
+ mockCollaborationCanFlushGraphOnPageClose.mockReturnValue(canFlushGraphOnPageClose)
+ mockCollaborationCanUseLocalDraftFallback.mockReturnValue(canUseLocalDraftFallback)
+}
+
describe('useNodesSyncDraft', () => {
beforeEach(() => {
vi.resetAllMocks()
- mockSetShowConfirm.mockImplementation((confirmation) => {
- workflowStoreState.showConfirm = confirmation
- })
- reactFlowState = {
- getNodes: mockGetNodes,
- edges: [],
- transform: [0, 0, 1],
- }
- workflowStoreState = {
- appId: 'app-1',
- isWorkflowDataLoaded: true,
- syncWorkflowDraftHash: 'hash-123',
- conversationVariables: [],
- setSyncWorkflowDraftHash: mockSetSyncWorkflowDraftHash,
- setDraftUpdatedAt: mockSetDraftUpdatedAt,
- showConfirm: undefined,
- setShowConfirm: mockSetShowConfirm,
- }
- featuresState = {
- features: {
- opening: { enabled: false, opening_statement: '', suggested_questions: [] },
- suggested: {},
- text2speech: {},
- speech2text: {},
- citation: {},
- moderation: {},
- file: {},
- },
- }
- mockGetNodesReadOnly.mockReturnValue(false)
- mockGetNodes.mockReturnValue([
- { id: 'n1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } },
- ])
mockSyncWorkflowDraft.mockResolvedValue({ hash: 'new', updated_at: 1 })
- mockCollaborationIsConnected.mockReturnValue(false)
- mockCollaborationGetIsLeader.mockReturnValue(true)
- mockCollaborationCanPersistLocalGraph.mockReturnValue(true)
- mockCollaborationCanFlushGraphOnPageClose.mockReturnValue(true)
- mockCollaborationCanUseLocalDraftFallback.mockReturnValue(false)
- mockCollaborationRequestWorkflowSync.mockResolvedValue({
- hash: 'remote-hash',
- updatedAt: 2,
- })
- isCollaborationEnabled = false
- appMode = 'workflow'
- })
+ useCollaborationSession({ connected: false, leader: true })
+ mockCollaborationRequestWorkflowSync.mockResolvedValue({ hash: 'remote-hash', updatedAt: 2 })
+ })
+
+ describe('payload', () => {
+ it.each(['draft sync', 'page close'] as const)(
+ 'removes Workflow LLM memory from %s without changing the canvas nodes',
+ async (savePath) => {
+ const memory = {
+ enabled: false,
+ role_prefix: { user: '', assistant: '' },
+ window: { enabled: false, size: 10 },
+ }
+ const containers = [
+ createNode({ id: 'iteration', data: { type: BlockEnum.Iteration, title: 'Iteration' } }),
+ createNode({ id: 'loop', data: { type: BlockEnum.Loop, title: 'Loop' } }),
+ ]
+ const canvasNodes = [
+ createNode({ id: 'llm', data: { type: BlockEnum.LLM, title: 'LLM', memory } }),
+ createNode({
+ id: 'iteration-llm',
+ parentId: 'iteration',
+ data: { type: BlockEnum.LLM, title: 'Iteration LLM', memory },
+ }),
+ createNode({
+ id: 'loop-llm',
+ parentId: 'loop',
+ data: { type: BlockEnum.LLM, title: 'Loop LLM', memory },
+ }),
+ ]
+ const { result } = renderUseNodesSyncDraft({ nodes: [...containers, ...canvasNodes] })
+
+ await act(async () => {
+ if (savePath === 'draft sync') await result.current.doSyncWorkflowDraft()
+ else result.current.syncWorkflowDraftWhenPageClose()
+ })
+
+ const expectedPayload = expect.objectContaining({
+ graph: expect.objectContaining({
+ nodes: expect.arrayContaining(
+ canvasNodes.map((node) =>
+ expect.objectContaining({
+ id: node.id,
+ data: { type: BlockEnum.LLM, title: node.data.title, desc: '' },
+ }),
+ ),
+ ),
+ }),
+ })
+ if (savePath === 'draft sync')
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(draftRequest(expectedPayload))
+ else
+ expect(mockPostWithKeepalive).toHaveBeenCalledWith(
+ '/api/apps/app-1/workflows/draft',
+ expectedPayload,
+ )
+ canvasNodes.forEach((node) => expect(node.data).toHaveProperty('memory', memory))
+ },
+ )
- it.each(['draft sync', 'page close'] as const)(
- 'should remove Workflow LLM memory from %s without changing the canvas nodes',
- async (savePath) => {
+ it('preserves LLM memory in chatflow apps', async () => {
const memory = {
- enabled: false,
- role_prefix: { user: '', assistant: '' },
- window: { enabled: false, size: 10 },
+ role_prefix: { user: 'Human', assistant: 'Assistant' },
+ window: { enabled: true, size: 10 },
}
- const canvasNodes = [
- {
- id: 'llm',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.LLM, title: 'LLM', memory },
- },
- {
- id: 'iteration-llm',
- parentId: 'iteration',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.LLM, title: 'Iteration LLM', memory },
- },
- {
- id: 'loop-llm',
- parentId: 'loop',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.LLM, title: 'Loop LLM', memory },
- },
- ]
- mockGetNodes.mockReturnValue(canvasNodes)
- const { result } = renderUseNodesSyncDraft()
+ const { result } = renderUseNodesSyncDraft({
+ appMode: 'advanced-chat',
+ nodes: [createNode({ id: 'llm', data: { type: BlockEnum.LLM, title: 'LLM', memory } })],
+ })
await act(async () => {
- if (savePath === 'draft sync') await result.current.doSyncWorkflowDraft()
- else result.current.syncWorkflowDraftWhenPageClose()
+ await result.current.doSyncWorkflowDraft()
+ result.current.syncWorkflowDraftWhenPageClose()
})
const expectedPayload = expect.objectContaining({
graph: expect.objectContaining({
- nodes: canvasNodes.map((node) => ({
- ...node,
- data: { type: BlockEnum.LLM, title: node.data.title },
- })),
+ nodes: [
+ expect.objectContaining({
+ data: { type: BlockEnum.LLM, title: 'LLM', desc: '', memory },
+ }),
+ ],
}),
})
- if (savePath === 'draft sync')
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith({
- url: '/apps/app-1/workflows/draft',
- params: expectedPayload,
- })
- else
- expect(mockPostWithKeepalive).toHaveBeenCalledWith(
- '/api/apps/app-1/workflows/draft',
- expectedPayload,
- )
- canvasNodes.forEach((node) => expect(node.data.memory).toEqual(memory))
- },
- )
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(draftRequest(expectedPayload))
+ expect(mockPostWithKeepalive).toHaveBeenCalledWith(
+ '/api/apps/app-1/workflows/draft',
+ expectedPayload,
+ )
+ })
- it.each(['advanced-chat'] as const)(
- 'should preserve LLM memory when app mode is %s',
- async (mode) => {
- appMode = mode
- const canvasNodes = [
+ it('strips temporary entities and private data, uses the latest hash, and stores the result', async () => {
+ const conversationVariables = [
{
- id: 'llm',
- position: { x: 0, y: 0 },
- data: {
- type: BlockEnum.LLM,
- memory: {
- role_prefix: { user: 'Human', assistant: 'Assistant' },
- window: { enabled: true, size: 10 },
- },
- },
+ id: 'conversation-1',
+ name: 'topic',
+ value_type: ChatVarType.String,
+ value: 'conversation',
+ description: '',
},
]
- mockGetNodes.mockReturnValue(canvasNodes)
- const { result } = renderUseNodesSyncDraft()
+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }
+ const { result, store } = renderUseNodesSyncDraft({
+ nodes: [
+ createNode({
+ id: 'n1',
+ data: { type: BlockEnum.Start, title: 'Start', _tempField: 'drop' },
+ }),
+ createNode({
+ id: 'start-placeholder',
+ position: { x: 1, y: 1 },
+ data: { type: BlockEnum.StartPlaceholder },
+ }),
+ createNode({
+ id: 'temp-node',
+ position: { x: 2, y: 2 },
+ data: { type: BlockEnum.Answer, _isTempNode: true },
+ }),
+ ],
+ edges: [
+ createEdge({
+ id: 'edge-1',
+ source: 'n1',
+ target: 'n2',
+ data: { _isTemp: false, _hovering: true, isInIteration: false },
+ }),
+ createEdge({ id: 'placeholder-edge', source: 'start-placeholder', target: 'n1' }),
+ createEdge({ id: 'temp-edge', source: 'n2', target: 'n3', data: { _isTemp: true } }),
+ ],
+ transform: [10, 20, 1.5],
+ features: {
+ opening: { enabled: true, opening_statement: 'Hello', suggested_questions: ['Q1'] },
+ suggested: { enabled: true },
+ text2speech: { enabled: true },
+ speech2text: { enabled: true },
+ citation: { enabled: true },
+ moderation: { enabled: false },
+ file: { enabled: true },
+ },
+ initialStoreState: { syncWorkflowDraftHash: 'latest-hash', conversationVariables },
+ })
await act(async () => {
- await result.current.doSyncWorkflowDraft()
- result.current.syncWorkflowDraftWhenPageClose()
+ await result.current.doSyncWorkflowDraft(false, callbacks)
})
- const expectedPayload = expect.objectContaining({
- graph: expect.objectContaining({ nodes: canvasNodes }),
- })
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith({
- url: '/apps/app-1/workflows/draft',
- params: expectedPayload,
- })
- expect(mockPostWithKeepalive).toHaveBeenCalledWith(
- '/api/apps/app-1/workflows/draft',
- expectedPayload,
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
+ draftRequest({
+ graph: {
+ nodes: [savedStartNode],
+ edges: [
+ createEdge({
+ id: 'edge-1',
+ source: 'n1',
+ target: 'n2',
+ data: { isInIteration: false },
+ }),
+ ],
+ viewport: { x: 10, y: 20, zoom: 1.5 },
+ },
+ features: {
+ opening_statement: 'Hello',
+ suggested_questions: ['Q1'],
+ suggested_questions_after_answer: { enabled: true },
+ text_to_speech: { enabled: true },
+ speech_to_text: { enabled: true },
+ retriever_resource: { enabled: true },
+ sensitive_word_avoidance: { enabled: false },
+ file_upload: { enabled: true },
+ },
+ conversation_variables: conversationVariables,
+ hash: 'latest-hash',
+ }),
)
- },
- )
-
- it('should wait for confirmation before saving an empty graph with force', async () => {
- mockGetNodes.mockReturnValue([])
- const callbacks = {
- onSuccess: vi.fn(),
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
- const { result } = renderUseNodesSyncDraft()
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
-
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft(false, callbacks)
+ expect(store.getState()).toMatchObject({
+ showConfirm: undefined,
+ syncWorkflowDraftHash: 'new',
+ draftUpdatedAt: 1000,
+ })
+ expect(callbacks.onSuccess).toHaveBeenCalledOnce()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- expect(workflowStoreState.showConfirm).toEqual(
- expect.objectContaining({
- title: 'workflow.common.clearCanvasConfirmTitle',
- desc: 'workflow.common.clearCanvasConfirmDescription',
- }),
- )
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(callbacks.onSettled).not.toHaveBeenCalled()
+ it('includes an environment variable patch in a full draft sync', async () => {
+ const environmentVariablePatch: EnvironmentVariablePatch = {
+ environmentVariables: [
+ {
+ id: 'env-1',
+ name: 'for_summarize',
+ description: '',
+ value_type: 'llm',
+ value: { provider: 'langgenius/openai/openai', name: 'gpt-4.1', mode: 'chat' },
+ },
+ ],
+ deletedEnvironmentVariableIds: ['env-2'],
+ }
+ const { result } = renderUseNodesSyncDraft()
- await act(async () => {
- workflowStoreState.showConfirm?.onConfirm()
- await expect(syncPromise).resolves.toEqual({ hash: 'new', updatedAt: 1 })
- })
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, undefined, { environmentVariablePatch })
+ })
- expect(workflowStoreState.showConfirm).toBeUndefined()
- expect(mockSyncWorkflowDraft).toHaveBeenCalledOnce()
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- graph: expect.objectContaining({ nodes: [], edges: [] }),
- force: true,
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ environment_variable_patch: {
+ environment_variables: environmentVariablePatch.environmentVariables,
+ deleted_environment_variable_ids:
+ environmentVariablePatch.deletedEnvironmentVariableIds,
+ },
+ }),
}),
- }),
- )
- expect(callbacks.onSuccess).toHaveBeenCalledOnce()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
-
- it('should settle a canceled empty save without posting or reporting an error', async () => {
- mockGetNodes.mockReturnValue([])
- const callbacks = {
- onSuccess: vi.fn(),
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
- const { result } = renderUseNodesSyncDraft()
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
-
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft(false, callbacks)
- })
-
- expect(workflowStoreState.showConfirm?.onCancel).toBeDefined()
- await act(async () => {
- workflowStoreState.showConfirm?.onCancel?.()
- await expect(syncPromise).resolves.toBeNull()
+ )
})
- expect(workflowStoreState.showConfirm).toBeUndefined()
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(callbacks.onSuccess).not.toHaveBeenCalled()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
+ it('keeps pending inline Agent v2 nodes in draft without incomplete bindings', async () => {
+ const agentData = {
+ type: BlockEnum.Agent,
+ title: 'Agent',
+ desc: '',
+ agent_node_kind: 'dify_agent',
+ version: '2',
+ agent_binding: { binding_type: 'inline_agent' },
+ selected: true,
+ }
+ const { result } = renderUseNodesSyncDraft({
+ nodes: [
+ startNode,
+ createNode({
+ id: 'pending-agent',
+ position: { x: 1, y: 1 },
+ data: { ...agentData, _isTempNode: true, _openInlineAgentPanel: true },
+ }),
+ createNode({
+ id: 'temp-node',
+ position: { x: 2, y: 2 },
+ data: { type: BlockEnum.Answer, _isTempNode: true },
+ }),
+ ],
+ edges: [
+ createEdge({
+ id: 'edge-1',
+ source: 'n1',
+ target: 'pending-agent',
+ data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Agent },
+ }),
+ createEdge({ id: 'temp-edge', source: 'temp-node', target: 'pending-agent' }),
+ ],
+ })
- it('should confirm a graph that is empty after filtering placeholders and temporary entities', async () => {
- mockGetNodes.mockReturnValue([
- {
- id: 'start-placeholder',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.StartPlaceholder },
- },
- {
- id: 'temp-node',
- position: { x: 1, y: 1 },
- data: { type: BlockEnum.Answer, _isTempNode: true },
- },
- ])
- reactFlowState.edges = [
- {
- id: 'temp-edge',
- source: 'start-placeholder',
- target: 'temp-node',
- data: { _isTemp: true },
- },
- ]
- const { result } = renderUseNodesSyncDraft()
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false)
+ })
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft()
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ graph: expect.objectContaining({
+ nodes: [
+ savedStartNode,
+ expect.objectContaining({ id: 'pending-agent', data: agentData }),
+ ],
+ edges: [
+ createEdge({
+ id: 'edge-1',
+ source: 'n1',
+ target: 'pending-agent',
+ data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Agent },
+ }),
+ ],
+ }),
+ }),
+ }),
+ )
})
- expect(workflowStoreState.showConfirm).toBeDefined()
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
-
- await act(async () => {
- workflowStoreState.showConfirm?.onConfirm()
- await syncPromise
- })
+ it('captures the graph before a queued sync runs after the canvas is torn down', async () => {
+ const draftEdge = createEdge({ id: 'edge-1', source: 'n1', target: 'n2' })
+ const { result, setCanvas } = renderUseNodesSyncDraft({
+ edges: [draftEdge],
+ transform: [10, 20, 1.5],
+ })
+ let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- graph: expect.objectContaining({ nodes: [], edges: [] }),
- force: true,
- }),
- }),
- )
- })
+ act(() => {
+ syncPromise = result.current.doSyncWorkflowDraft(false)
+ // ReactFlow clears its store immediately after the page starts unmounting.
+ setCanvas({ nodes: [], edges: [], transform: [0, 0, 1] })
+ })
- it('should skip an empty page-close save without opening confirmation', () => {
- mockGetNodes.mockReturnValue([])
- const { result } = renderUseNodesSyncDraft()
+ await act(async () => {
+ await syncPromise
+ })
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ graph: {
+ nodes: [savedStartNode],
+ edges: [draftEdge],
+ viewport: { x: 10, y: 20, zoom: 1.5 },
+ },
+ }),
+ }),
+ )
})
-
- expect(mockPostWithKeepalive).not.toHaveBeenCalled()
- expect(mockSetShowConfirm).not.toHaveBeenCalled()
})
- it('should keep one confirmation when another hook instance tries to save the empty graph', async () => {
- mockGetNodes.mockReturnValue([])
- const first = renderUseNodesSyncDraft()
- const second = renderUseNodesSyncDraft()
- const secondCallbacks = { onError: vi.fn(), onSettled: vi.fn() }
- let firstSave!: ReturnType<typeof first.result.current.doSyncWorkflowDraft>
+ describe('empty graph confirmation', () => {
+ it('waits for confirmation before force-saving an empty graph', async () => {
+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }
+ const { result, store } = renderUseNodesSyncDraft({ nodes: [] })
+ const syncPromise = startEmptySave(result, false, callbacks)
- act(() => {
- firstSave = first.result.current.doSyncWorkflowDraft()
- })
- const confirmation = workflowStoreState.showConfirm
-
- await act(async () => {
- await expect(
- second.result.current.doSyncWorkflowDraft(false, secondCallbacks),
- ).resolves.toBeNull()
- })
+ expect(store.getState().showConfirm).toEqual(
+ expect.objectContaining({
+ title: 'workflow.common.clearCanvasConfirmTitle',
+ desc: 'workflow.common.clearCanvasConfirmDescription',
+ }),
+ )
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).not.toHaveBeenCalled()
- expect(mockSetShowConfirm).toHaveBeenCalledOnce()
- expect(workflowStoreState.showConfirm).toBe(confirmation)
- expect(secondCallbacks.onError).not.toHaveBeenCalled()
- expect(secondCallbacks.onSettled).toHaveBeenCalledOnce()
+ await act(async () => {
+ store.getState().showConfirm?.onConfirm()
+ await expect(syncPromise).resolves.toEqual({ hash: 'new', updatedAt: 1 })
+ })
- await act(async () => {
- confirmation?.onConfirm()
- await firstSave
+ expect(store.getState().showConfirm).toBeUndefined()
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ graph: expect.objectContaining({ nodes: [], edges: [] }),
+ force: true,
+ }),
+ }),
+ )
+ expect(callbacks.onSuccess).toHaveBeenCalledOnce()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- expect(mockSyncWorkflowDraft).toHaveBeenCalledOnce()
- })
+ it('settles a canceled empty save without posting or reporting an error', async () => {
+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }
+ const { result, store } = renderUseNodesSyncDraft({ nodes: [] })
+ const syncPromise = startEmptySave(result, false, callbacks)
- it('should not save the old empty graph when a node is added before confirmation', async () => {
- mockGetNodes.mockReturnValue([])
- const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
- const { result } = renderUseNodesSyncDraft()
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
+ await act(async () => {
+ store.getState().showConfirm?.onCancel?.()
+ await expect(syncPromise).resolves.toBeNull()
+ })
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft(false, callbacks)
+ expect(store.getState().showConfirm).toBeUndefined()
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(callbacks.onSuccess).not.toHaveBeenCalled()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- mockGetNodes.mockReturnValue([
- { id: 'new-node', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } },
- ])
+ it('treats a graph with only placeholders and temporary entities as empty', async () => {
+ const { result, store } = renderUseNodesSyncDraft({
+ nodes: [
+ createNode({ id: 'start-placeholder', data: { type: BlockEnum.StartPlaceholder } }),
+ createNode({
+ id: 'temp-node',
+ position: { x: 1, y: 1 },
+ data: { type: BlockEnum.Answer, _isTempNode: true },
+ }),
+ ],
+ edges: [
+ createEdge({
+ id: 'temp-edge',
+ source: 'start-placeholder',
+ target: 'temp-node',
+ data: { _isTemp: true },
+ }),
+ ],
+ })
+ const syncPromise = startEmptySave(result)
- await act(async () => {
- workflowStoreState.showConfirm?.onConfirm()
- await expect(syncPromise).resolves.toBeNull()
- })
+ expect(store.getState().showConfirm).toBeDefined()
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
+ await act(async () => {
+ store.getState().showConfirm?.onConfirm()
+ await syncPromise
+ })
- it('should recheck a confirmed empty graph after an earlier save finishes', async () => {
- let finishEarlierSave!: (response: { hash: string; updated_at: number }) => void
- let notifySaveStarted!: () => void
- const saveStarted = new Promise<void>((resolve) => {
- notifySaveStarted = resolve
- })
- mockSyncWorkflowDraft.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- finishEarlierSave = resolve
- notifySaveStarted()
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ graph: expect.objectContaining({ nodes: [], edges: [] }),
+ force: true,
+ }),
}),
- )
- const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
- const { result } = renderUseNodesSyncDraft()
- let earlierSave!: ReturnType<typeof result.current.doSyncWorkflowDraft>
- let emptySave!: ReturnType<typeof result.current.doSyncWorkflowDraft>
-
- act(() => {
- earlierSave = result.current.doSyncWorkflowDraft()
- })
- await saveStarted
- mockGetNodes.mockReturnValue([])
-
- act(() => {
- emptySave = result.current.doSyncWorkflowDraft(false, callbacks)
+ )
})
- await act(async () => {
- workflowStoreState.showConfirm?.onConfirm()
- })
+ it('skips an empty page-close save without opening confirmation', () => {
+ const { result, store } = renderUseNodesSyncDraft({ nodes: [] })
- mockGetNodes.mockReturnValue([
- { id: 'restored-node', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } },
- ])
+ act(() => {
+ result.current.syncWorkflowDraftWhenPageClose()
+ })
- await act(async () => {
- finishEarlierSave({ hash: 'earlier-save', updated_at: 1 })
- await earlierSave
- await expect(emptySave).resolves.toBeNull()
+ expect(mockPostWithKeepalive).not.toHaveBeenCalled()
+ expect(store.getState().showConfirm).toBeUndefined()
})
- expect(mockSyncWorkflowDraft).toHaveBeenCalledOnce()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
-
- it('should cancel a pending empty save when its owning hook unmounts', async () => {
- mockGetNodes.mockReturnValue([])
- const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
- const { result, unmount } = renderUseNodesSyncDraft()
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
+ it('keeps one confirmation when another hook instance tries to save the empty graph', async () => {
+ const { result, store } = renderSyncDraft(
+ () => [useNodesSyncDraft(), useNodesSyncDraft()] as const,
+ { nodes: [] },
+ )
+ const [first, second] = result.current
+ const secondCallbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ let firstSave!: ReturnType<typeof first.doSyncWorkflowDraft>
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft(false, callbacks)
- })
- expect(workflowStoreState.showConfirm).toBeDefined()
+ act(() => {
+ firstSave = first.doSyncWorkflowDraft()
+ })
+ const confirmation = store.getState().showConfirm
- unmount()
- await expect(syncPromise).resolves.toBeNull()
+ await act(async () => {
+ await expect(second.doSyncWorkflowDraft(false, secondCallbacks)).resolves.toBeNull()
+ })
- expect(workflowStoreState.showConfirm).toBeUndefined()
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
+ expect(store.getState().showConfirm).toBe(confirmation)
+ expect(secondCallbacks.onError).not.toHaveBeenCalled()
+ expect(secondCallbacks.onSettled).toHaveBeenCalledOnce()
- it('should confirm and save an empty collaborative follower graph in the initiating tab', async () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(true)
- mockCollaborationGetIsLeader.mockReturnValue(false)
- mockGetNodes.mockReturnValue([])
- const { result } = renderUseNodesSyncDraft()
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
+ await act(async () => {
+ confirmation?.onConfirm()
+ await firstSave
+ })
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft()
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledOnce()
})
- expect(workflowStoreState.showConfirm).toBeDefined()
- expect(mockCollaborationRequestWorkflowSync).not.toHaveBeenCalled()
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ it('does not save the old empty graph when a node is added before confirmation', async () => {
+ const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ const { result, setCanvas, store } = renderUseNodesSyncDraft({ nodes: [] })
+ const syncPromise = startEmptySave(result, false, callbacks)
- await act(async () => {
- workflowStoreState.showConfirm?.onConfirm()
- await syncPromise
- })
+ setCanvas({ nodes: [createNode({ id: 'new-node', data: { type: BlockEnum.Start } })] })
- expect(mockCollaborationRequestWorkflowSync).not.toHaveBeenCalled()
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({ force: true, _is_collaborative: true }),
- }),
- )
- })
-
- it('should call handleRefreshWorkflowDraft(true) — not updating canvas — on draft_workflow_not_sync', async () => {
- const error = createHttpError(new Response(null, { status: 409 }), {
- code: 'draft_workflow_not_sync',
- message: 'Workflow not synced.',
- status: 409,
- })
- mockSyncWorkflowDraft.mockRejectedValue(error)
+ await act(async () => {
+ store.getState().showConfirm?.onConfirm()
+ await expect(syncPromise).resolves.toBeNull()
+ })
- const { result } = renderUseNodesSyncDraft()
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false)
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledWith(true)
- })
-
- it('should NOT refresh when notRefreshWhenSyncError=true', async () => {
- const error = createHttpError(new Response(null, { status: 409 }), {
- code: 'draft_workflow_not_sync',
- message: 'Workflow not synced.',
- status: 409,
- })
- mockSyncWorkflowDraft.mockRejectedValue(error)
+ it('rechecks a confirmed empty graph after an earlier save finishes', async () => {
+ let finishEarlierSave!: (response: { hash: string; updated_at: number }) => void
+ let notifySaveStarted!: () => void
+ const saveStarted = new Promise<void>((resolve) => {
+ notifySaveStarted = resolve
+ })
+ mockSyncWorkflowDraft.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishEarlierSave = resolve
+ notifySaveStarted()
+ }),
+ )
+ const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ const { result, setCanvas, store } = renderUseNodesSyncDraft()
+ const earlierSave = startEmptySave(result)
+ await saveStarted
+ setCanvas({ nodes: [] })
+ const emptySave = startEmptySave(result, false, callbacks)
- const { result } = renderUseNodesSyncDraft()
- await act(async () => {
- await result.current.doSyncWorkflowDraft(true)
- })
+ await act(async () => {
+ store.getState().showConfirm?.onConfirm()
+ })
- expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
- })
+ setCanvas({ nodes: [createNode({ id: 'restored-node', data: { type: BlockEnum.Start } })] })
- it('should NOT refresh for a different error code', async () => {
- const error = createHttpError(new Response(null, { status: 400 }), { code: 'other_error' })
- mockSyncWorkflowDraft.mockRejectedValue(error)
+ await act(async () => {
+ finishEarlierSave({ hash: 'earlier-save', updated_at: 1 })
+ await earlierSave
+ await expect(emptySave).resolves.toBeNull()
+ })
- const { result } = renderUseNodesSyncDraft()
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false)
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledOnce()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
- })
-
- it('should ignore non-JSON sync errors without throwing an unhandled rejection', async () => {
- const error = createHttpError(new Response(null, { status: 502 }))
- const callbacks = {
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
- mockSyncWorkflowDraft.mockRejectedValue(error)
-
- const { result } = renderUseNodesSyncDraft()
- await act(async () => {
- await expect(result.current.doSyncWorkflowDraft(false, callbacks)).resolves.toBeNull()
- })
+ it('cancels a pending empty save when its owning hook unmounts', async () => {
+ const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ const { result, store, unmount } = renderUseNodesSyncDraft({ nodes: [] })
+ const syncPromise = startEmptySave(result, false, callbacks)
+ expect(store.getState().showConfirm).toBeDefined()
- expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
- expect(callbacks.onError).toHaveBeenCalledOnce()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
+ unmount()
+ await expect(syncPromise).resolves.toBeNull()
- it('should treat unavailable workflow data as a skipped sync instead of an error', async () => {
- workflowStoreState = {
- ...workflowStoreState,
- isWorkflowDataLoaded: false,
- }
- const callbacks = {
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
-
- const { result } = renderUseNodesSyncDraft()
- await act(async () => {
- await expect(result.current.doSyncWorkflowDraft(false, callbacks)).resolves.toBeNull()
+ expect(store.getState().showConfirm).toBeUndefined()
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
+ it('confirms and saves an empty collaborative follower graph in the initiating tab', async () => {
+ useCollaborationSession({ connected: true, leader: false })
+ const { result, store } = renderUseNodesSyncDraft({
+ nodes: [],
+ isCollaborationEnabled: true,
+ })
+ const syncPromise = startEmptySave(result)
- it('should capture the graph before a queued sync runs after the canvas is torn down', async () => {
- const draftNode = {
- id: 'n1',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.Start, label: 'Start' },
- }
- const draftEdge = {
- id: 'edge-1',
- source: 'n1',
- target: 'n2',
- data: { stable: 'keep' },
- }
- mockGetNodes.mockReturnValue([draftNode])
- reactFlowState = {
- ...reactFlowState,
- edges: [draftEdge],
- transform: [10, 20, 1.5],
- }
-
- const { result } = renderUseNodesSyncDraft()
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
-
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft(false)
-
- // Simulate ReactFlow clearing its store immediately after the page starts unmounting.
- mockGetNodes.mockReturnValue([])
- reactFlowState = {
- ...reactFlowState,
- edges: [],
- transform: [0, 0, 1],
- }
- })
+ expect(store.getState().showConfirm).toBeDefined()
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- await act(async () => {
- await syncPromise
- })
+ await act(async () => {
+ store.getState().showConfirm?.onConfirm()
+ await syncPromise
+ })
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- graph: {
- nodes: [draftNode],
- edges: [draftEdge],
- viewport: { x: 10, y: 20, zoom: 1.5 },
- },
+ expect(mockCollaborationRequestWorkflowSync).not.toHaveBeenCalled()
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({ force: true, _is_collaborative: true }),
}),
- }),
- )
+ )
+ })
})
- it('should strip temp entities and private data, use the latest hash, and invoke success callbacks', async () => {
- reactFlowState = {
- ...reactFlowState,
- edges: [
- {
- id: 'edge-1',
- source: 'n1',
- target: 'n2',
- data: { _isTemp: false, _private: 'drop', stable: 'keep' },
- },
- {
- id: 'placeholder-edge',
- source: 'start-placeholder',
- target: 'n1',
- data: { stable: 'drop' },
- },
- { id: 'temp-edge', source: 'n2', target: 'n3', data: { _isTemp: true } },
- ],
- transform: [10, 20, 1.5],
- }
- mockGetNodes.mockReturnValue([
+ describe('failures and skipped saves', () => {
+ it.each([
{
- id: 'n1',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.Start, _tempField: 'drop', label: 'Start' },
+ scenario: 'an out-of-date draft',
+ error: draftNotSyncError,
+ notRefresh: false,
+ refreshes: 1,
},
{
- id: 'start-placeholder',
- position: { x: 1, y: 1 },
- data: { type: BlockEnum.StartPlaceholder },
+ scenario: 'an out-of-date draft with refresh disabled',
+ error: draftNotSyncError,
+ notRefresh: true,
+ refreshes: 0,
},
{
- id: 'temp-node',
- position: { x: 2, y: 2 },
- data: { type: BlockEnum.Answer, _isTempNode: true },
+ scenario: 'another API error',
+ error: () => createHttpError(new Response(null, { status: 400 }), { code: 'other_error' }),
+ notRefresh: false,
+ refreshes: 0,
},
- ])
- workflowStoreState = {
- ...workflowStoreState,
- syncWorkflowDraftHash: 'latest-hash',
- conversationVariables: [{ id: 'conversation-1', value: 'conversation' }],
- }
- featuresState = {
- features: {
- opening: { enabled: true, opening_statement: 'Hello', suggested_questions: ['Q1'] },
- suggested: { enabled: true },
- text2speech: { enabled: true },
- speech2text: { enabled: true },
- citation: { enabled: true },
- moderation: { enabled: false },
- file: { enabled: true },
+ {
+ scenario: 'a non-JSON error',
+ error: () => createHttpError(new Response(null, { status: 502 })),
+ notRefresh: false,
+ refreshes: 0,
},
- }
-
- const callbacks = {
- onSuccess: vi.fn(),
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
-
- const { result } = renderUseNodesSyncDraft()
-
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false, callbacks)
- })
+ ])(
+ 'reports $scenario and refreshes $refreshes time(s)',
+ async ({ error, notRefresh, refreshes }) => {
+ mockSyncWorkflowDraft.mockRejectedValue(error())
+ const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ const { result, store } = renderUseNodesSyncDraft()
+
+ await act(async () => {
+ await expect(
+ result.current.doSyncWorkflowDraft(notRefresh, callbacks),
+ ).resolves.toBeNull()
+ })
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith({
- url: '/apps/app-1/workflows/draft',
- params: {
- graph: {
- nodes: [
- { id: 'n1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start, label: 'Start' } },
- ],
- edges: [{ id: 'edge-1', source: 'n1', target: 'n2', data: { stable: 'keep' } }],
- viewport: { x: 10, y: 20, zoom: 1.5 },
- },
- features: {
- opening_statement: 'Hello',
- suggested_questions: ['Q1'],
- suggested_questions_after_answer: { enabled: true },
- text_to_speech: { enabled: true },
- speech_to_text: { enabled: true },
- retriever_resource: { enabled: true },
- sensitive_word_avoidance: { enabled: false },
- file_upload: { enabled: true },
- },
- conversation_variables: [{ id: 'conversation-1', value: 'conversation' }],
- hash: 'latest-hash',
+ expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledTimes(refreshes)
+ if (refreshes) expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledWith(true)
+ expect(callbacks.onError).toHaveBeenCalledOnce()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
+ expect(store.getState().syncWorkflowDraftHash).toBe('hash-123')
},
- })
- expect(mockSetShowConfirm).not.toHaveBeenCalled()
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('new')
- expect(mockSetDraftUpdatedAt).toHaveBeenCalledWith(1)
- expect(callbacks.onSuccess).toHaveBeenCalledOnce()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
-
- it('should include an environment variable patch in a full draft sync', async () => {
- const environmentVariablePatch: EnvironmentVariablePatch = {
- environmentVariables: [
- {
- id: 'env-1',
- name: 'for_summarize',
- description: '',
- value_type: 'llm',
- value: {
- provider: 'langgenius/openai/openai',
- name: 'gpt-4.1',
- mode: 'chat',
- },
- },
- ],
- deletedEnvironmentVariableIds: ['env-2'],
- }
- const { result } = renderUseNodesSyncDraft()
-
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false, undefined, { environmentVariablePatch })
- })
-
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- environment_variable_patch: {
- environment_variables: environmentVariablePatch.environmentVariables,
- deleted_environment_variable_ids:
- environmentVariablePatch.deletedEnvironmentVariableIds,
- },
- }),
- }),
)
- })
- it('should keep pending inline Agent v2 nodes in draft without incomplete bindings', async () => {
- reactFlowState = {
- ...reactFlowState,
- edges: [
- {
- id: 'edge-1',
- source: 'n1',
- target: 'pending-agent',
- data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Agent },
- },
- { id: 'temp-edge', source: 'temp-node', target: 'pending-agent', data: {} },
- ],
- }
- mockGetNodes.mockReturnValue([
- { id: 'n1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } },
- {
- id: 'pending-agent',
- position: { x: 1, y: 1 },
- data: {
- type: BlockEnum.Agent,
- title: 'Agent',
- desc: '',
- agent_node_kind: 'dify_agent',
- version: '2',
- agent_binding: {
- binding_type: 'inline_agent',
- },
- _isTempNode: true,
- _openInlineAgentPanel: true,
- selected: true,
- },
- },
+ it.each([
{
- id: 'temp-node',
- position: { x: 2, y: 2 },
- data: { type: BlockEnum.Answer, _isTempNode: true },
+ scenario: 'workflow data is not loaded',
+ initialStoreState: { isWorkflowDataLoaded: false },
},
- ])
-
- const { result } = renderUseNodesSyncDraft()
-
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false)
- })
-
- expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- graph: expect.objectContaining({
- nodes: [
- { id: 'n1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } },
- {
- id: 'pending-agent',
- position: { x: 1, y: 1 },
- data: {
- type: BlockEnum.Agent,
- title: 'Agent',
- desc: '',
- agent_node_kind: 'dify_agent',
- version: '2',
- agent_binding: {
- binding_type: 'inline_agent',
- },
- selected: true,
- },
- },
- ],
- edges: [
- {
- id: 'edge-1',
- source: 'n1',
- target: 'pending-agent',
- data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Agent },
- },
- ],
- }),
- }),
- }),
- )
- })
-
- it('should post workflow draft with keepalive when the page closes', () => {
- reactFlowState = {
- ...reactFlowState,
- transform: [1, 2, 3],
- }
- workflowStoreState = {
- ...workflowStoreState,
- conversationVariables: [{ id: 'conversation-1' }],
- }
-
- const { result } = renderUseNodesSyncDraft()
-
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
- })
-
- expect(mockPostWithKeepalive).toHaveBeenCalledWith(
- '/api/apps/app-1/workflows/draft',
- expect.objectContaining({
- graph: expect.objectContaining({
- viewport: { x: 1, y: 2, zoom: 3 },
- }),
- hash: 'hash-123',
- }),
- )
- })
-
- it('should skip draft persistence without reporting an error while the app is being deleted', async () => {
- const callbacks = {
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
- markAppDeletionStarted('app-1')
-
- try {
- const { result } = renderUseNodesSyncDraft()
+ { scenario: 'the canvas is read-only', initialStoreState: { canvasReadOnly: true } },
+ ])('skips persistence without an error when $scenario', async ({ initialStoreState }) => {
+ const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ const { result } = renderUseNodesSyncDraft({ initialStoreState })
await act(async () => {
- await result.current.doSyncWorkflowDraft(false, callbacks)
+ await expect(result.current.doSyncWorkflowDraft(false, callbacks)).resolves.toBeNull()
result.current.syncWorkflowDraftWhenPageClose()
})
expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
expect(mockPostWithKeepalive).not.toHaveBeenCalled()
expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- } finally {
- markAppDeletionFailed('app-1')
- }
- })
-
- it('should not report an in-flight draft failure after app deletion starts', async () => {
- let rejectSync!: (reason?: unknown) => void
- let resolveStarted!: () => void
- const started = new Promise<void>((resolve) => {
- resolveStarted = resolve
- })
- mockSyncWorkflowDraft.mockImplementationOnce(
- () =>
- new Promise((_, reject) => {
- rejectSync = reject
- resolveStarted()
- }),
- )
- const callbacks = {
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
- const { result } = renderUseNodesSyncDraft()
- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
-
- act(() => {
- syncPromise = result.current.doSyncWorkflowDraft(false, callbacks)
})
- await started
- markAppDeletionStarted('app-1')
-
- try {
- await act(async () => {
- rejectSync(new Error('App not found'))
- await syncPromise
- })
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- } finally {
- markAppDeletionFailed('app-1')
- }
- })
+ it('skips draft persistence without reporting an error while the app is being deleted', async () => {
+ const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ markAppDeletionStarted('app-1')
- it('should not post the local start placeholder when the page closes', () => {
- reactFlowState = {
- ...reactFlowState,
- edges: [{ id: 'placeholder-edge', source: 'start-placeholder', target: 'n1', data: {} }],
- }
- mockGetNodes.mockReturnValue([
- {
- id: 'start-placeholder',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.StartPlaceholder },
- },
- { id: 'n1', position: { x: 1, y: 1 }, data: { type: BlockEnum.Start } },
- ])
+ try {
+ const { result } = renderUseNodesSyncDraft()
- const { result } = renderUseNodesSyncDraft()
-
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
- })
-
- expect(mockPostWithKeepalive).toHaveBeenCalledWith(
- '/api/apps/app-1/workflows/draft',
- expect.objectContaining({
- graph: expect.objectContaining({
- nodes: [{ id: 'n1', position: { x: 1, y: 1 }, data: { type: BlockEnum.Start } }],
- edges: [],
- }),
- }),
- )
- })
-
- it('should wait for the leader save result when current user is collaboration follower', async () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(true)
- mockCollaborationGetIsLeader.mockReturnValue(false)
- const callbacks = {
- onSuccess: vi.fn(),
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
-
- const { result } = renderUseNodesSyncDraft()
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, callbacks)
+ result.current.syncWorkflowDraftWhenPageClose()
+ })
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false, callbacks)
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(mockPostWithKeepalive).not.toHaveBeenCalled()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
+ } finally {
+ markAppDeletionFailed('app-1')
+ }
})
- expect(mockCollaborationRequestWorkflowSync).toHaveBeenCalled()
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('remote-hash')
- expect(mockSetDraftUpdatedAt).toHaveBeenCalledWith(2)
- expect(callbacks.onSuccess).toHaveBeenCalledOnce()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
+ it('does not report an in-flight draft failure after app deletion starts', async () => {
+ let rejectSync!: (reason?: unknown) => void
+ let resolveStarted!: () => void
+ const started = new Promise<void>((resolve) => {
+ resolveStarted = resolve
+ })
+ mockSyncWorkflowDraft.mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ rejectSync = reject
+ resolveStarted()
+ }),
+ )
+ const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ const { result } = renderUseNodesSyncDraft()
+ const syncPromise = startEmptySave(result, false, callbacks)
+ await started
+ markAppDeletionStarted('app-1')
+
+ try {
+ await act(async () => {
+ rejectSync(new Error('App not found'))
+ await syncPromise
+ })
- it('should report a failed leader save to the follower caller', async () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(true)
- mockCollaborationGetIsLeader.mockReturnValue(false)
- mockCollaborationRequestWorkflowSync.mockRejectedValue(new Error('sync timeout'))
- const callbacks = {
- onSuccess: vi.fn(),
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
-
- const { result } = renderUseNodesSyncDraft()
-
- let syncResult: unknown
- await act(async () => {
- syncResult = await result.current.doSyncWorkflowDraft(false, callbacks)
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
+ } finally {
+ markAppDeletionFailed('app-1')
+ }
})
-
- expect(syncResult).toBeNull()
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(callbacks.onSuccess).not.toHaveBeenCalled()
- expect(callbacks.onError).toHaveBeenCalledOnce()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- it('should force a directed sync request to save locally even before leader status arrives', async () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(true)
- mockCollaborationGetIsLeader.mockReturnValue(false)
+ describe('page close', () => {
+ it('posts the draft with keepalive and leaves out the local start placeholder', () => {
+ const { result } = renderUseNodesSyncDraft({
+ nodes: [
+ createNode({ id: 'start-placeholder', data: { type: BlockEnum.StartPlaceholder } }),
+ startNode,
+ ],
+ edges: [createEdge({ id: 'placeholder-edge', source: 'start-placeholder', target: 'n1' })],
+ transform: [1, 2, 3],
+ })
- const { result } = renderUseNodesSyncDraft()
+ act(() => {
+ result.current.syncWorkflowDraftWhenPageClose()
+ })
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false, undefined, { forceLocal: true })
+ expect(mockPostWithKeepalive).toHaveBeenCalledWith(
+ '/api/apps/app-1/workflows/draft',
+ expect.objectContaining({
+ graph: { nodes: [savedStartNode], edges: [], viewport: { x: 1, y: 2, zoom: 3 } },
+ hash: 'hash-123',
+ }),
+ )
})
- expect(mockCollaborationRequestWorkflowSync).not.toHaveBeenCalled()
- expect(mockSyncWorkflowDraft).toHaveBeenCalled()
- })
-
- it('should not queue a directed local save behind the requester waiting for its ack', async () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(true)
- mockCollaborationGetIsLeader.mockReturnValue(false)
- let resolveRemoteSync: ((result: { hash: string; updatedAt: number }) => void) | undefined
- mockCollaborationRequestWorkflowSync.mockReturnValueOnce(
- new Promise((resolve) => {
- resolveRemoteSync = resolve
- }),
- )
- const { result } = renderUseNodesSyncDraft()
+ it.each([
+ {
+ scenario: 'a follower cannot flush the shared graph',
+ session: { connected: true, leader: false, canFlushGraphOnPageClose: false },
+ posts: 0,
+ },
+ {
+ scenario: 'the trusted sole leader flushes while hidden',
+ session: { connected: true, leader: true, canFlushGraphOnPageClose: true },
+ posts: 1,
+ },
+ {
+ // Without a connection there is no leader election; skipping would drop the edits.
+ scenario: 'collaboration never connected',
+ session: {
+ connected: false,
+ leader: false,
+ canFlushGraphOnPageClose: false,
+ canUseLocalDraftFallback: true,
+ },
+ posts: 1,
+ },
+ {
+ scenario: 'an established collaboration disconnected',
+ session: {
+ connected: false,
+ leader: true,
+ canFlushGraphOnPageClose: false,
+ canUseLocalDraftFallback: false,
+ },
+ posts: 0,
+ },
+ ])('posts $posts keepalive save(s) when $scenario', ({ session, posts }) => {
+ useCollaborationSession(session)
+ const { result } = renderUseNodesSyncDraft({ isCollaborationEnabled: true })
- let requesterSync: Promise<unknown> | undefined
- await act(async () => {
- requesterSync = result.current.doSyncWorkflowDraft()
- await Promise.resolve()
- })
+ act(() => {
+ result.current.syncWorkflowDraftWhenPageClose()
+ })
- await act(async () => {
- await result.current.doSyncWorkflowDraft(false, undefined, { forceLocal: true })
+ expect(mockPostWithKeepalive).toHaveBeenCalledTimes(posts)
})
+ })
- expect(mockSyncWorkflowDraft).toHaveBeenCalledTimes(1)
+ describe('collaboration', () => {
+ it('waits for the leader save result when the current user is a follower', async () => {
+ useCollaborationSession({ connected: true, leader: false })
+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }
+ const { result, store } = renderUseNodesSyncDraft({ isCollaborationEnabled: true })
- resolveRemoteSync?.({ hash: 'remote-hash', updatedAt: 2 })
- await act(async () => {
- await requesterSync
- })
- })
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, callbacks)
+ })
- it('should not persist an untrusted collaborative graph', async () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(true)
- mockCollaborationGetIsLeader.mockReturnValue(true)
- mockCollaborationCanPersistLocalGraph.mockReturnValue(false)
- const callbacks = {
- onError: vi.fn(),
- onSettled: vi.fn(),
- }
-
- const { result } = renderUseNodesSyncDraft()
-
- let syncResult: unknown
- await act(async () => {
- syncResult = await result.current.doSyncWorkflowDraft(false, callbacks)
+ expect(mockCollaborationRequestWorkflowSync).toHaveBeenCalled()
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(store.getState()).toMatchObject({
+ syncWorkflowDraftHash: 'remote-hash',
+ draftUpdatedAt: 2000,
+ })
+ expect(callbacks.onSuccess).toHaveBeenCalledOnce()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- expect(syncResult).toBeNull()
- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).toHaveBeenCalledOnce()
- })
-
- it('should skip keepalive sync on page close when current user is collaboration follower', () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(true)
- mockCollaborationGetIsLeader.mockReturnValue(false)
- mockCollaborationCanFlushGraphOnPageClose.mockReturnValue(false)
+ it('reports a failed leader save to the follower caller', async () => {
+ useCollaborationSession({ connected: true, leader: false })
+ mockCollaborationRequestWorkflowSync.mockRejectedValue(new Error('sync timeout'))
+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }
+ const { result } = renderUseNodesSyncDraft({ isCollaborationEnabled: true })
- const { result } = renderUseNodesSyncDraft()
+ await act(async () => {
+ await expect(result.current.doSyncWorkflowDraft(false, callbacks)).resolves.toBeNull()
+ })
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(callbacks.onSuccess).not.toHaveBeenCalled()
+ expect(callbacks.onError).toHaveBeenCalledOnce()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
- expect(mockPostWithKeepalive).not.toHaveBeenCalled()
- })
-
- it('should allow the trusted sole leader to flush with keepalive while hidden', () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(true)
- mockCollaborationGetIsLeader.mockReturnValue(true)
- mockCollaborationCanFlushGraphOnPageClose.mockReturnValue(true)
+ it('saves a directed sync request locally even before leader status arrives', async () => {
+ useCollaborationSession({ connected: true, leader: false })
+ const { result } = renderUseNodesSyncDraft({ isCollaborationEnabled: true })
- const { result } = renderUseNodesSyncDraft()
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, undefined, { forceLocal: true })
+ })
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
+ expect(mockCollaborationRequestWorkflowSync).not.toHaveBeenCalled()
+ expect(mockSyncWorkflowDraft).toHaveBeenCalled()
})
- expect(mockPostWithKeepalive).toHaveBeenCalledTimes(1)
- })
+ it('does not queue a directed local save behind the requester waiting for its ack', async () => {
+ useCollaborationSession({ connected: true, leader: false })
+ let resolveRemoteSync: ((result: { hash: string; updatedAt: number }) => void) | undefined
+ mockCollaborationRequestWorkflowSync.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveRemoteSync = resolve
+ }),
+ )
+ const { result } = renderUseNodesSyncDraft({ isCollaborationEnabled: true })
- it('should still flush with keepalive on page close when collaboration is enabled but never connected', () => {
- // Without a connection there is no leader election, so the collaborative flush guard can never
- // be satisfied. Skipping the save here would silently drop the edits made before leaving.
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(false)
- mockCollaborationGetIsLeader.mockReturnValue(false)
- mockCollaborationCanFlushGraphOnPageClose.mockReturnValue(false)
- mockCollaborationCanUseLocalDraftFallback.mockReturnValue(true)
+ let requesterSync: Promise<unknown> | undefined
+ await act(async () => {
+ requesterSync = result.current.doSyncWorkflowDraft()
+ await Promise.resolve()
+ })
- const { result } = renderUseNodesSyncDraft()
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, undefined, { forceLocal: true })
+ })
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
- })
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledTimes(1)
- expect(mockPostWithKeepalive).toHaveBeenCalledTimes(1)
- })
+ resolveRemoteSync?.({ hash: 'remote-hash', updatedAt: 2 })
+ await act(async () => {
+ await requesterSync
+ })
+ })
- it('should not flush an untrusted graph after an established collaboration disconnects', () => {
- isCollaborationEnabled = true
- mockCollaborationIsConnected.mockReturnValue(false)
- mockCollaborationCanFlushGraphOnPageClose.mockReturnValue(false)
- mockCollaborationCanUseLocalDraftFallback.mockReturnValue(false)
+ it('does not persist an untrusted collaborative graph', async () => {
+ useCollaborationSession({ connected: true, leader: true, canPersistLocalGraph: false })
+ const callbacks = { onError: vi.fn(), onSettled: vi.fn() }
+ const { result } = renderUseNodesSyncDraft({ isCollaborationEnabled: true })
- const { result } = renderUseNodesSyncDraft()
+ await act(async () => {
+ await expect(result.current.doSyncWorkflowDraft(false, callbacks)).resolves.toBeNull()
+ })
- act(() => {
- result.current.syncWorkflowDraftWhenPageClose()
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
})
-
- expect(mockPostWithKeepalive).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
index 3de5f487ac2..f90d3e4cbd3 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
@@ -1,42 +1,35 @@
import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'
import type { UploadConfig } from '@dify/contracts/api/console/files/types.gen'
+import type { Shape } from '@/app/components/workflow/store/workflow'
import { waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { renderEditorHook as renderHookWithConsoleState } from '@/app/components/workflow/editor-resource/__tests__/render'
+import { renderWorkflowHook } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum } from '@/app/components/workflow/types'
import { createHttpError } from '@/service/http-error'
import { createAccountProfileQueryClient } from '@/test/console/account-profile'
-import { createQueryClientWrapper } from '@/test/console/query-client'
import { seedAppDetail } from '@/test/console/query-data'
import { createAppDetailFixture } from '@/test/fixtures/app'
import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'
import { AppACLPermission } from '@/utils/permission'
import { useWorkflowInit } from '../use-workflow-init'
-const mockSetSyncWorkflowDraftHash = vi.fn()
-const mockSetDraftUpdatedAt = vi.fn()
-const mockSetToolPublished = vi.fn()
-const mockSetPublishedAt = vi.fn()
-const mockSetLastPublishedHasUserInput = vi.fn()
-const mockSetFileUploadConfig = vi.fn()
-const mockWorkflowStoreSetState = vi.fn()
-const mockWorkflowStoreGetState = vi.fn()
const mockFetchNodesDefaultConfigs = vi.fn()
const mockFetchPublishedWorkflow = vi.fn()
const mockSyncWorkflowDraft = vi.fn()
let appDetail: AppDetailWithSite
-const renderHook = <Result>(callback: () => Result) => {
+const renderHook = <Result>(callback: () => Result, initialStoreState?: Partial<Shape>) => {
const queryClient = createAccountProfileQueryClient({ id: 'user-1' })
seedAppDetail(queryClient, appDetail)
- return renderHookWithConsoleState(callback, {
+ return renderWorkflowHook(callback, {
resource: {
kind: 'app',
appId: 'app-1',
mode: appDetail.mode === 'advanced-chat' ? 'advanced-chat' : 'workflow',
},
- wrapper: createQueryClientWrapper(queryClient),
+ queryClient,
+ initialStoreState,
})
}
@@ -45,16 +38,6 @@ let workflowConfigState: {
isLoading: boolean
}
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: <T>(
- selector: (state: { setSyncWorkflowDraftHash: ReturnType<typeof vi.fn> }) => T,
- ): T => selector({ setSyncWorkflowDraftHash: mockSetSyncWorkflowDraftHash }),
- useWorkflowStore: () => ({
- setState: mockWorkflowStoreSetState,
- getState: mockWorkflowStoreGetState,
- }),
-}))
-
vi.mock('@/next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('@/next/navigation')>()),
useParams: () => ({ appId: 'app-1' }),
@@ -142,13 +125,6 @@ describe('useWorkflowInit', () => {
permission_keys: [AppACLPermission.Edit],
})
workflowConfigState = { data: null, isLoading: false }
- mockWorkflowStoreGetState.mockReturnValue({
- setDraftUpdatedAt: mockSetDraftUpdatedAt,
- setToolPublished: mockSetToolPublished,
- setPublishedAt: mockSetPublishedAt,
- setLastPublishedHasUserInput: mockSetLastPublishedHasUserInput,
- setFileUploadConfig: mockSetFileUploadConfig,
- })
mockFetchNodesDefaultConfigs.mockResolvedValue([])
mockFetchPublishedWorkflow.mockResolvedValue({ created_at: 0, graph: { nodes: [], edges: [] } })
mockFetchWorkflowDraft.mockRejectedValueOnce(notExistError())
@@ -182,7 +158,7 @@ describe('useWorkflowInit', () => {
})
mockSyncWorkflowDraft.mockResolvedValue({ hash: 'new-hash', updated_at: 1 })
- const { result } = renderHook(() => useWorkflowInit())
+ const { result, store } = renderHook(() => useWorkflowInit())
await waitFor(() => {
expect(result.current.data?.graph.nodes).toEqual([
@@ -190,14 +166,12 @@ describe('useWorkflowInit', () => {
])
})
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith(
- expect.objectContaining({
- showOnboarding: false,
- shouldAutoOpenStartNodeSelector: false,
- hasSelectedStartNode: false,
- hasShownOnboarding: true,
- }),
- )
+ expect(store.getState()).toMatchObject({
+ showOnboarding: false,
+ shouldAutoOpenStartNodeSelector: false,
+ hasSelectedStartNode: false,
+ hasShownOnboarding: true,
+ })
expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
expect.objectContaining({
params: expect.objectContaining({
@@ -209,8 +183,7 @@ describe('useWorkflowInit', () => {
}),
}),
)
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('new-hash')
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('new-workflow-hash')
+ expect(store.getState().syncWorkflowDraftHash).toBe('new-workflow-hash')
})
it('should keep creating the first backend draft for advanced chat apps', async () => {
@@ -226,7 +199,7 @@ describe('useWorkflowInit', () => {
.mockResolvedValueOnce(draftResponse)
mockSyncWorkflowDraft.mockResolvedValue({ hash: 'new-hash', updated_at: 1 })
- renderHook(() => useWorkflowInit())
+ const { result, store } = renderHook(() => useWorkflowInit())
await waitFor(() =>
expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
@@ -241,14 +214,13 @@ describe('useWorkflowInit', () => {
}),
),
)
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith(
- expect.objectContaining({
- showOnboarding: false,
- shouldAutoOpenStartNodeSelector: false,
- hasShownOnboarding: false,
- }),
- )
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('new-hash')
+ await waitFor(() => expect(result.current.data?.hash).toBe('server-hash'))
+ expect(store.getState()).toMatchObject({
+ showOnboarding: false,
+ shouldAutoOpenStartNodeSelector: false,
+ hasShownOnboarding: false,
+ syncWorkflowDraftHash: 'server-hash',
+ })
})
it('should keep readonly users local when the first workflow draft does not exist', async () => {
@@ -260,7 +232,9 @@ describe('useWorkflowInit', () => {
})
mockFetchWorkflowDraft.mockReset().mockRejectedValueOnce(notExistError())
- const { result } = renderHook(() => useWorkflowInit())
+ const { result, store } = renderHook(() => useWorkflowInit(), {
+ syncWorkflowDraftHash: 'stale-hash',
+ })
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
@@ -270,15 +244,13 @@ describe('useWorkflowInit', () => {
{ id: 'start-placeholder', data: { type: BlockEnum.StartPlaceholder } },
])
expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith(
- expect.objectContaining({
- envSecrets: {},
- environmentVariables: [],
- conversationVariables: [],
- isWorkflowDataLoaded: true,
- }),
- )
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('')
+ expect(store.getState()).toMatchObject({
+ envSecrets: {},
+ environmentVariables: [],
+ conversationVariables: [],
+ isWorkflowDataLoaded: true,
+ syncWorkflowDraftHash: '',
+ })
expect(result.current.data?.graph.viewport).toBeUndefined()
})
@@ -289,7 +261,7 @@ describe('useWorkflowInit', () => {
hash: 'empty-draft-hash',
})
- const { result } = renderHook(() => useWorkflowInit())
+ const { result, store } = renderHook(() => useWorkflowInit())
await waitFor(() => {
expect(result.current.data?.graph.nodes).toEqual([
@@ -298,7 +270,7 @@ describe('useWorkflowInit', () => {
})
expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('empty-draft-hash')
+ expect(store.getState().syncWorkflowDraftHash).toBe('empty-draft-hash')
})
it('should preserve existing draft nodes when restoring the local start placeholder', async () => {
@@ -352,36 +324,28 @@ describe('useWorkflowInit', () => {
},
})
- const { result } = renderHook(() => useWorkflowInit())
+ const { result, store } = renderHook(() => useWorkflowInit())
await waitFor(() => {
expect(result.current.data?.hash).toBe('server-hash')
})
+ await waitFor(() => expect(store.getState().publishedAt).toBe(99_000))
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith(
- expect.objectContaining({
- envSecrets: { 'env-secret': 'top-secret' },
- environmentVariables: [
- { id: 'env-secret', value_type: 'secret', value: '[__HIDDEN__]', name: 'SECRET' },
- { id: 'env-plain', value_type: 'text', value: 'visible', name: 'PLAIN' },
- ],
- conversationVariables: [{ id: 'conversation-1' }],
- isWorkflowDataLoaded: true,
- }),
- )
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
- nodesDefaultConfigs: {
- start: { title: 'Start Config' },
- },
+ expect(store.getState()).toMatchObject({
+ envSecrets: { 'env-secret': 'top-secret' },
+ environmentVariables: [
+ { id: 'env-secret', value_type: 'secret', value: '[__HIDDEN__]', name: 'SECRET' },
+ { id: 'env-plain', value_type: 'text', value: 'visible', name: 'PLAIN' },
+ ],
+ conversationVariables: [{ id: 'conversation-1' }],
+ isWorkflowDataLoaded: true,
+ nodesDefaultConfigs: { start: { title: 'Start Config' } },
+ syncWorkflowDraftHash: 'server-hash',
+ draftUpdatedAt: 9000,
+ toolPublished: true,
+ lastPublishedHasUserInput: true,
+ fileUploadConfig: createFileUploadConfigFixture({ file_size_limit: 20 }),
})
- expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('server-hash')
- expect(mockSetDraftUpdatedAt).toHaveBeenCalledWith(9)
- expect(mockSetToolPublished).toHaveBeenCalledWith(true)
- expect(mockSetPublishedAt).toHaveBeenCalledWith(99)
- expect(mockSetLastPublishedHasUserInput).toHaveBeenCalledWith(true)
- expect(mockSetFileUploadConfig).toHaveBeenCalledWith(
- createFileUploadConfigFixture({ file_size_limit: 20 }),
- )
expect(result.current.fileUploadConfigResponse).toEqual(
createFileUploadConfigFixture({ file_size_limit: 20 }),
)
@@ -400,11 +364,13 @@ describe('useWorkflowInit', () => {
},
})
- renderHook(() => useWorkflowInit())
+ const { store } = renderHook(() => useWorkflowInit())
await waitFor(() => {
- expect(mockSetPublishedAt).toHaveBeenCalledWith(99)
- expect(mockSetLastPublishedHasUserInput).toHaveBeenCalledWith(true)
+ expect(store.getState()).toMatchObject({
+ publishedAt: 99_000,
+ lastPublishedHasUserInput: true,
+ })
})
consoleErrorSpy.mockRestore()
@@ -418,15 +384,13 @@ describe('useWorkflowInit', () => {
])
mockFetchPublishedWorkflow.mockRejectedValue(new Error('published workflow failed'))
- renderHook(() => useWorkflowInit())
+ const { store } = renderHook(() => useWorkflowInit(), { lastPublishedHasUserInput: true })
await waitFor(() => {
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
- nodesDefaultConfigs: {
- start: { title: 'Start Config' },
- },
+ expect(store.getState()).toMatchObject({
+ nodesDefaultConfigs: { start: { title: 'Start Config' } },
+ lastPublishedHasUserInput: false,
})
- expect(mockSetLastPublishedHasUserInput).toHaveBeenCalledWith(false)
})
consoleErrorSpy.mockRestore()
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-start-run.spec.tsx b/web/app/components/workflow-app/hooks/__tests__/use-workflow-start-run.spec.tsx
index 45b4d0ff6f8..22ba28ea358 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-start-run.spec.tsx
+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-start-run.spec.tsx
@@ -1,55 +1,24 @@
import type { ReactNode } from 'react'
+import type { Features } from '@/app/components/base/features/types'
+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'
import type { Shape } from '@/app/components/workflow/store'
+import type { Node } from '@/app/components/workflow/types'
import { act } from '@testing-library/react'
+import { FeaturesContext } from '@/app/components/base/features/context'
+import { createFeaturesStore } from '@/app/components/base/features/store'
+import { createNode } from '@/app/components/workflow/__tests__/fixtures'
import {
baseRunningData,
- createTestWorkflowStore,
+ renderWorkflowCanvasHook,
} from '@/app/components/workflow/__tests__/workflow-test-env'
-import { WorkflowContext } from '@/app/components/workflow/context'
-import { renderEditorHook } from '@/app/components/workflow/editor-resource/__tests__/render'
import { TriggerType } from '@/app/components/workflow/header/test-run-menu'
import { BlockEnum, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { useWorkflowStartRunByCanEdit } from '../use-workflow-start-run'
-const mockGetNodes = vi.fn()
-const mockGetFeaturesState = vi.fn()
-const mockHandleCancelDebugAndPreviewPanel = vi.fn()
+// Draft persistence and the run stream are owned by their own hooks and suites.
const mockHandleRun = vi.fn()
const mockDoSyncWorkflowDraft = vi.fn()
-let workflowStoreState: Partial<Shape>
-let workflowStore: ReturnType<typeof createTestWorkflowStore>
-const renderHook: typeof renderEditorHook = (callback, options = {}) => {
- workflowStore = createTestWorkflowStore(workflowStoreState)
- return renderEditorHook(callback, {
- ...options,
- wrapper: ({ children }: { children: ReactNode }) => (
- <WorkflowContext value={workflowStore}>{children}</WorkflowContext>
- ),
- })
-}
-
-vi.mock('reactflow', async (importOriginal) => ({
- ...(await importOriginal<typeof import('reactflow')>()),
- useStoreApi: () => ({
- getState: () => ({
- getNodes: mockGetNodes,
- }),
- }),
-}))
-
-vi.mock('@/app/components/base/features/hooks', () => ({
- useFeaturesStore: () => ({
- getState: mockGetFeaturesState,
- }),
-}))
-
-vi.mock('@/app/components/workflow/hooks/use-workflow-panel-interactions', () => ({
- useWorkflowInteractions: () => ({
- handleCancelDebugAndPreviewPanel: mockHandleCancelDebugAndPreviewPanel,
- }),
-}))
-
vi.mock('../use-nodes-sync-draft', () => ({
useNodesSyncDraftByCanEdit: () => ({
doSyncWorkflowDraft: mockDoSyncWorkflowDraft,
@@ -62,6 +31,28 @@ vi.mock('../use-workflow-run', () => ({
}),
}))
+let workflowStoreState: Partial<Shape>
+let canvasNodes: Node[]
+let features: Partial<Features>
+let workflowStore: ReturnType<typeof renderWorkflowCanvasHook>['store']
+
+const toNodes = (nodes: { id: string; data: Record<string, unknown> }[]) =>
+ nodes.map(({ id, data }) => createNode({ id, data }))
+
+const renderHook = <R,>(callback: () => R, { resource }: { resource: EditorResource }) => {
+ const featuresStore = createFeaturesStore({ features })
+ const rendered = renderWorkflowCanvasHook(callback, {
+ resource,
+ initialStoreState: workflowStoreState,
+ nodes: canvasNodes,
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <FeaturesContext value={featuresStore}>{children}</FeaturesContext>
+ ),
+ })
+ workflowStore = rendered.store
+ return rendered
+}
+
const createWorkflowStoreState = (overrides: Partial<Shape> = {}): Partial<Shape> => ({
showDebugAndPreviewPanel: false,
showEnvPanel: true,
@@ -74,18 +65,8 @@ describe('useWorkflowStartRunByCanEdit', () => {
beforeEach(() => {
vi.resetAllMocks()
workflowStoreState = createWorkflowStoreState()
- mockGetNodes.mockReturnValue([
- { id: 'inset-s-1', data: { type: BlockEnum.Start, variables: [] } },
- ])
- mockGetFeaturesState.mockReturnValue({
- features: {
- file: {
- image: {
- enabled: false,
- },
- },
- },
- })
+ canvasNodes = toNodes([{ id: 'inset-s-1', data: { type: BlockEnum.Start, variables: [] } }])
+ features = { file: { image: { enabled: false } } }
mockDoSyncWorkflowDraft.mockResolvedValue(undefined)
})
@@ -107,9 +88,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
})
it('should not sync or run when only the start placeholder exists', async () => {
- mockGetNodes.mockReturnValue([
- { id: 'start-placeholder', data: { type: BlockEnum.StartPlaceholder } },
- ])
+ canvasNodes = toNodes([{ id: 'start-placeholder', data: { type: BlockEnum.StartPlaceholder } }])
const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
@@ -126,7 +105,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
})
it('should open the input panel instead of running immediately when start inputs are required', async () => {
- mockGetNodes.mockReturnValue([
+ canvasNodes = toNodes([
{ id: 'inset-s-1', data: { type: BlockEnum.Start, variables: [{ name: 'query' }] } },
])
@@ -145,15 +124,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
})
it('should open the input panel when image upload is enabled even without start variables', async () => {
- mockGetFeaturesState.mockReturnValue({
- features: {
- file: {
- image: {
- enabled: true,
- },
- },
- },
- })
+ features = { file: { image: { enabled: true } } }
const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
@@ -182,7 +153,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
await result.current.handleWorkflowStartRunInWorkflow()
})
- expect(mockHandleCancelDebugAndPreviewPanel).toHaveBeenCalled()
+ expect(workflowStore.getState().showDebugAndPreviewPanel).toBe(false)
expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()
expect(mockHandleRun).not.toHaveBeenCalled()
})
@@ -206,7 +177,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
})
it('should configure schedule trigger runs and execute the workflow with schedule options', async () => {
- mockGetNodes.mockReturnValue([{ id: 'schedule-1', data: { type: BlockEnum.TriggerSchedule } }])
+ canvasNodes = toNodes([{ id: 'schedule-1', data: { type: BlockEnum.TriggerSchedule } }])
const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
@@ -235,7 +206,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
workflowStoreState = createWorkflowStoreState({
showDebugAndPreviewPanel: true,
})
- mockGetNodes.mockReturnValue([{ id: 'schedule-1', data: { type: BlockEnum.TriggerSchedule } }])
+ canvasNodes = toNodes([{ id: 'schedule-1', data: { type: BlockEnum.TriggerSchedule } }])
const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
@@ -245,7 +216,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
await result.current.handleWorkflowTriggerScheduleRunInWorkflow('schedule-1')
})
- expect(mockHandleCancelDebugAndPreviewPanel).toHaveBeenCalled()
+ expect(workflowStore.getState().showDebugAndPreviewPanel).toBe(false)
expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()
expect(mockHandleRun).not.toHaveBeenCalled()
})
@@ -297,7 +268,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
},
])('does not run when the $title trigger node cannot be found', async ({ invoke }) => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
- mockGetNodes.mockReturnValue([{ id: 'other-node', data: { type: BlockEnum.Start } }])
+ canvasNodes = toNodes([{ id: 'other-node', data: { type: BlockEnum.Start } }])
const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
@@ -335,7 +306,7 @@ describe('useWorkflowStartRunByCanEdit', () => {
])(
'should configure $title trigger runs with node-specific options',
async ({ nodeId, nodeType, invoke, expectedParams, expectedOptions }) => {
- mockGetNodes.mockReturnValue([{ id: nodeId, data: { type: nodeType } }])
+ canvasNodes = toNodes([{ id: nodeId, data: { type: nodeType } }])
const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
diff --git a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
index 0e62070212f..33a6139f52e 100644
--- a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
+++ b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
@@ -149,7 +149,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
...(isCollaborationEnabled ? { _is_collaborative: true } : {}),
},
}
- }, [store, featuresStore, workflowStore, isCollaborationEnabled, appMode])
+ }, [store, featuresStore, workflowStore, isCollaborationEnabled, appMode, appId])
const syncWorkflowDraftWhenPageClose = useCallback(() => {
if (getNodesReadOnly()) return
@@ -249,6 +249,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
getPostParams,
handleRefreshWorkflowDraft,
isCollaborationEnabled,
+ appId,
],
)
@@ -349,6 +350,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
isCollaborationEnabled,
t,
workflowStore,
+ appId,
],
)
diff --git a/web/app/components/workflow-app/hooks/use-workflow-refresh-draft.ts b/web/app/components/workflow-app/hooks/use-workflow-refresh-draft.ts
index 060be206a74..2e056dfad41 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-refresh-draft.ts
+++ b/web/app/components/workflow-app/hooks/use-workflow-refresh-draft.ts
@@ -79,7 +79,7 @@ export const useWorkflowRefreshDraft = () => {
if (refreshSequence === refreshSequenceRef.current) setIsSyncingWorkflowDraft(false)
})
},
- [getWorkflowDraftGraphForCanvas, handleUpdateWorkflowCanvas, workflowStore],
+ [appId, getWorkflowDraftGraphForCanvas, handleUpdateWorkflowCanvas, workflowStore],
)
return {
diff --git a/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx b/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx
index edd7c3e11a3..844609e97d5 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx
+++ b/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx
@@ -256,7 +256,7 @@ const useWorkflowStartRunBase = (
allNodeIds: nodeIds,
})
},
- [store, workflowStore, handleRun, doSyncWorkflowDraft],
+ [workflowStore, handleRun, doSyncWorkflowDraft],
)
const handleWorkflowStartRunInChatflow = useCallback(async () => {
diff --git a/web/app/components/workflow/__tests__/workflow-test-env.tsx b/web/app/components/workflow/__tests__/workflow-test-env.tsx
index 4710658c142..e8e5b660ed3 100644
--- a/web/app/components/workflow/__tests__/workflow-test-env.tsx
+++ b/web/app/components/workflow/__tests__/workflow-test-env.tsx
@@ -73,7 +73,7 @@ import type { WorkflowHistoryState } from '../store/workflow/history-slice'
import type { Edge, Node, WorkflowRunningData } from '../types'
import { QueryClient } from '@tanstack/react-query'
import * as React from 'react'
-import ReactFlow, { ReactFlowProvider } from 'reactflow'
+import ReactFlow, { ReactFlowProvider, useStoreApi } from 'reactflow'
import { consoleQuery } from '@/service/console'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { createQueryClientWrapper } from '@/test/console/query-client'
@@ -429,6 +429,96 @@ export function renderWorkflowFlowHook<R, P = undefined>(
return { ...renderResult, ...stores }
}
+// ---------------------------------------------------------------------------
+// renderWorkflowCanvasHook — real ReactFlow store without a mounted canvas
+// ---------------------------------------------------------------------------
+
+type WorkflowCanvasState = {
+ nodes?: Node[]
+ edges?: Edge[]
+ transform?: [number, number, number]
+}
+
+type WorkflowCanvasHookTestOptions<P> = Omit<RenderHookOptions<P>, 'wrapper'> &
+ WorkflowProviderOptions &
+ WorkflowCanvasState & {
+ /** Extra providers rendered inside the workflow and ReactFlow providers. */
+ wrapper?: React.ComponentType<{ children: React.ReactNode }>
+ }
+
+type WorkflowCanvasHookTestResult<R, P> = WorkflowHookTestResult<R, P> & {
+ /** Replace the graph or viewport the hook reads from the ReactFlow store. */
+ setCanvas: (canvas: WorkflowCanvasState) => void
+}
+
+/**
+ * Renders a hook against real workflow, hooks, and ReactFlow stores without mounting
+ * `<ReactFlow>`, so the graph and viewport stay exactly as seeded. Use it for hooks that
+ * read the canvas through `useStoreApi()`, such as draft persistence.
+ */
+export function renderWorkflowCanvasHook<R, P = undefined>(
+ hook: (props: P) => R,
+ options?: WorkflowCanvasHookTestOptions<P>,
+): WorkflowCanvasHookTestResult<R, P> {
+ const {
+ initialStoreState,
+ injectWorkflowStoreSliceFn,
+ hooksStoreProps,
+ historyStore: historyConfig,
+ queryClient,
+ resource,
+ nodes = [],
+ edges = [],
+ transform = [0, 0, 1],
+ wrapper: ExtraWrapper,
+ ...rest
+ } = options ?? {}
+
+ const stores = createStoresFromOptions({
+ initialStoreState,
+ hooksStoreProps,
+ injectWorkflowStoreSliceFn,
+ })
+ const workflowWrapper = createWorkflowWrapper(stores, historyConfig, queryClient, resource)
+ let flowStore: ReturnType<typeof useStoreApi> | undefined
+
+ const setCanvas = (canvas: WorkflowCanvasState) => {
+ if (!flowStore) throw new Error('The ReactFlow store is not mounted.')
+ const state = flowStore.getState()
+ if (canvas.nodes) state.setNodes(canvas.nodes)
+ if (canvas.edges) state.setEdges(canvas.edges)
+ if (canvas.transform) flowStore.setState({ transform: canvas.transform })
+ }
+
+ function CanvasSeed({ children }: { children: React.ReactNode }) {
+ const store = useStoreApi()
+ const [seeded] = React.useState(() => {
+ flowStore = store
+ setCanvas({ nodes, edges, transform })
+ return true
+ })
+ return seeded ? children : null
+ }
+
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(
+ workflowWrapper,
+ null,
+ React.createElement(
+ ReactFlowProvider,
+ null,
+ React.createElement(
+ CanvasSeed,
+ null,
+ ExtraWrapper ? React.createElement(ExtraWrapper, null, children) : children,
+ ),
+ ),
+ )
+
+ const renderResult = renderHook(hook, { wrapper, ...rest })
+ return { ...renderResult, ...stores, setCanvas }
+}
+
// ---------------------------------------------------------------------------
// renderNodeComponent — convenience wrapper for node components
// ---------------------------------------------------------------------------
diff --git a/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx b/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx
index 21869638e2b..2afb33d38b7 100644
--- a/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx
@@ -18,10 +18,6 @@ const mocks = vi.hoisted(() => ({
toastError: vi.fn(),
}))
-vi.mock('@/app/components/workflow/hooks-store', () => ({
- useHooksStore: () => undefined,
-}))
-
vi.mock('@/app/notifications', () => ({
toast: { error: mocks.toastError },
}))
diff --git a/web/app/components/workflow/header/__tests__/run-mode.spec.tsx b/web/app/components/workflow/header/__tests__/run-mode.spec.tsx
index a67f89787fb..59635d43fc1 100644
--- a/web/app/components/workflow/header/__tests__/run-mode.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/run-mode.spec.tsx
@@ -3,7 +3,10 @@ import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { trackEvent } from '@/app/components/base/amplitude'
import { toast } from '@/app/notifications'
-import { baseRunningData, renderWorkflowComponent } from '../../__tests__/workflow-test-env'
+import {
+ baseRunningData,
+ renderWorkflowComponent as renderWithStores,
+} from '../../__tests__/workflow-test-env'
import { fullWorkflowAccessControl } from '../../hooks-store/store'
import RunMode from '../run-mode'
import { TriggerType } from '../test-run-menu'
@@ -28,32 +31,22 @@ vi.mock('../../hooks/use-checklist', async (importOriginal) => {
}
})
-vi.mock('../../hooks/use-workflow-run', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../hooks/use-workflow-run')>()
-
- return {
- ...actual,
- useWorkflowRun: () => ({
- handleStopRun: mockHandleStopRun,
- }),
- }
-})
-
-vi.mock('../../hooks/use-workflow-start-run', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../hooks/use-workflow-start-run')>()
-
- return {
- ...actual,
- useWorkflowStartRun: () => ({
+// Start and stop handlers reach RunMode through the hooks store, exactly as the app wires them.
+const renderWorkflowComponent = (...[ui, options]: Parameters<typeof renderWithStores>) =>
+ renderWithStores(ui, {
+ ...options,
+ hooksStoreProps: {
handleWorkflowStartRunInWorkflow: mockHandleWorkflowStartRunInWorkflow,
handleWorkflowTriggerScheduleRunInWorkflow: mockHandleWorkflowTriggerScheduleRunInWorkflow,
handleWorkflowTriggerWebhookRunInWorkflow: mockHandleWorkflowTriggerWebhookRunInWorkflow,
handleWorkflowTriggerPluginRunInWorkflow: mockHandleWorkflowTriggerPluginRunInWorkflow,
handleWorkflowRunAllTriggersInWorkflow: mockHandleWorkflowRunAllTriggersInWorkflow,
- }),
- }
-})
+ handleStopRun: mockHandleStopRun,
+ ...options?.hooksStoreProps,
+ },
+ })
+// Checklist validation and trigger discovery derive from the graph and have their own suites.
vi.mock('../../hooks/use-dynamic-test-run-options', () => ({
useDynamicTestRunOptions: () => mockDynamicOptions,
}))
diff --git a/web/app/components/workflow/help-line/__tests__/index.spec.tsx b/web/app/components/workflow/help-line/__tests__/index.spec.tsx
index 4a2394da584..02903540e29 100644
--- a/web/app/components/workflow/help-line/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/help-line/__tests__/index.spec.tsx
@@ -1,68 +1,53 @@
-import { render } from '@testing-library/react'
+import type { ReactNode } from 'react'
+import { act } from '@testing-library/react'
+import { useState } from 'react'
+import { ReactFlowProvider, useStoreApi } from 'reactflow'
+import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
import HelpLine from '../index'
-const mockUseViewport = vi.hoisted(() => vi.fn())
-const mockUseStore = vi.hoisted(() => vi.fn())
-
-vi.mock('reactflow', () => ({
- useViewport: () => mockUseViewport(),
-}))
-
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (
- selector: (state: {
- helpLineHorizontal?: { top: number; left: number; width: number }
- helpLineVertical?: { top: number; left: number; height: number }
- }) => unknown,
- ) => mockUseStore(selector),
-}))
+// Seeds the real ReactFlow viewport (x, y, zoom) without mounting a canvas.
+const Viewport = ({ children }: { children: ReactNode }) => {
+ const flowStore = useStoreApi()
+ useState(() => flowStore.setState({ transform: [10, 20, 2] }))
+ return children
+}
+
+const renderHelpLine = (initialStoreState = {}) =>
+ renderWorkflowComponent(
+ <ReactFlowProvider>
+ <Viewport>
+ <HelpLine />
+ </Viewport>
+ </ReactFlowProvider>,
+ { initialStoreState },
+ )
describe('HelpLine', () => {
- let helpLineHorizontal: { top: number; left: number; width: number } | undefined
- let helpLineVertical: { top: number; left: number; height: number } | undefined
-
- beforeEach(() => {
- vi.clearAllMocks()
- helpLineHorizontal = undefined
- helpLineVertical = undefined
+ it('renders nothing when no node is being aligned', () => {
+ const { container } = renderHelpLine()
- mockUseViewport.mockReturnValue({ x: 10, y: 20, zoom: 2 })
- mockUseStore.mockImplementation(
- (
- selector: (state: {
- helpLineHorizontal?: { top: number; left: number; width: number }
- helpLineVertical?: { top: number; left: number; height: number }
- }) => unknown,
- ) =>
- selector({
- helpLineHorizontal,
- helpLineVertical,
- }),
- )
+ expect(container).toBeEmptyDOMElement()
})
- it('should render nothing when both help lines are absent', () => {
- const { container } = render(<HelpLine />)
+ it('draws both guide lines in screen space using the viewport offset and zoom', () => {
+ const { container } = renderHelpLine({
+ helpLineHorizontal: { top: 30, left: 40, width: 50 },
+ helpLineVertical: { top: 60, left: 70, height: 80 },
+ })
+ const [horizontal, vertical] = Array.from(container.querySelectorAll('div'))
- expect(container).toBeEmptyDOMElement()
+ expect(horizontal).toHaveStyle({ top: '80px', left: '90px', width: '100px' })
+ expect(vertical).toHaveStyle({ top: '140px', left: '150px', height: '160px' })
})
- it('should render the horizontal and vertical guide lines using viewport offsets and zoom', () => {
- helpLineHorizontal = { top: 30, left: 40, width: 50 }
- helpLineVertical = { top: 60, left: 70, height: 80 }
+ it('removes the guides once alignment ends', () => {
+ const { container, store } = renderHelpLine({
+ helpLineHorizontal: { top: 30, left: 40, width: 50 },
+ })
+ expect(container.querySelectorAll('div')).toHaveLength(1)
- const { container } = render(<HelpLine />)
- const [horizontal, vertical] = Array.from(container.querySelectorAll('div'))
+ act(() => store.setState({ helpLineHorizontal: undefined }))
- expect(horizontal).toHaveStyle({
- top: '80px',
- left: '90px',
- width: '100px',
- })
- expect(vertical).toHaveStyle({
- top: '140px',
- left: '150px',
- height: '160px',
- })
+ expect(container).toBeEmptyDOMElement()
})
})
diff --git a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
index f3ab1302055..dc004edbca7 100644
--- a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
+++ b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
@@ -22,6 +22,8 @@ vi.mock('../../hooks/use-available-blocks', async (importOriginal) => {
}
})
+// Node replacement is owned by use-nodes-interactions (own suite); this file covers menu and
+// change-block popup focus. Copy/duplicate/delete/run against the real canvas live in index.spec.
vi.mock('../../hooks/use-nodes-interactions', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../hooks/use-nodes-interactions')>()
@@ -243,25 +245,10 @@ describe('node actions menu details', () => {
})
})
- it('should run, copy, duplicate, delete, and expose the help link', async () => {
+ it('links the help menu item to the node documentation', async () => {
const user = userEvent.setup()
- const { store } = await renderDropdownContent(user)
-
- await user.click(screen.getByText('workflow.panel.runThisStep'))
- await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
- await user.click(screen.getByText('workflow.common.copy'))
- await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
- await user.click(screen.getByText('workflow.common.duplicate'))
- await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
- await user.click(screen.getByText('common.operation.delete'))
+ await renderDropdownContent(user)
- expect(handleNodeSelect).toHaveBeenCalledWith('node-1')
- expect(store.getState().initShowLastRunTab).toBe(true)
- expect(store.getState().pendingSingleRun).toEqual({ nodeId: 'node-1', action: 'run' })
- expect(handleNodesCopy).toHaveBeenCalledWith('node-1')
- expect(handleNodesDuplicate).toHaveBeenCalledWith('node-1')
- expect(handleNodeDelete).toHaveBeenCalledWith('node-1')
- await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
expect(screen.getByRole('menuitem', { name: 'workflow.panel.helpLink' })).toHaveAttribute(
'href',
'https://docs.example.com/node',
diff --git a/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx
index 7a9f4cedde4..5af85929de6 100644
--- a/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx
@@ -1,21 +1,20 @@
+import type { AvailableNodesMetaData } from '../../hooks-store'
import { detectPlatform } from '@tanstack/react-hotkeys'
import { fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { use, useLayoutEffect } from 'react'
+import { useNodes } from 'reactflow'
+import { createNode } from '@/app/components/workflow/__tests__/fixtures'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum } from '@/app/components/workflow/types'
-import { useNodesInteractions } from '../../hooks/use-nodes-interactions'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { HooksStoreContext } from '../../hooks-store'
import { useNodeMetaData } from '../../hooks/use-nodes-meta-data'
+import { useWorkflowNodeCatalog } from '../../node-catalog'
import { NodeActionsDropdown } from '../index'
-vi.mock('../../hooks/use-nodes-interactions', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../hooks/use-nodes-interactions')>()
-
- return {
- ...actual,
- useNodesInteractions: vi.fn(),
- }
-})
-
+// Node metadata comes from the per-app block registry, which has its own suite.
vi.mock('../../hooks/use-nodes-meta-data', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../hooks/use-nodes-meta-data')>()
@@ -41,37 +40,67 @@ vi.mock('../change-block-popup', () => ({
}))
const mockUseNodeMetaData = vi.mocked(useNodeMetaData)
-const mockUseNodesInteractions = vi.mocked(useNodesInteractions)
+
+// Publishes the real block catalog so copy/duplicate know which nodes are copyable.
+const CanvasNodes = () => {
+ const catalog = useWorkflowNodeCatalog()
+ const hooksStore = use(HooksStoreContext)!
+ useLayoutEffect(() => {
+ const nodesMap = catalog.nodesMap as NonNullable<AvailableNodesMetaData['nodesMap']>
+ hooksStore.setState({
+ availableNodesMetaData: {
+ nodes: catalog.nodes.map((node) => nodesMap[node.metaData.type]),
+ nodesMap,
+ },
+ })
+ }, [catalog, hooksStore])
+ const nodes = useNodes<{ selected?: boolean }>()
+ return (
+ <output aria-label="Canvas nodes">
+ {nodes.map((node) => `${node.id}${node.data.selected ? '*' : ''}`).join(',')}
+ </output>
+ )
+}
+const canvasNodes = () => screen.getByRole('status', { name: 'Canvas nodes' }).textContent
const renderComponent = (
showHelpLink: boolean = true,
onOpenChange?: (open: boolean) => void,
readOnly = false,
-) =>
- renderWorkflowFlowComponent(
- <NodeActionsDropdown
- id="node-1"
- data={{
- title: 'Code Node',
- desc: '',
- type: BlockEnum.Code,
- }}
- triggerClassName="node-actions-trigger"
- onOpenChange={onOpenChange}
- showHelpLink={showHelpLink}
- />,
+) => {
+ const { queryClient } = createConsoleQueryWrapper({ appDslVersion: '0.6.0' })
+ seedModelProviderQueries(queryClient)
+ return renderWorkflowFlowComponent(
+ <>
+ <NodeActionsDropdown
+ id="node-1"
+ data={{
+ title: 'Code Node',
+ desc: '',
+ type: BlockEnum.Code,
+ }}
+ triggerClassName="node-actions-trigger"
+ onOpenChange={onOpenChange}
+ showHelpLink={showHelpLink}
+ />
+ <CanvasNodes />
+ </>,
{
initialStoreState: { canvasReadOnly: readOnly },
- nodes: [],
+ nodes: [
+ createNode({
+ id: 'node-1',
+ width: 240,
+ height: 80,
+ data: { type: BlockEnum.Code, title: 'Code Node' },
+ }),
+ ],
edges: [],
+ queryClient,
},
)
+}
describe('NodeActionsDropdown', () => {
- const handleNodeSelect = vi.fn()
- const handleNodeDelete = vi.fn()
- const handleNodesCopy = vi.fn()
- const handleNodesDuplicate = vi.fn()
-
beforeEach(() => {
vi.clearAllMocks()
mockUseNodeMetaData.mockReturnValue({
@@ -82,12 +111,6 @@ describe('NodeActionsDropdown', () => {
author: 'Dify',
helpLinkUri: 'https://docs.example.com/node',
} as ReturnType<typeof useNodeMetaData>)
- mockUseNodesInteractions.mockReturnValue({
- handleNodeDelete,
- handleNodesDuplicate,
- handleNodeSelect,
- handleNodesCopy,
- } as unknown as ReturnType<typeof useNodesInteractions>)
})
it('should open the dropdown and trigger single-run actions', async () => {
@@ -103,19 +126,19 @@ describe('NodeActionsDropdown', () => {
await user.click(screen.getByText('workflow.panel.runThisStep'))
- expect(handleNodeSelect).toHaveBeenCalledWith('node-1')
+ expect(canvasNodes()).toBe('node-1*')
expect(store.getState().initShowLastRunTab).toBe(true)
expect(store.getState().pendingSingleRun).toEqual({ nodeId: 'node-1', action: 'run' })
})
it.each([
- { key: 'c', action: handleNodesCopy },
- { key: 'd', action: handleNodesDuplicate },
- { key: 'Delete', action: handleNodeDelete },
- { key: 'Backspace', action: handleNodeDelete },
- ])('runs $key from the focused portalled node menu', async ({ key, action }) => {
+ { key: 'c', clipboard: ['node-1'], nodeCount: 1 },
+ { key: 'd', clipboard: undefined, nodeCount: 2 },
+ { key: 'Delete', clipboard: undefined, nodeCount: 0 },
+ { key: 'Backspace', clipboard: undefined, nodeCount: 0 },
+ ])('runs $key from the focused portalled node menu', async ({ key, clipboard, nodeCount }) => {
const user = userEvent.setup()
- const { container } = renderComponent()
+ const { container, store } = renderComponent()
await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
await user.keyboard('{ArrowDown}')
const focusedItem = document.activeElement
@@ -125,7 +148,25 @@ describe('NodeActionsDropdown', () => {
const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
await user.keyboard(key.length === 1 ? `{${mod}>}${key}{/${mod}}` : `{${key}}`)
- expect(action).toHaveBeenCalledExactlyOnceWith('node-1')
+ if (clipboard)
+ expect(store.getState().clipboardElements.map((node) => node.id)).toEqual(clipboard)
+ expect(canvasNodes()!.split(',').filter(Boolean)).toHaveLength(nodeCount)
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ })
+
+ it.each([
+ { name: /workflow\.common\.copy/, clipboard: ['node-1'], nodeCount: 1 },
+ { name: /workflow\.common\.duplicate/, clipboard: undefined, nodeCount: 2 },
+ ])('runs the $name menu item on click', async ({ name, clipboard, nodeCount }) => {
+ const user = userEvent.setup()
+ const { store } = renderComponent()
+ await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
+
+ await user.click(screen.getByRole('menuitem', { name }))
+
+ if (clipboard)
+ expect(store.getState().clipboardElements.map((node) => node.id)).toEqual(clipboard)
+ expect(canvasNodes()!.split(',').filter(Boolean)).toHaveLength(nodeCount)
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
})
@@ -154,20 +195,19 @@ describe('NodeActionsDropdown', () => {
})
fireEvent(item, repeat)
expect(repeat.defaultPrevented).toBe(true)
- expect(handleNodesDuplicate).not.toHaveBeenCalled()
+ expect(canvasNodes()).toBe('node-1')
expect(screen.getByRole('menu')).toBeInTheDocument()
})
it('does not run unavailable editing shortcuts from a readonly node menu', async () => {
const user = userEvent.setup()
- renderComponent(true, undefined, true)
+ const { store } = renderComponent(true, undefined, true)
await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
await user.keyboard('{ArrowDown}')
const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
await user.keyboard(`{${mod}>}cd{/${mod}}{Delete}`)
- expect(handleNodesCopy).not.toHaveBeenCalled()
- expect(handleNodesDuplicate).not.toHaveBeenCalled()
- expect(handleNodeDelete).not.toHaveBeenCalled()
+ expect(store.getState().clipboardElements).toEqual([])
+ expect(canvasNodes()).toBe('node-1')
})
it('should hide single-run actions when nodes are readonly', async () => {
diff --git a/web/app/components/workflow/nodes/variable-assigner/__tests__/hooks.spec.ts b/web/app/components/workflow/nodes/variable-assigner/__tests__/hooks.spec.ts
index 81588fa7c85..ea46a55d699 100644
--- a/web/app/components/workflow/nodes/variable-assigner/__tests__/hooks.spec.ts
+++ b/web/app/components/workflow/nodes/variable-assigner/__tests__/hooks.spec.ts
@@ -1,117 +1,65 @@
+import type { Node } from '../../../types'
import { act } from '@testing-library/react'
-import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'
-import { VarType } from '../../../types'
+import { useNodes } from 'reactflow'
+import { createEdge, createNode } from '../../../__tests__/fixtures'
+import { renderWorkflowCanvasHook } from '../../../__tests__/workflow-test-env'
+import { BlockEnum, VarType } from '../../../types'
import { useGetAvailableVars, useVariableAssigner } from '../hooks'
-const mockUseStoreApi = vi.hoisted(() => vi.fn())
-const mockUseNodes = vi.hoisted(() => vi.fn())
-const mockUseNodeDataUpdate = vi.hoisted(() => vi.fn())
-const mockUseWorkflow = vi.hoisted(() => vi.fn())
-const mockUseWorkflowVariables = vi.hoisted(() => vi.fn())
-const mockUseWorkflowStore = vi.hoisted(() => vi.fn())
-vi.mock('reactflow', () => ({
- useStoreApi: () => mockUseStoreApi(),
- useNodes: () => mockUseNodes(),
+// Branch traversal and variable collection have their own suites; here they only feed the filters.
+const mockGetBeforeNodesInSameBranchIncludeParent = vi.hoisted(() => vi.fn())
+const mockGetNodeAvailableVars = vi.hoisted(() => vi.fn())
+vi.mock('../../../hooks/use-workflow', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../hooks/use-workflow')>()),
+ useWorkflow: () => ({
+ getBeforeNodesInSameBranchIncludeParent: mockGetBeforeNodesInSameBranchIncludeParent,
+ }),
}))
-
-vi.mock('../../../hooks/use-node-data-update', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../../hooks/use-node-data-update')>()
-
- return {
- ...actual,
- useNodeDataUpdate: () => mockUseNodeDataUpdate(),
- }
-})
-
-vi.mock('../../../hooks/use-workflow', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../../hooks/use-workflow')>()
-
- return {
- ...actual,
- useWorkflow: () => mockUseWorkflow(),
- }
-})
-
-vi.mock('../../../hooks/use-workflow-variables', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../../hooks/use-workflow-variables')>()
-
- return {
- ...actual,
- useWorkflowVariables: () => mockUseWorkflowVariables(),
- }
-})
-
-vi.mock('@/app/components/workflow/store', () => ({
- useWorkflowStore: () => mockUseWorkflowStore(),
+vi.mock('../../../hooks/use-workflow-variables', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../hooks/use-workflow-variables')>()),
+ useWorkflowVariables: () => ({ getNodeAvailableVars: mockGetNodeAvailableVars }),
}))
-describe('variable-assigner/hooks', () => {
- const mockHandleNodeDataUpdate = vi.fn()
- const mockSetNodes = vi.fn()
- const mockSetShowAssignVariablePopup = vi.fn()
- const mockSetHoveringAssignVariableGroupId = vi.fn()
- const getNodes = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
- getNodes.mockReturnValue([
- {
- id: 'assigner-1',
- data: {
- variables: [['start', 'foo']],
- output_type: VarType.string,
- advanced_settings: {
- groups: [
- {
- groupId: 'group-1',
- variables: [],
- output_type: VarType.string,
- },
- ],
- },
- },
+const createAssigner = (data: Record<string, unknown> = {}) =>
+ createNode({
+ id: 'assigner-1',
+ data: {
+ type: BlockEnum.VariableAssigner,
+ variables: [['start', 'foo']],
+ output_type: VarType.string,
+ advanced_settings: {
+ group_enabled: true,
+ groups: [
+ { groupId: 'group-1', group_name: 'Group1', variables: [], output_type: VarType.string },
+ ],
},
- ])
- mockUseStoreApi.mockReturnValue({
- getState: () => ({
- getNodes,
- setNodes: mockSetNodes,
- }),
- })
- mockUseNodeDataUpdate.mockReturnValue({
- handleNodeDataUpdate: mockHandleNodeDataUpdate,
- })
- mockUseWorkflowStore.mockReturnValue({
- getState: () => ({
- setShowAssignVariablePopup: mockSetShowAssignVariablePopup,
- setHoveringAssignVariableGroupId: mockSetHoveringAssignVariableGroupId,
- connectingNodePayload: { id: 'connecting-node' },
- }),
- })
- mockUseNodes.mockReturnValue([])
- mockUseWorkflow.mockReturnValue({
- getBeforeNodesInSameBranchIncludeParent: vi.fn(),
- })
- mockUseWorkflowVariables.mockReturnValue({
- getNodeAvailableVars: vi.fn(),
- })
+ ...data,
+ },
})
- it('should append target variables, ignore duplicates, and update grouped variables', () => {
- const { result } = renderHook(() => useVariableAssigner(), {
- resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
- })
+const renderAssigner = (nodes: Node[] = [createAssigner()], initialStoreState = {}) =>
+ renderWorkflowCanvasHook(() => ({ assigner: useVariableAssigner(), nodes: useNodes() }), {
+ nodes,
+ initialStoreState,
+ })
+
+const assignerData = (nodes: { id: string; data: unknown }[]) =>
+ nodes.find((node) => node.id === 'assigner-1')!.data as Record<string, unknown>
+
+describe('useVariableAssigner', () => {
+ it('appends new target variables, ignores duplicates, and fills grouped variables', () => {
+ const { result } = renderAssigner()
act(() => {
- result.current.handleAssignVariableValueChange('assigner-1', ['start', 'bar'], {
+ result.current.assigner.handleAssignVariableValueChange('assigner-1', ['start', 'bar'], {
variable: 'value',
type: VarType.number,
})
- result.current.handleAssignVariableValueChange('assigner-1', ['start', 'foo'], {
+ result.current.assigner.handleAssignVariableValueChange('assigner-1', ['start', 'foo'], {
variable: 'value',
type: VarType.number,
})
- result.current.handleAssignVariableValueChange(
+ result.current.assigner.handleAssignVariableValueChange(
'assigner-1',
['start', 'grouped'],
{ variable: 'grouped', type: VarType.arrayString },
@@ -119,226 +67,132 @@ describe('variable-assigner/hooks', () => {
)
})
- expect(mockHandleNodeDataUpdate).toHaveBeenNthCalledWith(1, {
- id: 'assigner-1',
- data: {
- variables: [
- ['start', 'foo'],
- ['start', 'bar'],
+ expect(assignerData(result.current.nodes)).toMatchObject({
+ variables: [
+ ['start', 'foo'],
+ ['start', 'bar'],
+ ],
+ output_type: VarType.number,
+ advanced_settings: {
+ groups: [
+ {
+ groupId: 'group-1',
+ variables: [['start', 'grouped']],
+ output_type: VarType.arrayString,
+ },
],
- output_type: VarType.number,
- },
- })
- expect(mockHandleNodeDataUpdate).toHaveBeenNthCalledWith(2, {
- id: 'assigner-1',
- data: {
- advanced_settings: {
- groups: [
- {
- groupId: 'group-1',
- variables: [['start', 'grouped']],
- output_type: VarType.arrayString,
- },
- ],
- },
},
})
- expect(mockHandleNodeDataUpdate).toHaveBeenCalledTimes(2)
})
- it('should close the popup and add variables through the positioned add-variable flow', () => {
- getNodes.mockReturnValue([
- {
- id: 'source-node',
- data: {
- _showAddVariablePopup: true,
- _holdAddVariablePopup: true,
- },
- },
- {
- id: 'assigner-1',
- data: {
- variables: [],
- advanced_settings: {
- groups: [
- {
- groupId: 'group-1',
- variables: [],
- },
- ],
- },
- _showAddVariablePopup: true,
- _holdAddVariablePopup: true,
- },
- },
- ])
-
- const { result } = renderHook(() => useVariableAssigner(), {
- resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
- })
+ it('closes the add-variable popups and adds the picked variable to the group', () => {
+ const popupOpen = { _showAddVariablePopup: true, _holdAddVariablePopup: true }
+ const { result, store } = renderAssigner(
+ [
+ createNode({ id: 'source-node', data: popupOpen }),
+ createAssigner({ variables: [], ...popupOpen }),
+ ],
+ { showAssignVariablePopup: { nodeId: 'assigner-1' } },
+ )
- act(() => {
- result.current.handleAddVariableInAddVariablePopupWithPosition(
+ act(() =>
+ result.current.assigner.handleAddVariableInAddVariablePopupWithPosition(
'source-node',
'assigner-1',
'group-1',
['start', 'output'],
{ variable: 'output', type: VarType.object },
- )
- })
+ ),
+ )
- expect(mockSetNodes).toHaveBeenCalledWith([
- expect.objectContaining({
- id: 'source-node',
- data: expect.objectContaining({
- _showAddVariablePopup: false,
- _holdAddVariablePopup: false,
- }),
- }),
- expect.objectContaining({
- id: 'assigner-1',
- data: expect.objectContaining({
- _showAddVariablePopup: false,
- _holdAddVariablePopup: false,
- }),
- }),
- ])
- expect(mockSetShowAssignVariablePopup).toHaveBeenCalledWith(undefined)
- expect(mockHandleNodeDataUpdate).toHaveBeenCalledWith({
- id: 'assigner-1',
- data: {
- advanced_settings: {
- groups: [
- {
- groupId: 'group-1',
- variables: [['start', 'output']],
- output_type: VarType.object,
- },
- ],
- },
+ for (const node of result.current.nodes)
+ expect(node.data).toMatchObject({
+ _showAddVariablePopup: false,
+ _holdAddVariablePopup: false,
+ })
+ expect(store.getState().showAssignVariablePopup).toBeUndefined()
+ expect(assignerData(result.current.nodes)).toMatchObject({
+ advanced_settings: {
+ groups: [
+ { groupId: 'group-1', variables: [['start', 'output']], output_type: VarType.object },
+ ],
},
})
})
- it('should update the hovered group state on enter and leave', () => {
- const { result } = renderHook(() => useVariableAssigner(), {
- resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
- })
+ it.each([
+ { connecting: true, afterLeave: undefined },
+ { connecting: false, afterLeave: 'group-1' },
+ ])(
+ 'tracks the hovered group and clears it on leave only while connecting (connecting=$connecting)',
+ ({ connecting, afterLeave }) => {
+ const { result, store } = renderAssigner([createAssigner()], {
+ connectingNodePayload: connecting ? { nodeId: 'source-node' } : undefined,
+ })
- act(() => {
- result.current.handleGroupItemMouseEnter('group-1')
- result.current.handleGroupItemMouseLeave()
- })
+ act(() => result.current.assigner.handleGroupItemMouseEnter('group-1'))
+ expect(store.getState().hoveringAssignVariableGroupId).toBe('group-1')
- expect(mockSetHoveringAssignVariableGroupId).toHaveBeenNthCalledWith(1, 'group-1')
- expect(mockSetHoveringAssignVariableGroupId).toHaveBeenNthCalledWith(2, undefined)
- })
+ act(() => result.current.assigner.handleGroupItemMouseLeave())
+ expect(store.getState().hoveringAssignVariableGroupId).toBe(afterLeave)
+ },
+ )
+})
- it('should collect available vars and filter start-node env vars when hideEnv is enabled', () => {
- mockUseNodes.mockReturnValue([
- {
- id: 'current-node',
- parentId: 'parent-node',
- },
- {
- id: 'before-1',
- },
- {
- id: 'parent-node',
- },
- ])
- const getBeforeNodesInSameBranchIncludeParent = vi.fn(() => [
- { id: 'before-1' },
- { id: 'before-1' },
- ])
- const getNodeAvailableVars = vi
- .fn()
- .mockReturnValueOnce([
- {
- isStartNode: true,
- vars: [{ variable: 'sys.user_id' }, { variable: 'foo' }],
- },
- {
- isStartNode: false,
- vars: [],
- },
- ])
- .mockReturnValueOnce([
- {
- isStartNode: false,
- vars: [{ variable: 'bar' }],
- },
- ])
+describe('useGetAvailableVars', () => {
+ const canvas = {
+ nodes: [
+ createNode({ id: 'parent-node', data: { type: BlockEnum.Iteration } }),
+ createNode({ id: 'before-1' }),
+ createNode({ id: 'current-node', parentId: 'parent-node' }),
+ ],
+ edges: [createEdge({ source: 'before-1', target: 'current-node' })],
+ }
- mockUseWorkflow.mockReturnValue({
- getBeforeNodesInSameBranchIncludeParent,
- })
- mockUseWorkflowVariables.mockReturnValue({
- getNodeAvailableVars,
- })
+ beforeEach(() => {
+ mockGetBeforeNodesInSameBranchIncludeParent.mockReturnValue([canvas.nodes[1], canvas.nodes[1]])
+ })
- const { result } = renderHook(() => useGetAvailableVars(), {
- resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
- })
+ it('hides system start variables and empty groups when env vars are hidden', () => {
+ mockGetNodeAvailableVars.mockReturnValue([
+ { isStartNode: true, vars: [{ variable: 'sys.user_id' }, { variable: 'foo' }] },
+ { isStartNode: false, vars: [] },
+ ])
+ const { result } = renderWorkflowCanvasHook(() => useGetAvailableVars(), canvas)
expect(result.current('current-node', 'target', () => true, true)).toEqual([
- {
- isStartNode: true,
- vars: [{ variable: 'foo' }],
- },
+ { isStartNode: true, vars: [{ variable: 'foo' }] },
])
- expect(result.current('current-node', 'target', () => true, false)).toEqual([
- {
- isStartNode: false,
- vars: [{ variable: 'bar' }],
- },
- ])
- expect(getNodeAvailableVars).toHaveBeenNthCalledWith(
- 1,
+ expect(mockGetNodeAvailableVars).toHaveBeenCalledWith(
expect.objectContaining({
- parentNode: { id: 'parent-node' },
- beforeNodes: [{ id: 'before-1' }],
+ parentNode: expect.objectContaining({ id: 'parent-node' }),
+ beforeNodes: [expect.objectContaining({ id: 'before-1' })],
hideEnv: true,
isChatflow: false,
}),
)
- expect(result.current('missing-node', 'target', () => true)).toEqual([])
- expect(getNodeAvailableVars).toHaveBeenCalledTimes(2)
})
- it('should filter system variables when the current flow is a snippet', () => {
- mockUseNodes.mockReturnValue([
- {
- id: 'current-node',
- },
- {
- id: 'before-1',
- },
- ])
- const getBeforeNodesInSameBranchIncludeParent = vi.fn(() => [{ id: 'before-1' }])
- const getNodeAvailableVars = vi.fn(() => [
- {
- isStartNode: false,
- vars: [{ variable: 'sys.user_id' }, { variable: 'answer' }],
- },
- ])
+ it('returns the collected variables unchanged when env vars are shown', () => {
+ const vars = [{ isStartNode: false, vars: [{ variable: 'bar' }] }]
+ mockGetNodeAvailableVars.mockReturnValue(vars)
+ const { result } = renderWorkflowCanvasHook(() => useGetAvailableVars(), canvas)
- mockUseWorkflow.mockReturnValue({
- getBeforeNodesInSameBranchIncludeParent,
- })
- mockUseWorkflowVariables.mockReturnValue({
- getNodeAvailableVars,
- })
+ expect(result.current('current-node', 'target', () => true, false)).toEqual(vars)
+ expect(result.current('missing-node', 'target', () => true)).toEqual([])
+ })
- const { result } = renderHook(() => useGetAvailableVars(), {
+ it('filters system variables when the current flow is a snippet', () => {
+ mockGetNodeAvailableVars.mockReturnValue([
+ { isStartNode: false, vars: [{ variable: 'sys.user_id' }, { variable: 'answer' }] },
+ ])
+ const { result } = renderWorkflowCanvasHook(() => useGetAvailableVars(), {
+ ...canvas,
resource: { kind: 'snippet', snippetId: 'snippet-1' },
})
expect(result.current('current-node', 'target', () => true, false)).toEqual([
- {
- isStartNode: false,
- vars: [{ variable: 'answer' }],
- },
+ { isStartNode: false, vars: [{ variable: 'answer' }] },
])
})
})
diff --git a/web/app/components/workflow/note-node/__tests__/hooks.spec.tsx b/web/app/components/workflow/note-node/__tests__/hooks.spec.tsx
index 1529fd5fd02..3ad6381102d 100644
--- a/web/app/components/workflow/note-node/__tests__/hooks.spec.tsx
+++ b/web/app/components/workflow/note-node/__tests__/hooks.spec.tsx
@@ -1,54 +1,47 @@
-import { act, renderHook } from '@testing-library/react'
+import type { NoteNodeType } from '../types'
+import { act, waitFor } from '@testing-library/react'
import { $createParagraphNode, $createTextNode, $getRoot, createEditor } from 'lexical'
-import { NOTE_SHOW_AUTHOR_STORAGE_KEY } from '../constants'
+import { useNodes } from 'reactflow'
+import { createNode } from '../../__tests__/fixtures'
+import { renderWorkflowCanvasHook } from '../../__tests__/workflow-test-env'
+import { CUSTOM_NOTE_NODE } from '../constants'
import { useNote } from '../hooks'
+import { NoteTheme } from '../types'
-const mockHandleNodeDataUpdateWithSyncDraft = vi.hoisted(() => vi.fn())
-const mockSaveStateToHistory = vi.hoisted(() => vi.fn())
-
-vi.mock('../../hooks/use-node-data-update', () => ({
- useNodeDataUpdate: () => ({
- handleNodeDataUpdateWithSyncDraft: mockHandleNodeDataUpdateWithSyncDraft,
- }),
-}))
+const renderNote = () =>
+ renderWorkflowCanvasHook(() => ({ note: useNote('note-1'), nodes: useNodes<NoteNodeType>() }), {
+ nodes: [
+ createNode({
+ id: 'note-1',
+ type: CUSTOM_NOTE_NODE,
+ data: { text: '', theme: NoteTheme.blue, author: 'Alice', showAuthor: true },
+ }),
+ ],
+ historyStore: { nodes: [], edges: [] },
+ })
-vi.mock('../../hooks/use-workflow-history', () => ({
- useWorkflowHistory: () => ({
- saveStateToHistory: mockSaveStateToHistory,
- }),
- WorkflowHistoryEvent: {
- NoteChange: 'note-change',
- },
-}))
+const noteData = (result: ReturnType<typeof renderNote>['result']) =>
+ result.current.nodes.find((node) => node.id === 'note-1')!.data
describe('useNote', () => {
- beforeEach(() => {
- localStorage.removeItem(NOTE_SHOW_AUTHOR_STORAGE_KEY)
- })
-
- it('updates theme and author visibility while saving note history entries', () => {
- const { result } = renderHook(() => useNote('note-1'))
+ it('changes the note theme and records it in workflow history', async () => {
+ const { result, store } = renderNote()
act(() => {
- result.current.handleThemeChange('blue')
- result.current.handleShowAuthorChange(true)
+ result.current.note.handleThemeChange(NoteTheme.violet)
})
- expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenNthCalledWith(1, {
- id: 'note-1',
- data: { theme: 'blue' },
- })
- expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenNthCalledWith(2, {
- id: 'note-1',
- data: { showAuthor: true },
- })
- expect(mockSaveStateToHistory).toHaveBeenNthCalledWith(1, 'note-change', { nodeId: 'note-1' })
- expect(mockSaveStateToHistory).toHaveBeenNthCalledWith(2, 'note-change', { nodeId: 'note-1' })
- expect(localStorage.getItem(NOTE_SHOW_AUTHOR_STORAGE_KEY)).toBe('true')
+ expect(noteData(result)).toMatchObject({ theme: NoteTheme.violet })
+ await waitFor(() =>
+ expect(store.getState().workflowHistory).toMatchObject({
+ workflowHistoryEvent: 'NoteChange',
+ workflowHistoryEventMeta: { nodeId: 'note-1' },
+ }),
+ )
})
it('serializes non-empty editor state and clears empty editor state', () => {
- const { result } = renderHook(() => useNote('note-2'))
+ const { result } = renderNote()
const editor = createEditor({
onError: (error) => {
throw error
@@ -61,20 +54,18 @@ describe('useNote', () => {
},
{ discrete: true },
)
- const nonEmptyEditorState = editor.getEditorState()
act(() => {
- result.current.handleEditorChange(nonEmptyEditorState)
- result.current.handleEditorChange(emptyEditorState)
+ result.current.note.handleEditorChange(editor.getEditorState())
})
- const saved = mockHandleNodeDataUpdateWithSyncDraft.mock.calls[0]![0]
- expect(saved.id).toBe('note-2')
- const restored = editor.parseEditorState(saved.data.text)
+ const restored = editor.parseEditorState(noteData(result).text)
expect(restored.read(() => $getRoot().getTextContent())).toBe('Remember this decision')
- expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenNthCalledWith(2, {
- id: 'note-2',
- data: { text: '' },
+
+ act(() => {
+ result.current.note.handleEditorChange(emptyEditorState)
})
+
+ expect(noteData(result)).toMatchObject({ text: '' })
})
})
diff --git a/web/app/components/workflow/note-node/__tests__/index.spec.tsx b/web/app/components/workflow/note-node/__tests__/index.spec.tsx
index 50601d11721..6589787ef78 100644
--- a/web/app/components/workflow/note-node/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/note-node/__tests__/index.spec.tsx
@@ -1,63 +1,18 @@
import type { NoteNodeType } from '../types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useNodes } from 'reactflow'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { createNode } from '../../__tests__/fixtures'
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
-import { CUSTOM_NOTE_NODE } from '../constants'
+import { CUSTOM_NOTE_NODE, NOTE_SHOW_AUTHOR_STORAGE_KEY } from '../constants'
import NoteNode from '../index'
import { NoteTheme } from '../types'
-const {
- mockHandleEditorChange,
- mockHandleNodeDelete,
- mockHandleNodesCopy,
- mockHandleNodesDuplicate,
- mockHandleShowAuthorChange,
- mockHandleThemeChange,
-} = vi.hoisted(() => ({
- mockHandleEditorChange: vi.fn(),
- mockHandleNodeDelete: vi.fn(),
- mockHandleNodesCopy: vi.fn(),
- mockHandleNodesDuplicate: vi.fn(),
- mockHandleShowAuthorChange: vi.fn(),
- mockHandleThemeChange: vi.fn(),
-}))
-
-vi.mock('../../hooks/use-nodes-sync-draft', () => ({
- useNodesSyncDraft: () => ({ handleSyncWorkflowDraft: vi.fn() }),
-}))
-vi.mock('../../collaboration/core/collaboration-manager', () => ({
- collaborationManager: {
- setNodes: vi.fn(),
- setEdges: vi.fn(),
- canApplyLocalGraphMutation: () => true,
- },
-}))
-
-vi.mock('../../hooks/use-nodes-interactions', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../hooks/use-nodes-interactions')>()
- return {
- ...actual,
- useNodesInteractions: () => ({
- handleNodesCopy: mockHandleNodesCopy,
- handleNodesDuplicate: mockHandleNodesDuplicate,
- handleNodeDelete: mockHandleNodeDelete,
- }),
- }
-})
-
-vi.mock('../hooks', () => ({
- useNote: () => ({
- handleThemeChange: mockHandleThemeChange,
- handleEditorChange: mockHandleEditorChange,
- handleShowAuthorChange: mockHandleShowAuthorChange,
- }),
-}))
-
-const createNoteData = (overrides: Partial<NoteNodeType> = {}): NoteNodeType => ({
+const createNoteData = (overrides: Partial<NoteNodeType> = {}): Partial<NoteNodeType> => ({
title: '',
desc: '',
- type: '' as unknown as NoteNodeType['type'],
text: '',
theme: NoteTheme.blue,
author: 'Alice',
@@ -68,37 +23,54 @@ const createNoteData = (overrides: Partial<NoteNodeType> = {}): NoteNodeType =>
...overrides,
})
+const NoteIds = () => {
+ const nodes = useNodes()
+ return <output aria-label="Canvas notes">{nodes.map((node) => node.id).join(',')}</output>
+}
+
const renderNoteNode = (dataOverrides: Partial<NoteNodeType> = {}) => {
- const nodeData = createNoteData(dataOverrides)
- const nodes = [
- createNode({
- id: 'note-1',
- type: CUSTOM_NOTE_NODE,
- data: nodeData,
- selected: !!nodeData.selected,
- }),
- ]
-
- return renderWorkflowFlowComponent(<button type="button">Outside note</button>, {
- nodes,
- edges: [],
- reactFlowProps: {
- nodeTypes: {
- [CUSTOM_NOTE_NODE]: NoteNode,
+ const data = createNoteData(dataOverrides)
+ const { queryClient } = createConsoleQueryWrapper({ appDslVersion: '0.6.0' })
+ seedModelProviderQueries(queryClient)
+
+ return renderWorkflowFlowComponent(
+ <>
+ <button type="button">Outside note</button>
+ <NoteIds />
+ </>,
+ {
+ nodes: [
+ createNode({
+ id: 'note-1',
+ type: CUSTOM_NOTE_NODE,
+ data,
+ selected: !!data.selected,
+ width: 240,
+ height: 88,
+ }),
+ ],
+ edges: [],
+ reactFlowProps: {
+ nodeTypes: {
+ [CUSTOM_NOTE_NODE]: NoteNode,
+ },
},
+ historyStore: { nodes: [], edges: [] },
+ queryClient,
},
- initialStoreState: {
- controlPromptEditorRerenderKey: 0,
- },
- })
+ )
+}
+
+const openNoteMenu = async (user: ReturnType<typeof userEvent.setup>) => {
+ await user.click(await screen.findByRole('button', { name: 'common.operation.more' }))
}
describe('NoteNode', () => {
beforeEach(() => {
- vi.clearAllMocks()
+ localStorage.removeItem(NOTE_SHOW_AUTHOR_STORAGE_KEY)
})
- it('should hide the toolbar for temporary notes', () => {
+ it('hides the toolbar for temporary notes', () => {
renderNoteNode({
_isTempNode: true,
showAuthor: false,
@@ -107,11 +79,10 @@ describe('NoteNode', () => {
expect(screen.queryByText('workflow.nodes.note.editor.small')).not.toBeInTheDocument()
})
- it('should clear the selected state when clicking outside the note', async () => {
+ it('clears the selected state when clicking outside the note', async () => {
const user = userEvent.setup()
renderNoteNode()
- expect(screen.getByText('Alice')).toBeInTheDocument()
expect(await screen.findByText('workflow.nodes.note.editor.small')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Outside note' }))
await waitFor(() =>
@@ -119,4 +90,31 @@ describe('NoteNode', () => {
)
expect(screen.getByText('Alice')).toBeInTheDocument()
})
+
+ it('hides the author and remembers the preference for new notes', async () => {
+ const user = userEvent.setup()
+ renderNoteNode()
+
+ expect(screen.getByText('Alice')).toBeInTheDocument()
+ await openNoteMenu(user)
+ await user.click(
+ screen.getByRole('menuitemcheckbox', { name: 'workflow.nodes.note.editor.showAuthor' }),
+ )
+
+ await waitFor(() => expect(screen.queryByText('Alice')).not.toBeInTheDocument())
+ expect(localStorage.getItem(NOTE_SHOW_AUTHOR_STORAGE_KEY)).toBe('false')
+ })
+
+ it('removes the note from the canvas from its menu', async () => {
+ const user = userEvent.setup()
+ renderNoteNode()
+
+ expect(screen.getByRole('status', { name: 'Canvas notes' })).toHaveTextContent('note-1')
+ await openNoteMenu(user)
+ await user.click(screen.getByRole('menuitem', { name: /common\.operation\.delete/ }))
+
+ await waitFor(() =>
+ expect(screen.getByRole('status', { name: 'Canvas notes' })).toBeEmptyDOMElement(),
+ )
+ })
})
diff --git a/web/app/components/workflow/operator/__tests__/control.spec.tsx b/web/app/components/workflow/operator/__tests__/control.spec.tsx
index 9cdef2f490f..9e192f25cf7 100644
--- a/web/app/components/workflow/operator/__tests__/control.spec.tsx
+++ b/web/app/components/workflow/operator/__tests__/control.spec.tsx
@@ -1,176 +1,144 @@
-import { screen } from '@testing-library/react'
+import type { Shape } from '../../store/workflow'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { renderWorkflowComponent as renderComponent } from '../../__tests__/workflow-test-env'
-import { ControlMode } from '../../types'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createNode } from '../../__tests__/fixtures'
+import { baseRunningData, renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
+import { CUSTOM_NOTE_NODE } from '../../note-node/constants'
+import { ControlMode, WorkflowRunningStatus } from '../../types'
import Control from '../control'
-type WorkflowStoreState = {
- controlMode: ControlMode
-}
+vi.mock('../../hooks/use-nodes-sync-draft', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../hooks/use-nodes-sync-draft')>()
+ return {
+ ...actual,
+ useNodesSyncDraft: () => ({
+ handleSyncWorkflowDraft: vi.fn(),
+ }),
+ }
+})
-const {
- mockHandleAddNote,
- mockHandleLayout,
- mockHandleModeComment,
- mockHandleModeHand,
- mockHandleModePointer,
-} = vi.hoisted(() => ({
- mockHandleAddNote: vi.fn(),
- mockHandleLayout: vi.fn(),
- mockHandleModeComment: vi.fn(),
- mockHandleModeHand: vi.fn(),
- mockHandleModePointer: vi.fn(),
+// The add-block selector and image export own their own suites and service setup.
+vi.mock('../add-block', () => ({
+ default: () => null,
}))
-let mockNodesReadOnly = false
-let mockCanUseCommentMode = true
-let mockIsCommentModeAvailable = true
-let mockStoreState: WorkflowStoreState
-
-vi.mock('../../hooks/use-workflow', () => ({
- useNodesReadOnly: () => ({
- nodesReadOnly: mockNodesReadOnly,
- getNodesReadOnly: () => mockNodesReadOnly,
- }),
+vi.mock('../export-image', () => ({
+ ExportImage: () => null,
}))
-vi.mock('../../hooks/use-workflow-panel-interactions', () => ({
- useWorkflowMoveMode: () => ({
- handleModePointer: mockHandleModePointer,
- handleModeHand: mockHandleModeHand,
- handleModeComment: mockHandleModeComment,
- isCommentModeAvailable: mockIsCommentModeAvailable,
- canUseCommentMode: mockCanUseCommentMode,
- }),
-}))
+const renderControl = ({
+ initialStoreState,
+ collaborationEnabled = true,
+}: {
+ initialStoreState?: Partial<Shape>
+ collaborationEnabled?: boolean
+} = {}) => {
+ const { queryClient } = createConsoleQueryWrapper({
+ accountProfile: { name: 'Ada' },
+ systemFeatures: { enable_collaboration_mode: collaborationEnabled },
+ })
+ return renderWorkflowFlowComponent(<Control />, {
+ queryClient,
+ nodes: [createNode({ id: 'node-1' })],
+ initialStoreState: { controlMode: ControlMode.Pointer, ...initialStoreState },
+ })
+}
-vi.mock('../../hooks/use-workflow-organize', () => ({
- useWorkflowOrganize: () => ({
- handleLayout: mockHandleLayout,
- }),
-}))
+const getModeButton = (mode: 'pointerMode' | 'handMode' | 'commentMode') =>
+ screen.getByRole('button', { name: `workflow.common.${mode}` })
-vi.mock('../hooks', () => ({
- useOperator: () => ({
- handleAddNote: mockHandleAddNote,
- }),
-}))
+describe('Control', () => {
+ it('switches the canvas between pointer, hand, and comment modes', async () => {
+ const user = userEvent.setup()
+ const { store } = renderControl()
-vi.mock('../add-block', () => ({
- default: () => <div data-testid="add-block" />,
-}))
+ expect(getModeButton('pointerMode')).toHaveAttribute('aria-pressed', 'true')
-vi.mock('../export-image', () => ({
- ExportImage: () => <div data-testid="export-image" />,
-}))
+ await user.click(getModeButton('handMode'))
+ expect(store.getState().controlMode).toBe(ControlMode.Hand)
+ expect(getModeButton('handMode')).toHaveAttribute('aria-pressed', 'true')
+ expect(getModeButton('pointerMode')).toHaveAttribute('aria-pressed', 'false')
-const render = (ui: React.ReactElement) =>
- renderComponent(ui, { initialStoreState: mockStoreState })
+ await user.click(getModeButton('commentMode'))
+ expect(store.getState().controlMode).toBe(ControlMode.Comment)
+ expect(getModeButton('commentMode')).toHaveAttribute('aria-pressed', 'true')
-describe('Control', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockNodesReadOnly = false
- mockCanUseCommentMode = true
- mockIsCommentModeAvailable = true
- mockStoreState = {
- controlMode: ControlMode.Pointer,
- }
+ await user.click(getModeButton('pointerMode'))
+ expect(store.getState().controlMode).toBe(ControlMode.Pointer)
})
- // Rendering and semantic states for control buttons.
- describe('Rendering', () => {
- it('should render the child action groups and highlight the active pointer mode', () => {
- render(<Control />)
-
- expect(screen.getByRole('button', { name: 'workflow.common.pointerMode' })).toHaveAttribute(
- 'aria-pressed',
- 'true',
- )
- expect(screen.getByRole('button', { name: 'workflow.common.handMode' })).toHaveAttribute(
- 'aria-pressed',
- 'false',
- )
- })
+ it('creates a note candidate attributed to the current user', async () => {
+ const user = userEvent.setup()
+ const { store } = renderControl()
- it('should highlight hand mode when it is active', () => {
- mockStoreState = {
- controlMode: ControlMode.Hand,
- }
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.note.addNote' }))
- render(<Control />)
-
- expect(screen.getByRole('button', { name: 'workflow.common.handMode' })).toHaveAttribute(
- 'aria-pressed',
- 'true',
- )
+ expect(store.getState().candidateNode).toMatchObject({
+ type: CUSTOM_NOTE_NODE,
+ data: expect.objectContaining({ author: 'Ada', showAuthor: true, _isCandidate: true }),
})
})
- // User interactions exposed by the control bar.
- describe('User Interactions', () => {
- it('should trigger the note, mode, and organize handlers', async () => {
- const user = userEvent.setup()
- render(<Control />)
-
- await user.click(screen.getByRole('button', { name: 'workflow.nodes.note.addNote' }))
- await user.click(screen.getByRole('button', { name: 'workflow.common.pointerMode' }))
- await user.click(screen.getByRole('button', { name: 'workflow.common.handMode' }))
- await user.click(screen.getByRole('button', { name: 'workflow.common.commentMode' }))
- await user.click(screen.getByRole('button', { name: 'workflow.panel.organizeBlocks' }))
-
- expect(mockHandleAddNote).toHaveBeenCalledTimes(1)
- expect(mockHandleModePointer).toHaveBeenCalledTimes(1)
- expect(mockHandleModeHand).toHaveBeenCalledTimes(1)
- expect(mockHandleModeComment).toHaveBeenCalledTimes(1)
- expect(mockHandleLayout).toHaveBeenCalledTimes(1)
- })
+ it('starts organizing blocks when the canvas is editable', async () => {
+ const user = userEvent.setup()
+ const { store } = renderControl()
- it('should keep read-only actions focusable without activating them', async () => {
- const user = userEvent.setup()
- mockNodesReadOnly = true
+ await user.click(screen.getByRole('button', { name: 'workflow.panel.organizeBlocks' }))
- render(<Control />)
+ await waitFor(() => expect(store.getState().nodeAnimation).toBe(true))
+ })
- const noteButton = screen.getByRole('button', { name: 'workflow.nodes.note.addNote' })
+ it('keeps read-only editing actions focusable without changing the canvas', async () => {
+ const user = userEvent.setup()
+ const { store } = renderControl({ initialStoreState: { canvasReadOnly: true } })
- expect(noteButton).toHaveAttribute('aria-disabled', 'true')
- await user.tab()
- expect(noteButton).toHaveFocus()
- await user.keyboard('{Enter}')
+ const noteButton = screen.getByRole('button', { name: 'workflow.nodes.note.addNote' })
+ expect(noteButton).toHaveAttribute('aria-disabled', 'true')
+ noteButton.focus()
+ expect(noteButton).toHaveFocus()
+ await user.keyboard('{Enter}')
+ await user.click(getModeButton('handMode'))
+ await user.click(screen.getByRole('button', { name: 'workflow.panel.organizeBlocks' }))
- expect(mockHandleAddNote).not.toHaveBeenCalled()
+ expect(store.getState()).toMatchObject({
+ candidateNode: undefined,
+ controlMode: ControlMode.Pointer,
+ nodeAnimation: false,
})
+ })
- it('should keep comment mode enabled when nodes are read-only', async () => {
- const user = userEvent.setup()
- mockNodesReadOnly = true
- mockCanUseCommentMode = true
-
- render(<Control />)
+ it('still allows comment mode on a read-only canvas', async () => {
+ const user = userEvent.setup()
+ const { store } = renderControl({ initialStoreState: { canvasReadOnly: true } })
- const commentButton = screen.getByRole('button', { name: 'workflow.common.commentMode' })
- expect(commentButton).toBeEnabled()
+ await user.click(getModeButton('commentMode'))
- await user.click(commentButton)
+ expect(store.getState().controlMode).toBe(ControlMode.Comment)
+ })
- expect(mockHandleModeComment).toHaveBeenCalledTimes(1)
+ it('blocks comment mode while a workflow run is in progress', async () => {
+ const user = userEvent.setup()
+ const { store } = renderControl({
+ initialStoreState: {
+ workflowRunningData: baseRunningData({
+ result: { status: WorkflowRunningStatus.Running },
+ }),
+ },
})
- it('should keep blocked comment mode focusable without activating it', async () => {
- const user = userEvent.setup()
- mockCanUseCommentMode = false
+ const commentButton = getModeButton('commentMode')
+ expect(commentButton).toHaveAttribute('aria-disabled', 'true')
+ await user.click(commentButton)
- render(<Control />)
-
- const commentButton = screen.getByRole('button', { name: 'workflow.common.commentMode' })
- expect(commentButton).toHaveAttribute('aria-disabled', 'true')
+ expect(store.getState().controlMode).toBe(ControlMode.Pointer)
+ })
- commentButton.focus()
- expect(commentButton).toHaveFocus()
- await user.keyboard('{Enter}')
+ it('hides comment mode when collaboration is unavailable', () => {
+ renderControl({ collaborationEnabled: false })
- expect(mockHandleModeComment).not.toHaveBeenCalled()
- })
+ expect(
+ screen.queryByRole('button', { name: 'workflow.common.commentMode' }),
+ ).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx
index 1c26faa8828..dd17cdfa050 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx
@@ -9,10 +9,18 @@ import { createStartNode } from '@/app/components/workflow/__tests__/fixtures'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { InputVarType } from '@/app/components/workflow/types'
import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'
+import { useEventEmitterContextContext } from '@/context/event-emitter'
+import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
import ChatWrapper from '../chat-wrapper'
const mockUseChat = vi.hoisted(() => vi.fn())
-const mockUseSubscription = vi.hoisted(() => vi.fn())
+
+let emitWorkflowEvent: ((event: { type: string }) => void) | undefined
+const EmitterProbe = () => {
+ const { eventEmitter } = useEventEmitterContextContext()
+ emitWorkflowEvent = (event) => eventEmitter?.emit(event as never)
+ return null
+}
const mockRequest = vi.hoisted(() => vi.fn())
@@ -130,14 +138,6 @@ vi.mock('@/app/components/base/features/hooks', () => ({
}),
}))
-vi.mock('@/context/event-emitter', () => ({
- useEventEmitterContextContext: () => ({
- eventEmitter: {
- useSubscription: mockUseSubscription,
- },
- }),
-}))
-
const createChatState = (overrides: Record<string, unknown> = {}) => ({
conversationId: 'conversation-1',
chatList: [],
@@ -261,13 +261,16 @@ describe('ChatWrapper', () => {
)
const { store } = renderWorkflowFlowComponent(
- <ChatWrapper
- ref={createChatWrapperRef()}
- showConversationVariableModal={false}
- onConversationModalHide={vi.fn()}
- showInputsFieldsPanel={false}
- onHide={vi.fn()}
- />,
+ <EventEmitterContextProvider>
+ <EmitterProbe />
+ <ChatWrapper
+ ref={createChatWrapperRef()}
+ showConversationVariableModal={false}
+ onConversationModalHide={vi.fn()}
+ showInputsFieldsPanel={false}
+ onHide={vi.fn()}
+ />
+ </EventEmitterContextProvider>,
{
nodes: [
createStartNode({
@@ -361,12 +364,7 @@ describe('ChatWrapper', () => {
})
})
- const subscription = mockUseSubscription.mock.calls[0]?.[0] as (payload: {
- type: string
- }) => void
- act(() => {
- subscription({ type: EVENT_WORKFLOW_STOP })
- })
+ act(() => emitWorkflowEvent?.({ type: EVENT_WORKFLOW_STOP }))
expect(handleStop).toHaveBeenCalledTimes(1)
})
diff --git a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
index 60376a9a2ee..1d96faa9bce 100644
--- a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
@@ -95,21 +95,6 @@ vi.mock('@/service/use-workflow', async (importOriginal) => ({
}),
}))
-vi.mock('../../../hooks/use-DSL', () => ({
- useDSL: () => ({ handleExportDSL: mockHandleExportDSL }),
-}))
-
-vi.mock('../../../hooks/use-workflow-refresh-draft', () => ({
- useWorkflowRefreshDraft: () => ({ handleRefreshWorkflowDraft: mockHandleRefreshWorkflowDraft }),
-}))
-
-vi.mock('../../../hooks/use-workflow-run', () => ({
- useWorkflowRun: () => ({
- handleRestoreFromPublishedWorkflow: mockHandleRestoreFromPublishedWorkflow,
- handleLoadBackupDraft: mockHandleLoadBackupDraft,
- }),
-}))
-
vi.mock('../../../collaboration/core/collaboration-manager', () => ({
collaborationManager: {
emitRestoreIntent: mockEmitRestoreIntent,
@@ -360,7 +345,14 @@ function render(ui: ReactElement) {
const rendered = renderWorkflowComponent(<NuqsTestingAdapter>{ui}</NuqsTestingAdapter>, {
queryClient,
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
- hooksStoreProps: { accessControl: fullWorkflowAccessControl },
+ // Export, draft refresh and restore are provided by the app hooks through the hooks store.
+ hooksStoreProps: {
+ accessControl: fullWorkflowAccessControl,
+ handleExportDSL: mockHandleExportDSL,
+ handleRefreshWorkflowDraft: mockHandleRefreshWorkflowDraft,
+ handleRestoreFromPublishedWorkflow: mockHandleRestoreFromPublishedWorkflow,
+ handleLoadBackupDraft: mockHandleLoadBackupDraft,
+ },
initialStoreState: {
currentVersion: mockCurrentVersion,
isRestoring: true,