Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
test(web): replace HITL owner and store doubles (AP1/AP3/AP11/AP32) (#45152)
Stephen Zhouf9451801ba53
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/human-input-v2/__tests__/use-config.spec.tsindex a43ee312845..06528ab22e2 100644--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/use-config.spec.ts@@ -1,31 +1,13 @@import type { HumanInputV2NodeType } from '../types'-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { useNodes, useStoreApi } from 'reactflow'import { BlockEnum, InputVarType } from '@/app/components/workflow/types'+import { createNode } from '../../../__tests__/fixtures'+import { renderWorkflowCanvasHook } from '../../../__tests__/workflow-test-env'import { createDefaultFormInputByType } from '../../human-input/shared/types'import useHumanInputV2Config from '../use-config'-const setInputs = vi.hoisted(() => vi.fn<(inputs: HumanInputV2NodeType) => void>())-const readOnly = vi.hoisted(() => ({ value: false }))--vi.mock('reactflow', async (importOriginal) => ({- ...(await importOriginal<typeof import('reactflow')>()),- useUpdateNodeInternals: () => vi.fn(),-}))-vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({- useNodesReadOnly: () => ({ nodesReadOnly: readOnly.value }),- useWorkflow: () => ({ handleOutVarRenameChange: vi.fn() }),-}))-vi.mock('@/app/components/workflow/hooks/use-edges-interactions', () => ({- useEdgesInteractions: () => ({- handleEdgeDeleteByDeleteBranch: vi.fn(),- handleEdgeSourceHandleChange: vi.fn(),- }),-}))-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({- default: (_id: string, inputs: HumanInputV2NodeType) => ({ inputs, setInputs }),-}))--const createNode = (): HumanInputV2NodeType => ({+const createData = (): HumanInputV2NodeType => ({title: 'Migration Approval',desc: '',type: BlockEnum.HumanInput,@@ -51,204 +33,128 @@ const createNode = (): HumanInputV2NodeType => ({debug_mode: { enabled: false, channels: [] },})-describe('Human Input V2 form configuration', () => {- beforeEach(() => {- setInputs.mockClear()- readOnly.value = false- })-- it('restores a configured decision field missing from the editor body without replacing its options', () => {- const node = createNode()- const { result } = renderHook(() => useHumanInputV2Config('approval', node))-- expect(result.current.inputs.form_content).toContain('{{#$output.decision#}}')- expect(result.current.inputs.form_content.startsWith(node.form_content)).toBe(true)- expect(result.current.inputs.form_content.match(/\{\{#\$output\.note#\}\}/g)).toHaveLength(1)- expect(result.current.inputs.inputs).toEqual(node.inputs)-- act(() => {- result.current.handleFormContentChange(result.current.inputs.form_content)- })-- expect(setInputs).toHaveBeenCalledWith({- ...node,- form_content: result.current.inputs.form_content,- })- })-- it('keeps a restored field exactly once after saving and reloading the node', () => {- const node = createNode()- const { result, rerender } = renderHook(- ({ payload }) => useHumanInputV2Config('approval', payload),- {- initialProps: { payload: node },- },- )- const restored = result.current.inputs-- rerender({ payload: restored })- rerender({ payload: result.current.inputs })-- expect(result.current.inputs.form_content).toBe(restored.form_content)- expect(result.current.inputs.form_content.match(/\{\{#\$output\.decision#\}\}/g)).toHaveLength(- 1,- )- expect(result.current.inputs.inputs).toEqual(node.inputs)- })-- it('preserves the configured fields when saving another V2 setting', () => {- const node = createNode()- const { result } = renderHook(() => useHumanInputV2Config('approval', node))-- act(() => {- result.current.handleRecipientsChange([{ type: 'all_workspace_contacts' }])- })-- expect(setInputs).toHaveBeenCalledWith({- ...result.current.inputs,- recipients_spec: [{ type: 'all_workspace_contacts' }],- })- expect(node.form_content).not.toContain('{{#$output.decision#}}')- })-- it('does not restore a field again after it is explicitly removed', () => {- const { result, rerender } = renderHook(- ({ payload }) => useHumanInputV2Config('approval', payload),- {- initialProps: { payload: createNode() },- },- )- const restored = result.current.inputs-- act(() => {- result.current.handleFormInputItemRemove('decision')- })-- const removed = setInputs.mock.lastCall?.[0]- if (!removed) throw new Error('Expected the updated node after removing decision')- expect(removed.form_content).not.toContain('{{#$output.decision#}}')- expect(removed.inputs).toEqual([restored.inputs[0]])- rerender({ payload: removed })- expect(result.current.inputs.form_content).toBe(removed.form_content)- })-- it('shows restored fields in readonly mode without saving the repair', () => {- readOnly.value = true- const node = createNode()- const { result } = renderHook(() => useHumanInputV2Config('approval', node))-- expect(result.current.inputs.form_content).toContain('{{#$output.decision#}}')- expect(setInputs).not.toHaveBeenCalled()-- act(() => {- result.current.handleFormContentChange(result.current.inputs.form_content)- })+function setup(data = createData(), readOnly = false) {+ return renderWorkflowCanvasHook(+ () => {+ const node = useNodes<HumanInputV2NodeType>().find((node) => node.id === 'approval')!+ return {+ ...useHumanInputV2Config(node.id, node.data),+ canvas: useStoreApi(),+ }+ },+ {+ nodes: [createNode({ id: 'approval', data })],+ initialStoreState: { canvasReadOnly: readOnly },+ hooksStoreProps: { doSyncWorkflowDraft: async () => null },+ },+ )+}++const saved = (view: ReturnType<typeof setup>) =>+ view.result.current.canvas.getState().getNodes()[0]!.data++it('restores a missing decision once and persists its original options with the body', () => {+ const data = createData()+ const view = setup(data)+ const restored = view.result.current.inputs.form_content+ expect(restored.startsWith(data.form_content)).toBe(true)+ expect(restored.match(/\{\{#\$output\.note#\}\}/g)).toHaveLength(1)+ expect(restored.match(/\{\{#\$output\.decision#\}\}/g)).toHaveLength(1)+ act(() => view.result.current.handleFormContentChange(restored))+ view.rerender()+ expect(saved(view)).toMatchObject({ ...data, form_content: restored })+ expect(view.result.current.inputs.form_content).toBe(restored)+})- expect(setInputs).not.toHaveBeenCalled()+it('preserves restored fields when another V2 setting is saved', () => {+ const view = setup()+ const restored = view.result.current.inputs.form_content+ act(() => view.result.current.handleRecipientsChange([{ type: 'all_workspace_contacts' }]))+ expect(saved(view)).toMatchObject({+ form_content: restored,+ inputs: createData().inputs,+ recipients_spec: [{ type: 'all_workspace_contacts' }],})+})- it.each([- InputVarType.paragraph,- InputVarType.select,- InputVarType.singleFile,- InputVarType.multiFiles,- ])('restores an unreferenced %s field while preserving its type and name', (type) => {- const node = createNode()- const field = createDefaultFormInputByType(type, 'ReviewNote')- node.inputs = [field]- node.form_content = 'Please review this request.'- const { result } = renderHook(() => useHumanInputV2Config('approval', node))-- expect(result.current.inputs.form_content).toBe(- 'Please review this request.\n\n{{#$output.ReviewNote#}}',- )- expect(result.current.inputs.inputs).toEqual([field])- })+it('does not restore a field again after explicit removal', () => {+ const view = setup()+ const note = view.result.current.inputs.inputs[0]+ act(() => view.result.current.handleFormInputItemRemove('decision'))+ view.rerender()+ expect(saved(view).form_content).not.toContain('{{#$output.decision#}}')+ expect(saved(view).inputs).toEqual([note])+ expect(view.result.current.inputs.form_content).toBe(saved(view).form_content)+})- it('preserves the exact body when every configured field is already present', () => {- const node = createNode()- node.form_content += '\nDecision:\n{{#$output.decision#}}\n\n'- const { result } = renderHook(() => useHumanInputV2Config('approval', node))+it('shows restored fields on a readonly canvas without saving the repair', () => {+ const data = createData()+ const view = setup(data, true)+ expect(view.result.current.inputs.form_content).toContain('{{#$output.decision#}}')+ act(() => view.result.current.handleFormContentChange(view.result.current.inputs.form_content))+ expect(saved(view)).toMatchObject(data)+})- expect(result.current.inputs.form_content).toBe(node.form_content)- expect(setInputs).not.toHaveBeenCalled()+it.each([+ InputVarType.paragraph,+ InputVarType.select,+ InputVarType.singleFile,+ InputVarType.multiFiles,+])('restores an unreferenced %s field with its configured type and name', (type) => {+ const field = createDefaultFormInputByType(type, 'ReviewNote')+ const view = setup({+ ...createData(),+ inputs: [field],+ form_content: 'Please review this request.',})+ expect(view.result.current.inputs.form_content).toBe(+ 'Please review this request.\n\n{{#$output.ReviewNote#}}',+ )+ expect(view.result.current.inputs.inputs).toEqual([field])+})- it('keeps keyboard deletion and undo consistent with the field definitions', () => {- const { result, rerender } = renderHook(- ({ payload }) => useHumanInputV2Config('approval', payload),- { initialProps: { payload: createNode() } },- )- const restored = result.current.inputs- const withoutDecision = restored.form_content.replace('{{#$output.decision#}}', '')-- act(() => {- result.current.handleFormContentChange(withoutDecision)- })-- const deleted = setInputs.mock.lastCall?.[0]- if (!deleted) throw new Error('Expected the keyboard deletion to update the node')- expect(deleted.inputs).toEqual([restored.inputs[0]])- rerender({ payload: deleted })- expect(result.current.inputs.form_content).toBe(withoutDecision)-- act(() => {- result.current.handleFormContentChange(restored.form_content)- })+it('preserves the exact body when all configured fields are present', () => {+ const data = createData()+ data.form_content += '\nDecision:\n{{#$output.decision#}}\n\n'+ const view = setup(data)+ expect(view.result.current.inputs.form_content).toBe(data.form_content)+ expect(saved(view)).toMatchObject(data)+})- const undone = setInputs.mock.lastCall?.[0]- if (!undone) throw new Error('Expected undo to restore the node')- expect(undone.inputs).toEqual(restored.inputs)- rerender({ payload: undone })- expect(result.current.inputs.form_content).toBe(restored.form_content)+it('keeps editor deletion and undo consistent with persisted field definitions', () => {+ const view = setup()+ const restored = view.result.current.inputs+ const withoutDecision = restored.form_content.replace('{{#$output.decision#}}', '')+ act(() => view.result.current.handleFormContentChange(withoutDecision))+ expect(saved(view)).toMatchObject({ inputs: [restored.inputs[0]], form_content: withoutDecision })+ expect(view.result.current.inputs.form_content).toBe(withoutDecision)+ act(() => view.result.current.handleFormContentChange(restored.form_content))+ expect(saved(view)).toMatchObject({+ inputs: restored.inputs,+ form_content: restored.form_content,})+})- it('does not revive a deleted field when an existing editor block saves an old field list', () => {- const { result, rerender } = renderHook(- ({ payload }) => useHumanInputV2Config('approval', payload),- { initialProps: { payload: createNode() } },- )- const restored = result.current.inputs- const retainedHandler = result.current.handleFormInputsChange-- act(() => {- result.current.handleFormContentChange(- restored.form_content.replace('{{#$output.decision#}}', ''),- )- })- const deleted = setInputs.mock.lastCall?.[0]- if (!deleted) throw new Error('Expected the field deletion to update the node')- rerender({ payload: deleted })-- const editedNote = {- ...restored.inputs[0]!,- default: { type: 'constant' as const, selector: [], value: 'Edited note' },- }- act(() => {- retainedHandler([editedNote, restored.inputs[1]!])- })-- expect(setInputs.mock.lastCall?.[0].inputs).toEqual([editedNote])- expect(setInputs.mock.lastCall?.[0].form_content).toBe(deleted.form_content)- })+it('does not revive a deleted field when a retained editor callback saves an old field list', () => {+ const view = setup()+ const restored = view.result.current.inputs+ const retainedHandler = view.result.current.handleFormInputsChange+ const deletedBody = restored.form_content.replace('{{#$output.decision#}}', '')+ act(() => view.result.current.handleFormContentChange(deletedBody))+ const editedNote = {+ ...restored.inputs[0]!,+ default: { type: 'constant' as const, selector: [], value: 'Edited note' },+ }+ act(() => retainedHandler([editedNote, restored.inputs[1]!]))+ expect(saved(view)).toMatchObject({ inputs: [editedNote], form_content: deletedBody })+})- it('keeps a newly inserted field after the editor persists its body token', () => {- const { result, rerender } = renderHook(- ({ payload }) => useHumanInputV2Config('approval', payload),- { initialProps: { payload: createNode() } },- )- const existing = result.current.inputs- const added = createDefaultFormInputByType(InputVarType.paragraph, 'ReviewNote')- act(() => {- result.current.handleFormContentChange(`${existing.form_content}\n{{#$output.ReviewNote#}}`)- })- const bodyUpdated = setInputs.mock.lastCall?.[0]- if (!bodyUpdated) throw new Error('Expected the inserted token to update the body')- rerender({ payload: bodyUpdated })- act(() => {- result.current.handleFormInputsChange([...existing.inputs, added])- })- expect(setInputs.mock.lastCall?.[0].inputs).toEqual([...existing.inputs, added])- expect(setInputs.mock.lastCall?.[0].form_content).toContain('{{#$output.ReviewNote#}}')- })+it('keeps a newly inserted field after the editor persists its token', () => {+ const view = setup()+ const existing = view.result.current.inputs+ const added = createDefaultFormInputByType(InputVarType.paragraph, 'ReviewNote')+ const body = `${existing.form_content}\n{{#$output.ReviewNote#}}`+ act(() => view.result.current.handleFormContentChange(body))+ act(() => view.result.current.handleFormInputsChange([...existing.inputs, added]))+ expect(saved(view)).toMatchObject({ inputs: [...existing.inputs, added], form_content: body })})diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/provider.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/provider.spec.tsxindex 27b248cb7f0..4b5eff74d91 100644--- a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/provider.spec.tsx+++ b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/provider.spec.tsx@@ -1,93 +1,41 @@+import type { ReactNode } from 'react'import type { SyncDraftCallback } from '@/app/components/workflow/hooks-store'+import type { Shape as HooksStoreShape } from '@/app/components/workflow/hooks-store/store'import type { HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'import type { Node } from '@/app/components/workflow/types'import { ORPCError } from '@orpc/client'-import { act, render, screen, waitFor } from '@testing-library/react'+import { act, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { use } from 'react'-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { useStoreApi } from 'reactflow'import { createDefaultFormInputByType } from '@/app/components/workflow/nodes/human-input/types'import { BlockEnum, InputVarType } from '@/app/components/workflow/types'+import { seedModelProviderQueries } from '@/test/console/model-provider'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { createEdge, createNode } from '../../../../__tests__/fixtures'+import { renderWorkflowCanvasHook } from '../../../../__tests__/workflow-test-env'+import { useNodeDataUpdate } from '../../../../hooks/use-node-data-update'import { HumanInputMigrationContext } from '../context'import HumanInputMigrationProvider from '../provider'-const runtime = vi.hoisted(() => ({- nodes: [] as Node[],- edges: [] as never[],- releaseEnabled: true,-}))+const runtime = vi.hoisted(() => ({ releaseEnabled: true }))+const postMigration = vi.hoisted(() => vi.fn())vi.mock('@/config', async (importOriginal) => ({...(await importOriginal<typeof import('@/config')>()),get ENABLE_HITL_IM() {return runtime.releaseEnabled},}))-const mocks = vi.hoisted(() => ({- postMigration: vi.fn(),- setNodes: vi.fn(),- doSync: vi.fn(),- saveHistory: vi.fn(),- toastError: vi.fn(),- toastSuccess: vi.fn(),-}))--vi.mock('reactflow', () => ({- useNodes: () => runtime.nodes,- useStoreApi: () => ({- getState: () => ({- getNodes: () => runtime.nodes,- edges: runtime.edges,+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')+ return {+ ...actual,+ consoleClient: withConsoleClientResponses(actual.consoleClient, {+ 'workspaces.current.humanInput.v2.nodeDataMigration.post': postMigration,}),- }),-}))--vi.mock('@/app/components/workflow/hooks/use-collaborative-workflow', () => ({- useCollaborativeWorkflow: () => ({- setNodes: (...args: unknown[]) => mocks.setNodes(...args),- }),-}))--vi.mock('@/app/components/workflow/hooks/use-nodes-meta-data', () => ({- useNodesMetaData: () => ({- nodesMap: {- [BlockEnum.HumanInputV2]: {- metaData: { helpLinkUri: 'https://docs.example/human-input' },- },- },- }),-}))--vi.mock('@/app/components/workflow/hooks/use-nodes-sync-draft', () => ({- useNodesSyncDraft: () => ({- doSyncWorkflowDraft: (...args: unknown[]) => mocks.doSync(...args),- }),-}))--vi.mock('@/app/components/workflow/hooks/use-workflow-history', () => ({- useWorkflowHistory: () => ({ saveStateToHistory: mocks.saveHistory }),- WorkflowHistoryEvent: { HumanInputMigration: 'HumanInputMigration' },-}))--vi.mock('@/service/console', () => ({- consoleClient: {- workspaces: {- current: {- humanInput: {- v2: {- nodeDataMigration: { post: (...args: unknown[]) => mocks.postMigration(...args) },- },- },- },- },- },-}))--vi.mock('@/app/notifications', () => ({- toast: {- error: (...args: unknown[]) => mocks.toastError(...args),- success: (...args: unknown[]) => mocks.toastSuccess(...args),- },-}))+ }+})const createLegacyNode = (unsupported = false,@@ -123,361 +71,266 @@ const PolicyProbe = () => {)}-const renderProvider = (canEdit = true) =>- render(+const migrationResponse = (nodes: Node[]) => ({+ data: nodes+ .filter((node) => node.data.type === BlockEnum.HumanInput)+ .map((node) => ({+ node_id: node.id,+ node_data: {+ title: node.data.title,+ type: 'human-input',+ version: '2',+ form_content: '',+ inputs: 'inputs' in node.data ? node.data.inputs : [],+ user_actions: [],+ timeout: 3,+ timeout_unit: 'day',+ recipients_spec: [{ type: 'initiator' }],+ message_template: { subject: '', body: '' },+ debug_mode: { enabled: false, channels: [] },+ },+ })),+})++function setup({+ nodes = [createLegacyNode()],+ canEdit = true,+ sync = async () => ({ hash: 'saved-draft', updatedAt: 123 }),+}: {+ nodes?: Node[]+ canEdit?: boolean+ sync?: HooksStoreShape['doSyncWorkflowDraft']+} = {}) {+ const edges = nodes.length > 1 ? [createEdge({ source: nodes[0]!.id, target: nodes[1]!.id })] : []+ const { queryClient } = createConsoleQueryWrapper()+ seedModelProviderQueries(queryClient)+ postMigration.mockResolvedValue(migrationResponse(nodes))+ const Wrapper = ({ children }: { children: ReactNode }) => (<HumanInputMigrationProvider canEdit={canEdit}>+ <div>Original workflow canvas</div><PolicyProbe />- </HumanInputMigrationProvider>,+ {children}+ </HumanInputMigrationProvider>)--describe('Human Input migration provider', () => {- beforeEach(() => {- vi.clearAllMocks()- runtime.releaseEnabled = true- runtime.nodes = [createLegacyNode()]- runtime.edges = []- mocks.postMigration.mockImplementation(async () => ({- data: runtime.nodes.map((node) => ({- node_id: node.id,- node_data: {- title: node.data.title,- type: 'human-input',- version: '2',- form_content: '',- inputs: 'inputs' in node.data ? node.data.inputs : [],- user_actions: [],- timeout: 3,- timeout_unit: 'day',- recipients_spec: [{ type: 'initiator' }],- message_template: { subject: '', body: '' },- debug_mode: { enabled: false, channels: [] },- },- })),- }))- mocks.setNodes.mockImplementation((nodes: Node[]) => {- runtime.nodes = nodes- })- mocks.doSync.mockImplementation(- async (_notRefreshWhenSyncError: boolean, callback?: SyncDraftCallback) => {- callback?.onSuccess?.()- callback?.onSettled?.()- },- )+ const view = renderWorkflowCanvasHook(() => ({ canvas: useStoreApi(), ...useNodeDataUpdate() }), {+ nodes,+ edges,+ queryClient,+ wrapper: Wrapper,+ historyStore: { nodes, edges },+ hooksStoreProps: { doSyncWorkflowDraft: sync },})-- it('keeps the original canvas without migration UI or writes when the release gate is off', () => {- runtime.releaseEnabled = false- render(- <HumanInputMigrationProvider canEdit>- <div>Original workflow canvas</div>- </HumanInputMigrationProvider>,- )-- expect(screen.getByText('Original workflow canvas')).toBeInTheDocument()- expect(screen.queryByRole('complementary')).not.toBeInTheDocument()- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()- expect(mocks.postMigration).not.toHaveBeenCalled()- expect(mocks.setNodes).not.toHaveBeenCalled()- expect(mocks.doSync).not.toHaveBeenCalled()+ const graph = () => ({+ nodes: view.result.current.canvas.getState().getNodes(),+ edges: view.result.current.canvas.getState().edges,})+ return { ...view, graph }+}- it('migrates through one shared dialog, syncs once, and derives the completed UI state', async () => {- const user = userEvent.setup()- const view = renderProvider()- expect(screen.getByText('insertion-blocked')).toBeInTheDocument()- expect(- screen.getByRole('complementary', {- name: 'workflow.nodes.humanInputMigration.banner.ariaLabel',- }),- ).toBeInTheDocument()-- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrateNow',- }),- )- await user.click(- screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),- )+const openDialog = async (user: ReturnType<typeof userEvent.setup>) =>+ user.click(+ screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrateNow' }),+ )+const confirmMigration = async (user: ReturnType<typeof userEvent.setup>) => {+ await openDialog(user)+ await user.click(+ screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),+ )+}- await waitFor(() => expect(mocks.doSync).toHaveBeenCalledTimes(1))- expect(mocks.setNodes).toHaveBeenCalledTimes(1)- expect(mocks.postMigration).toHaveBeenCalledTimes(1)- expect(mocks.postMigration).toHaveBeenCalledWith(- expect.objectContaining({- body: { nodes: [expect.objectContaining({ node_id: 'legacy-human-input' })] },- }),- { context: { silent: true } },- )- expect(mocks.saveHistory).toHaveBeenCalledTimes(1)- expect(mocks.toastSuccess).toHaveBeenCalledWith('workflow.nodes.humanInputMigration.success')- expect((runtime.nodes[0]!.data as { version?: unknown }).version).toBe('2')+beforeEach(() => {+ runtime.releaseEnabled = true+ vi.useFakeTimers({ shouldAdvanceTime: true })+})+afterEach(() => {+ vi.clearAllTimers()+ vi.useRealTimers()+})+const newUser = () => userEvent.setup({ advanceTimers: vi.advanceTimersByTime })++it('keeps the original graph without migration UI or requests when the release gate is off', () => {+ runtime.releaseEnabled = false+ const view = setup()+ expect(screen.getByText('Original workflow canvas')).toBeInTheDocument()+ expect(screen.queryByRole('complementary')).not.toBeInTheDocument()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+ expect(view.graph().nodes[0]!.data).toEqual(createLegacyNode().data)+ expect(postMigration).not.toHaveBeenCalled()+})- view.rerender(- <HumanInputMigrationProvider canEdit>- <PolicyProbe />- </HumanInputMigrationProvider>,- )- expect(screen.getByText('insertion-enabled')).toBeInTheDocument()- expect(screen.queryByRole('complementary')).not.toBeInTheDocument()- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+it('migrates the real graph through one shared dialog and updates the insertion policy', async () => {+ const user = newUser()+ const unrelated = createNode({ id: 'unrelated' })+ const view = setup({ nodes: [createLegacyNode(), unrelated] })+ const edges = view.graph().edges+ expect(screen.getByText('insertion-blocked')).toBeInTheDocument()+ expect(+ screen.getByRole('complementary', {+ name: 'workflow.nodes.humanInputMigration.banner.ariaLabel',+ }),+ ).toBeInTheDocument()+ await confirmMigration(user)+ expect(await screen.findByText('insertion-enabled')).toBeInTheDocument()+ expect(view.graph().nodes[0]!.data).toMatchObject({+ version: '2',+ recipients_spec: [{ type: 'initiator' }],})+ expect(view.graph().nodes[0]!.data).not.toHaveProperty('delivery_methods')+ expect(view.graph().nodes[1]!.data).toEqual(unrelated.data)+ expect(view.graph().edges).toEqual(edges)+ expect(postMigration).toHaveBeenCalledExactlyOnceWith(+ {+ body: { nodes: [{ node_id: 'legacy-human-input', node_data: createLegacyNode().data }] },+ },+ { context: { silent: true } },+ )+ expect(screen.queryByRole('complementary')).not.toBeInTheDocument()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+ await act(async () => vi.advanceTimersByTime(500))+})- it('shows the current legacy-node count in the shared confirmation dialog', async () => {- runtime.nodes = [createLegacyNode(false, 'legacy-one'), createLegacyNode(false, 'legacy-two')]- const user = userEvent.setup()- renderProvider()-- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrateNow',- }),- )-- expect(- screen.getByRole('alertdialog', {- name: 'workflow.nodes.humanInputMigration.dialog.title:{"count":2}',- }),- ).toBeInTheDocument()- })+it('shows the current legacy count in the shared confirmation dialog', async () => {+ setup({ nodes: [createLegacyNode(false, 'legacy-one'), createLegacyNode(false, 'legacy-two')] })+ await openDialog(newUser())+ expect(+ screen.getByRole('alertdialog', {+ name: 'workflow.nodes.humanInputMigration.dialog.title:{"count":2}',+ }),+ ).toBeInTheDocument()+})- it('finishes preflight before mutation and reports a node-specific blocker', async () => {- runtime.nodes = [createLegacyNode(true)]- mocks.postMigration.mockRejectedValueOnce(- new ORPCError('BAD_REQUEST', {- status: 400,- data: {- body: {- status: 400,- code: 'hitl_node_data_migration_failure',- message: 'Human Input node-data migration failed.',- blockers: [- {- code: 'invalid-default-value',- node_id: 'legacy-human-input',- node_title: 'Approval',- value: 'default_value',- },- ],- },+it('reports the server preflight blocker without changing the graph', async () => {+ const view = setup({ nodes: [createLegacyNode(true)] })+ const original = view.graph()+ postMigration.mockRejectedValueOnce(+ new ORPCError('BAD_REQUEST', {+ status: 400,+ data: {+ body: {+ status: 400,+ code: 'hitl_node_data_migration_failure',+ message: 'Human Input node-data migration failed.',+ blockers: [+ {+ code: 'invalid-default-value',+ node_id: 'legacy-human-input',+ node_title: 'Approval',+ value: 'default_value',+ },+ ],},- }),- )- const user = userEvent.setup()- renderProvider()- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrateNow',- }),- )- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrate',- }),- )-- expect(await screen.findByRole('alert')).toHaveTextContent('Approval')- expect(screen.getByRole('alert')).toHaveTextContent(- 'workflow.nodes.humanInputMigration.blocker.invalidDefaultValue',- )- expect(mocks.setNodes).not.toHaveBeenCalled()- expect(mocks.doSync).not.toHaveBeenCalled()- expect(mocks.saveHistory).not.toHaveBeenCalled()- expect(mocks.toastSuccess).not.toHaveBeenCalled()- })-- it('migrates a supported select field and enables insertion without an unsupported-field alert', async () => {- const input = createDefaultFormInputByType(InputVarType.select, 'decision')- runtime.nodes = [createLegacyNode(false, 'legacy-human-input', [input])]- const user = userEvent.setup()- const view = renderProvider()- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrateNow',- }),- )- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrate',- }),- )-- await waitFor(() =>- expect(runtime.nodes[0]?.data).toMatchObject({ version: '2', inputs: [input] }),- )- view.rerender(- <HumanInputMigrationProvider canEdit>- <PolicyProbe />- </HumanInputMigrationProvider>,- )- expect(await screen.findByText('insertion-enabled')).toBeInTheDocument()- expect(screen.queryByRole('alert')).not.toBeInTheDocument()- })-- it('locks duplicate confirmation while pending', async () => {- let settleSync: (() => void) | undefined- mocks.doSync.mockImplementation(- (_notRefreshWhenSyncError: boolean, callback?: SyncDraftCallback) =>- new Promise<void>((resolve) => {- settleSync = () => {- callback?.onSuccess?.()- callback?.onSettled?.()- resolve()- }- }),- )- const user = userEvent.setup()- renderProvider()- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrateNow',- }),- )- const confirm = screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrate',- })- await user.dblClick(confirm)-- expect(mocks.setNodes).toHaveBeenCalledTimes(1)- expect(mocks.doSync).toHaveBeenCalledTimes(1)- expect(- screen.getByRole('button', { name: /workflow.nodes.humanInputMigration.action.migrating/ }),- ).toHaveAttribute('aria-disabled', 'true')+ },+ }),+ )+ await confirmMigration(newUser())+ expect(await screen.findByRole('alert')).toHaveTextContent('Approval')+ expect(screen.getByRole('alert')).toHaveTextContent(+ 'workflow.nodes.humanInputMigration.blocker.invalidDefaultValue',+ )+ expect(view.graph()).toEqual(original)+ expect(screen.getByText('insertion-blocked')).toBeInTheDocument()+})- await act(async () => settleSync?.())- await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledTimes(1))- })+it('preserves a supported select field through migration', async () => {+ const input = createDefaultFormInputByType(InputVarType.select, 'decision')+ const view = setup({ nodes: [createLegacyNode(false, 'legacy-human-input', [input])] })+ await confirmMigration(newUser())+ expect(await screen.findByText('insertion-enabled')).toBeInTheDocument()+ expect(view.graph().nodes[0]!.data).toMatchObject({ version: '2', inputs: [input] })+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+})- it('rolls back the complete graph and retains retry guidance after sync failure', async () => {- const originalNode = runtime.nodes[0]!- mocks.doSync.mockImplementation(- async (_notRefreshWhenSyncError: boolean, callback?: SyncDraftCallback) => {- callback?.onError?.()- callback?.onSettled?.()- },- )- const user = userEvent.setup()- renderProvider()- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrateNow',+it('starts only one migration when confirmation is double-clicked during a draft save', async () => {+ let finishSave!: () => void+ const sync = vi.fn(+ () =>+ new Promise<{ hash: string; updatedAt: number }>((resolve) => {+ finishSave = () => resolve({ hash: 'saved', updatedAt: 1 })}),- )- await user.click(- screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),- )+ )+ const view = setup({ sync })+ const user = newUser()+ await openDialog(user)+ await user.dblClick(+ screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),+ )+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+ expect(view.graph().nodes[0]!.data.version).toBe('2')+ expect(postMigration).toHaveBeenCalledTimes(1)+ expect(sync).toHaveBeenCalledTimes(1)+ await act(async () => finishSave())+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+ expect(screen.getByText('insertion-enabled')).toBeInTheDocument()+})+it.each(['failed', 'skipped', 'skipped-without-settled', 'undefined'] as const)(+ 'rolls back the graph and retains retry guidance when saving is %s',+ async (outcome) => {+ const sync = async (_notRefresh?: boolean, callback?: SyncDraftCallback) => {+ if (outcome === 'failed') callback?.onError?.()+ if (outcome !== 'skipped-without-settled') callback?.onSettled?.()+ return outcome === 'undefined' ? undefined : null+ }+ const view = setup({ nodes: [createLegacyNode(), createNode({ id: 'unrelated' })], sync })+ const original = view.graph()+ await confirmMigration(newUser())expect(await screen.findByRole('alert')).toHaveTextContent('workflow.nodes.humanInputMigration.error.sync',)- expect(mocks.setNodes).toHaveBeenCalledTimes(2)- expect(runtime.nodes).toEqual([originalNode])- expect(mocks.saveHistory).not.toHaveBeenCalled()- expect(mocks.toastSuccess).not.toHaveBeenCalled()+ expect(view.graph()).toEqual(original)expect(screen.getByRole('alertdialog')).toBeInTheDocument()+ expect(screen.getByText('insertion-blocked')).toBeInTheDocument()expect(screen.getByText('workflow.nodes.humanInputMigration.banner.description'),).toBeInTheDocument()- })-- it.each([- { result: null, settles: true },- { result: null, settles: false },- { result: undefined, settles: true },- ])(- 'rolls back when draft saving is skipped ($result, settled: $settles)',- async ({ result, settles }) => {- const originalNodes = runtime.nodes- mocks.doSync.mockImplementation(- async (_notRefreshWhenSyncError: boolean, callback?: SyncDraftCallback) => {- if (settles) callback?.onSettled?.()- return result- },- )- const user = userEvent.setup()- renderProvider()- await user.click(- screen.getByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrateNow',- }),- )- await user.click(- screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),- )+ },+)- expect(await screen.findByRole('alert')).toHaveTextContent(- 'workflow.nodes.humanInputMigration.error.sync',- )- expect(mocks.setNodes).toHaveBeenCalledTimes(2)- expect(runtime.nodes).toEqual(originalNodes)- expect(mocks.saveHistory).not.toHaveBeenCalled()- expect(mocks.toastSuccess).not.toHaveBeenCalled()+it('accepts an actual draft result without a success callback', async () => {+ const view = setup({+ sync: async (_notRefresh, callback) => {+ callback?.onSettled?.()+ return { hash: 'saved-draft-hash', updatedAt: 123 }},- )-- it('accepts an actual draft save result even without a success callback', async () => {- mocks.doSync.mockImplementation(- async (_notRefreshWhenSyncError: boolean, callback?: SyncDraftCallback) => {- callback?.onSettled?.()- return { hash: 'saved-draft-hash', updatedAt: 123 }- },- )- const user = userEvent.setup()- renderProvider()- await user.click(- screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrateNow' }),- )- await user.click(- screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),- )-- await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledTimes(1))- expect(mocks.setNodes).toHaveBeenCalledTimes(1)- expect(mocks.saveHistory).toHaveBeenCalledTimes(1)- })-- it('retains new node edits and shows retry guidance when the graph changes during conversion', async () => {- mocks.postMigration.mockImplementationOnce(async () => {- runtime.nodes = [createLegacyNode(false, 'new-node')]- return {- data: [- {- node_id: 'legacy-human-input',- node_data: {- title: 'Approval',- version: '2',- recipients_spec: [{ type: 'initiator' }],- message_template: { subject: '', body: '' },- debug_mode: { channels: [] },- },- },- ],- }- })- const user = userEvent.setup()- renderProvider()- await user.click(- screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrateNow' }),- )- await user.click(- screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),- )- expect(await screen.findByRole('alert')).toHaveTextContent(- 'workflow.nodes.humanInputMigration.error.graphChanged',- )- expect(runtime.nodes[0]?.id).toBe('new-node')- expect(mocks.setNodes).not.toHaveBeenCalled()- expect(mocks.doSync).not.toHaveBeenCalled()- expect(mocks.saveHistory).not.toHaveBeenCalled()})+ await confirmMigration(newUser())+ expect(await screen.findByText('insertion-enabled')).toBeInTheDocument()+ expect(view.graph().nodes[0]!.data.version).toBe('2')+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+})- it('does not offer migration to a user without editing permission', () => {- renderProvider(false)- expect(- screen.queryByRole('button', {- name: 'workflow.nodes.humanInputMigration.action.migrateNow',+it('retains edits made through the real node owner during conversion and requests retry', async () => {+ const view = setup()+ let finishConversion!: () => void+ postMigration.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishConversion = () => resolve(migrationResponse([createLegacyNode()]))}),- ).not.toBeInTheDocument()- expect(mocks.postMigration).not.toHaveBeenCalled()+ )+ await confirmMigration(newUser())+ act(() =>+ view.result.current.handleNodeDataUpdate({+ id: 'legacy-human-input',+ data: { title: 'Edited approval' },+ }),+ )+ await act(async () => finishConversion())+ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'workflow.nodes.humanInputMigration.error.graphChanged',+ )+ expect(view.graph().nodes[0]!.data).toEqual({+ ...createLegacyNode().data,+ title: 'Edited approval',})+ expect(screen.getByText('insertion-blocked')).toBeInTheDocument()+})++it('offers no migration to a user without editing permission', () => {+ const view = setup({ canEdit: false })+ expect(+ screen.queryByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrateNow' }),+ ).not.toBeInTheDocument()+ expect(view.graph().nodes[0]!.data).toEqual(createLegacyNode().data)+ expect(postMigration).not.toHaveBeenCalled()})diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.hitl-v2.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.hitl-v2.spec.tsxindex 39dc6b3fff6..8113ee0d043 100644--- a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.hitl-v2.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.hitl-v2.spec.tsx@@ -1,184 +1,77 @@-import type { ReactNode } from 'react'-import type { UserActionButtonType } from '../../types'-import { render as rtlRender, screen } from '@testing-library/react'+import { act, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'-import { withSelectorKey } from '@/test/i18n-mock'+import { createNode } from '../../../../__tests__/fixtures'+import { renderWorkflowComponent } from '../../../../__tests__/workflow-test-env'import FormContentPreview from '../form-content-preview'-const mockUseTranslation = vi.hoisted(() => vi.fn())-const mockUseStore = vi.hoisted(() => vi.fn())-const mockUseNodes = vi.hoisted(() => vi.fn())-const mockGetButtonStyle = vi.hoisted(() => vi.fn())-const mockPreview = vi.hoisted(() => vi.fn())-const mockSyncDraft = vi.hoisted(() => vi.fn())+const preview = vi.hoisted(() => vi.fn())+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')+ return {+ ...actual,+ consoleClient: withConsoleClientResponses(actual.consoleClient, {+ 'apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.preview.post': preview,+ }),+ }+})-vi.mock('@/app/components/workflow/hooks/use-nodes-sync-draft', () => ({- useNodesSyncDraft: () => ({ doSyncWorkflowDraft: mockSyncDraft }),-}))-vi.mock('@/service/console', () => ({- consoleClient: {- apps: {- byAppId: {- workflows: {- draft: {- humanInput: { nodes: { byNodeId: { form: { preview: { post: mockPreview } } } } },- },- },- },+const props = {+ nodeId: 'node-1',+ content: 'Unsaved local content',+ formInputs: [],+ userActions: [],+ onClose: () => {},+}+const renderPreview = (+ options: Parameters<typeof renderWorkflowComponent>[1] = {},+ readOnly = false,+) =>+ renderWorkflowComponent(<FormContentPreview {...props} readOnly={readOnly} />, {+ ...options,+ initialStoreState: {+ panelWidth: 320,+ nodes: [createNode({ id: 'node-1', data: { title: 'Classifier' } })],},- },-}))--vi.mock('react-i18next', () => ({- useTranslation: () => mockUseTranslation(),-}))--vi.mock('@/app/components/workflow/store', () => ({- useStore: (selector: (state: { panelWidth: number }) => unknown) => mockUseStore(selector),-}))--vi.mock('@/app/components/workflow/store/workflow/use-nodes', () => ({- __esModule: true,- default: () => mockUseNodes(),-}))--vi.mock('@/app/components/base/badge', () => ({- __esModule: true,- default: ({ children }: { children?: ReactNode }) => <div data-testid="badge">{children}</div>,-}))--vi.mock('@/app/components/base/chat/chat/answer/human-input-content/utils', () => ({- getButtonStyle: (...args: unknown[]) => mockGetButtonStyle(...args),-}))--vi.mock('@/app/components/base/markdown', () => ({- Markdown: ({- content,- customComponents,- }: {- content: string- customComponents: {- variable: (props: { node: { properties: { dataPath: string } } }) => ReactNode- section: (props: { node: { properties: { dataName: string } } }) => ReactNode- }- }) => (- <div>- <p>{content}</p>- {customComponents.variable({ node: { properties: { dataPath: '#node-1.answer#' } } })}- {customComponents.section({ node: { properties: { dataName: 'field_1' } } })}- {customComponents.section({ node: { properties: { dataName: 'missing_field' } } })}- </div>- ),-}))--vi.mock('../variable-in-markdown', () => ({- rehypeNotes: vi.fn(),- rehypeVariable: vi.fn(),- Variable: ({ path }: { path: string }) => <div data-testid="variable-path">{path}</div>,- Note: ({- input,- nodeName,- }: {- input: {- type: string- default?: { selector: string[] }- option_source?: { selector: string[] }- }- nodeName: (nodeId: string) => string- }) => (- <div data-testid="note">- {input.default?.selector?.length- ? nodeName(input.default.selector[0]!)- : input.option_source?.selector?.join('.') || input.type}- </div>- ),-}))--const render = (ui: Parameters<typeof rtlRender>[0]) =>- rtlRender(- <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>- {ui}- </EditorResourceScope>,- )--describe('FormContentPreview', () => {- const onClose = vi.fn()-- beforeEach(() => {- vi.clearAllMocks()- mockSyncDraft.mockResolvedValue({})- mockUseTranslation.mockReturnValue({- t: withSelectorKey((key: string) => key),- })- mockUseStore.mockImplementation((selector: (state: { panelWidth: number }) => unknown) =>- selector({ panelWidth: 320 }),- )- mockUseNodes.mockReturnValue([- {- id: 'node-1',- data: { title: 'Classifier' },- },- ])- mockGetButtonStyle.mockImplementation((style: UserActionButtonType) => style.toLowerCase())})- it('loads the V2 preview from the saved workflow and displays server content', async () => {- mockPreview.mockResolvedValue({- form_content: 'Resolved server preview',- inputs: [],- actions: [],- })- render(- <FormContentPreview- nodeId="node-1"- content="Unsaved local content"- formInputs={[]}- userActions={[]}- onClose={onClose}- />,- )- expect(await screen.findByText('Resolved server preview')).toBeInTheDocument()- expect(screen.queryByText('Unsaved local content')).not.toBeInTheDocument()- expect(mockSyncDraft).toHaveBeenCalledOnce()- expect(mockPreview).toHaveBeenCalledWith({- params: { app_id: 'app-1', node_id: 'node-1' },- body: { inputs: {} },- })+it('waits for the saved workflow before displaying the real server markdown', async () => {+ let finishSave!: () => void+ const saving = new Promise<{ hash: string; updatedAt: number }>((resolve) => {+ finishSave = () => resolve({ hash: 'saved-draft', updatedAt: 1 })})-- it('shows a failed server preview and retries without displaying local content as a result', async () => {- const user = userEvent.setup()- mockPreview- .mockRejectedValueOnce(new Error('Server preview failed'))- .mockResolvedValue({ form_content: 'Retried preview', inputs: [], actions: [] })- render(- <FormContentPreview- nodeId="node-1"- content="Local draft"- formInputs={[]}- userActions={[]}- onClose={onClose}- />,- )- expect(await screen.findByText('Server preview failed')).toBeInTheDocument()- expect(screen.queryByText('Local draft')).not.toBeInTheDocument()- await user.click(screen.getByRole('button', { name: 'operation.retry' }))- expect(await screen.findByText('Retried preview')).toBeInTheDocument()+ preview.mockResolvedValue({ form_content: 'Resolved server preview', inputs: [], actions: [] })+ renderPreview({ hooksStoreProps: { doSyncWorkflowDraft: () => saving } })+ expect(screen.getByRole('status')).toHaveTextContent('common.loading')+ expect(preview).not.toHaveBeenCalled()+ expect(screen.queryByText(props.content)).not.toBeInTheDocument()+ await act(async () => finishSave())+ expect(await screen.findByText('Resolved server preview')).toBeInTheDocument()+ expect(screen.queryByText(props.content)).not.toBeInTheDocument()+ expect(preview).toHaveBeenCalledExactlyOnceWith({+ params: { app_id: 'app-1', node_id: 'node-1' },+ body: { inputs: {} },})- it('uses historical props for a read-only V2 preview without fetching the current draft', () => {- render(- <FormContentPreview- nodeId="node-1"- readOnly- content="Historical form content"- formInputs={[]}- userActions={[]}- onClose={onClose}- />,- )- expect(screen.getByText('Historical form content')).toBeInTheDocument()- expect(mockPreview).not.toHaveBeenCalled()- expect(mockSyncDraft).not.toHaveBeenCalled()+})++it('shows a server failure and retries without presenting local content as the result', async () => {+ const user = userEvent.setup()+ preview+ .mockRejectedValueOnce(new Error('Server preview failed'))+ .mockResolvedValue({ form_content: 'Retried preview', inputs: [], actions: [] })+ renderPreview({+ hooksStoreProps: { doSyncWorkflowDraft: async () => ({ hash: 'saved', updatedAt: 1 }) },})+ expect(await screen.findByText('Server preview failed')).toBeInTheDocument()+ expect(screen.queryByText(props.content)).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))+ expect(await screen.findByText('Retried preview')).toBeInTheDocument()+})++it('renders historical readonly content without loading the current draft', async () => {+ const sync = vi.fn()+ renderPreview({ hooksStoreProps: { doSyncWorkflowDraft: sync } }, true)+ expect(await screen.findByText(props.content)).toBeInTheDocument()+ expect(preview).not.toHaveBeenCalled()+ expect(sync).not.toHaveBeenCalled()})diff --git a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-form-content.hitl-v2.spec.ts b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-form-content.hitl-v2.spec.tsindex e02c472ecc0..fd0fa0bab0d 100644--- a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-form-content.hitl-v2.spec.ts+++ b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-form-content.hitl-v2.spec.ts@@ -1,120 +1,93 @@import type { HumanInputV2NodeType } from '../../../human-input-v2/types'-import type { HumanInputNodeType, ParagraphFormInput } from '../../types'-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { useNodes, useStoreApi } from 'reactflow'import { BlockEnum, InputVarType } from '@/app/components/workflow/types'+import { createNode } from '../../../../__tests__/fixtures'+import { renderWorkflowCanvasHook } from '../../../../__tests__/workflow-test-env'+import useHumanInputV2Config from '../../../human-input-v2/use-config'import useHumanInputFormContent from '../../shared/use-form-content'-const mockUseWorkflow = vi.hoisted(() => vi.fn())-const mockUseNodeCrud = vi.hoisted(() => vi.fn())--vi.mock('../../../../hooks/use-workflow', async (importOriginal) => {- const actual = await importOriginal<typeof import('../../../../hooks/use-workflow')>()-- return {- ...actual,- useWorkflow: () => mockUseWorkflow(),- }-})--vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({- __esModule: true,- default: (...args: unknown[]) => mockUseNodeCrud(...args),-}))--const createFormInput = (overrides: Partial<ParagraphFormInput> = {}): ParagraphFormInput => ({- type: InputVarType.paragraph,- output_variable_name: 'old_name',- default: {- selector: [],- type: 'constant',- value: '',- },- ...overrides,-})--const createPayload = (overrides: Partial<HumanInputNodeType> = {}): HumanInputNodeType => ({- title: 'Human Input',- desc: '',- type: BlockEnum.HumanInput,- delivery_methods: [],- form_content: 'Hello {{#$output.old_name#}}',- inputs: [createFormInput()],- user_actions: [],- timeout: 1,- timeout_unit: 'day',- ...overrides,-})--describe('human-input/use-form-content', () => {- const mockSetInputs = vi.fn()- const mockHandleOutVarRenameChange = vi.fn()- let currentInputs = createPayload()-- beforeEach(() => {- vi.clearAllMocks()- currentInputs = createPayload()- mockUseWorkflow.mockReturnValue({- handleOutVarRenameChange: mockHandleOutVarRenameChange,+it.each(['field', 'content'] as const)(+ 'preserves the latest V2 configuration when a retained editor saves %s',+ (change) => {+ const data: HumanInputV2NodeType = {+ title: 'Human Input V2',+ desc: '',+ type: BlockEnum.HumanInput,+ version: '2',+ form_content: 'Hello {{#$output.old_name#}}',+ inputs: [+ {+ type: InputVarType.paragraph,+ output_variable_name: 'old_name',+ default: { selector: [], type: 'constant', value: '' },+ },+ ],+ user_actions: [{ id: 'approve', title: 'Approve', button_style: 'primary' }],+ timeout: 1,+ timeout_unit: 'hour',+ recipients_spec: [{ type: 'initiator' }],+ message_template: { subject: 'Approval', body: 'Please review' },+ debug_mode: { enabled: false, channels: [] },+ }+ const { result } = renderWorkflowCanvasHook(+ () => {+ const node = useNodes<HumanInputV2NodeType>()[0]!+ return {+ editor: useHumanInputFormContent(node.id, node.data),+ config: useHumanInputV2Config(node.id, node.data),+ canvas: useStoreApi(),+ }+ },+ {+ nodes: [createNode({ id: 'human-input-node', data })],+ hooksStoreProps: { doSyncWorkflowDraft: async () => null },+ },+ )+ // Existing Lexical blocks retain these public callbacks while the panel changes.+ const retainedEditor = result.current.editor+ act(() =>+ result.current.config.handleRecipientsChange([+ { type: 'initiator' },+ { type: 'contact', contact_id: 'contact-1' },+ ]),+ )+ act(() =>+ result.current.config.handleUserActionChange(0, {+ id: 'approve',+ title: 'Approve updated',+ button_style: 'primary',+ }),+ )+ act(() => result.current.config.handleTimeoutChange({ timeout: 2, unit: 'hour' }))+ act(() =>+ result.current.config.handleMessageTemplateChange({+ subject: 'Updated approval',+ body: 'Updated message',+ }),+ )+ act(() => result.current.config.handleFormContentChange('Updated body {{#$output.old_name#}}'))+ const nextInputs = [+ {+ ...data.inputs[0]!,+ default: { selector: [], type: 'constant' as const, value: 'Updated default' },+ },+ ]+ act(() => {+ if (change === 'field') retainedEditor.handleFormInputsChange(nextInputs)+ else retainedEditor.handleFormContentChange('Edited body {{#$output.old_name#}}')})- mockUseNodeCrud.mockImplementation(() => ({- inputs: currentInputs,- setInputs: mockSetInputs,- }))- })-- it.each(['field', 'content'] as const)(- 'should preserve the latest V2 configuration when an existing editor saves %s changes',- (change) => {- const initialPayload: HumanInputV2NodeType = {- title: 'Human Input V2',- desc: '',- type: BlockEnum.HumanInput,- version: '2',- form_content: 'Hello {{#$output.old_name#}}',- inputs: [createFormInput()],- user_actions: [{ id: 'approve', title: 'Approve', button_style: 'primary' }],- timeout: 1,- timeout_unit: 'hour',- recipients_spec: [{ type: 'initiator' }],- message_template: { subject: 'Approval', body: 'Please review' },- debug_mode: { enabled: false, channels: [] },- }- mockUseNodeCrud.mockImplementation((_id: string, payload: HumanInputV2NodeType) => ({- inputs: payload,- setInputs: mockSetInputs,- }))- const { result, rerender } = renderHook(- ({ payload }) => useHumanInputFormContent('human-input-node', payload),- { initialProps: { payload: initialPayload } },- )- // Existing Lexical blocks retain these callbacks while the node panel changes.- const editorCallbacks = result.current- const latestPayload: HumanInputV2NodeType = {- ...initialPayload,- recipients_spec: [{ type: 'initiator' }, { type: 'contact', contact_id: 'contact-1' }],- user_actions: [{ id: 'approve', title: 'Approve updated', button_style: 'primary' }],- timeout: 2,- form_content: 'Updated body {{#$output.old_name#}}',- message_template: { subject: 'Updated approval', body: 'Updated message' },- }- rerender({ payload: latestPayload })- const nextInputs = [- createFormInput({- default: { selector: [], type: 'constant', value: 'Updated default' },- }),- ]-- act(() => {- if (change === 'field') editorCallbacks.handleFormInputsChange(nextInputs)- else editorCallbacks.handleFormContentChange('Edited body {{#$output.old_name#}}')- })-- expect(mockSetInputs).toHaveBeenCalledWith({- ...latestPayload,- ...(change === 'field'- ? { inputs: nextInputs }- : { form_content: 'Edited body {{#$output.old_name#}}' }),- })- },- )-})+ expect(result.current.canvas.getState().getNodes()[0]!.data).toMatchObject({+ ...data,+ recipients_spec: [{ type: 'initiator' }, { type: 'contact', contact_id: 'contact-1' }],+ user_actions: [{ id: 'approve', title: 'Approve updated', button_style: 'primary' }],+ timeout: 2,+ message_template: { subject: 'Updated approval', body: 'Updated message' },+ form_content:+ change === 'field'+ ? 'Updated body {{#$output.old_name#}}'+ : 'Edited body {{#$output.old_name#}}',+ inputs: change === 'field' ? nextInputs : data.inputs,+ })+ },+)