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 workflow panel edits through real node owners (#44630)

Stephen Zhou3c031c7f1dbb
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 82f2d58fd45..061e2abddc7 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -5734,11 +5734,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/workflow/nodes/trigger-schedule/components/next-execution-times.tsx": {
"better-tailwindcss/enforce-logical-properties": {
"count": 3
diff --git a/web/app/components/workflow/nodes/__tests__/render-node-panel.tsx b/web/app/components/workflow/nodes/__tests__/render-node-panel.tsx
new file mode 100644
index 00000000000..b136310c897
--- /dev/null
+++ b/web/app/components/workflow/nodes/__tests__/render-node-panel.tsx
@@ -0,0 +1,61 @@
+import type { ComponentType } from 'react'
+import type { ReactFlowInstance } from 'reactflow'
+import type { CommonNodeType, NodePanelProps } from '../../types'
+import { useNodes, useReactFlow } from 'reactflow'
+import { consoleQuery } from '@/service/console'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { seedToolProviders } from '@/test/console/tool-providers'
+import { createNode } from '../../__tests__/fixtures'
+import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
+
+type Options = NonNullable<Parameters<typeof renderWorkflowFlowComponent>[1]> & { nodeId?: string }
+
+// Like the production panel, subscribe to node data so successive edits use the saved graph.
+export function renderNodePanel<T extends CommonNodeType>(
+ Panel: ComponentType<NodePanelProps<T>>,
+ data: T,
+ { nodeId = 'node', nodes, queryClient: suppliedClient, ...options }: Options = {},
+) {
+ const queryClient = createConsoleQueryWrapper({ queryClient: suppliedClient }).queryClient
+ if (!suppliedClient) {
+ seedToolProviders(queryClient, {
+ builtInTools: [],
+ customTools: [],
+ workflowTools: [],
+ mcpTools: [],
+ })
+ queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
+ }
+ seedModelProviderQueries(queryClient)
+ let flow: ReactFlowInstance<T>
+ function LivePanel() {
+ flow = useReactFlow<T>()
+ const node = useNodes<T>().find((node) => node.id === nodeId)
+ return node ? (
+ <Panel
+ id={nodeId}
+ data={node.data}
+ panelProps={{
+ getInputVars: () => [],
+ toVarInputs: () => [],
+ runInputData: {},
+ runInputDataRef: { current: {} },
+ setRunInputData: vi.fn(),
+ runResult: null,
+ }}
+ />
+ ) : null
+ }
+ const rendered = renderWorkflowFlowComponent(<LivePanel />, {
+ resource: { kind: 'snippet', snippetId: 'snippet-1' },
+ ...options,
+ queryClient,
+ nodes: nodes ?? [createNode({ id: nodeId, data })],
+ })
+ return {
+ ...rendered,
+ data: () => flow.getNode(nodeId)!.data,
+ getNode: (id: string) => flow.getNode(id),
+ }
+}
diff --git a/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx
index 5851e9e3f4f..b7dc9fd9315 100644
--- a/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx
@@ -1,22 +1,27 @@
import type { AgentStrategyParameter } from '@dify/contracts/api/console/workspaces/types.gen'
import type { AgentNodeType } from '../types'
-import type useConfig from '../use-config'
-import type { NodePanelProps } from '@/app/components/workflow/types'
-import { zAgentStrategyParameter } from '@dify/contracts/api/console/workspaces/zod.gen'
+import {
+ zAgentProviderResponse,
+ zAgentStrategyParameter,
+} from '@dify/contracts/api/console/workspaces/zod.gen'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { renderWorkflowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum } from '@/app/components/workflow/types'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { seedToolProviders } from '@/test/console/tool-providers'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
+import { VarKindType } from '../../_base/types'
import Panel from '../panel'
+import { createProvider, createStrategy } from './strategy-fixture'
-const mockUseConfig = vi.hoisted(() => vi.fn())
-
-vi.mock('../use-config', () => ({
- __esModule: true,
- default: (...args: unknown[]) => mockUseConfig(...args),
+// Plugin metadata is an external service; the configuration and strategy owners stay real.
+vi.mock('@/service/use-plugins', () => ({
+ useFetchPluginsInMarketPlaceByIds: () => ({ isLoading: false, data: { data: { plugins: [] } } }),
+ useCheckInstalled: () => ({ data: { plugins: [] } }),
}))
+// The strategy picker/form has its own interaction suite; drive its public callbacks here.
vi.mock('../../_base/components/agent-strategy', () => ({
AgentStrategy: (props: {
strategy?: {
@@ -79,7 +84,7 @@ vi.mock('../../_base/components/agent-strategy', () => ({
const createStrategyParam = (overrides: Partial<AgentStrategyParameter> = {}) =>
zAgentStrategyParameter.parse({
name: 'instruction',
- type: FormTypeEnum.any,
+ type: 'string',
required: true,
label: { en_US: 'Instruction' },
help: { en_US: 'Instruction help' },
@@ -93,6 +98,8 @@ const createStrategyParam = (overrides: Partial<AgentStrategyParameter> = {}) =>
})
const createData = (overrides: Partial<AgentNodeType> = {}): AgentNodeType => ({
+ agent_parameters: { instruction: { type: VarKindType.constant, value: 'Plan and answer' } },
+ tool_node_version: '2',
title: 'Agent',
desc: '',
type: BlockEnum.Agent,
@@ -119,158 +126,105 @@ const createData = (overrides: Partial<AgentNodeType> = {}): AgentNodeType => ({
...overrides,
})
-const createConfigResult = (
- overrides: Partial<ReturnType<typeof useConfig>> = {},
-): ReturnType<typeof useConfig> => ({
- readOnly: false,
- inputs: createData(),
- setInputs: vi.fn(),
- handleVarListChange: vi.fn(),
- handleAddVariable: vi.fn(),
- currentStrategy: {
- identity: {
- author: 'provider',
- name: 'react',
- icon: 'icon',
- label: { en_US: 'React Agent' },
- provider: 'provider/agent',
- },
- parameters: [
- createStrategyParam(),
- createStrategyParam({
- name: 'modelParam',
- type: FormTypeEnum.modelSelector,
- required: false,
- }),
- ],
- description: { en_US: 'agent description' },
- output_schema: {},
- features: ['history-messages' as const],
- },
- formData: {
- instruction: 'Plan and answer',
- },
- onFormChange: vi.fn(),
- currentStrategyStatus: {
- plugin: { source: 'marketplace', installed: true },
- isExistInPlugin: true,
- },
- strategyProvider: undefined,
- pluginDetail: undefined,
- availableVars: [],
- availableNodesWithParent: [],
- outputSchema: [
- {
- name: 'summary',
- type: 'String',
- description: 'summary output',
- },
- ],
- handleMemoryChange: vi.fn(),
- isChatflow: true,
- ...overrides,
-})
-
-const panelProps = {} as NodePanelProps<AgentNodeType>['panelProps']
-
-describe('agent/panel', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseConfig.mockReturnValue(createConfigResult())
+const renderPanel = (
+ data = createData(),
+ {
+ readOnly = false,
+ isChatflow = true,
+ features = ['history-messages'] as 'history-messages'[],
+ } = {},
+) => {
+ const { queryClient } = createConsoleQueryWrapper()
+ seedToolProviders(queryClient, {
+ builtInTools: [],
+ customTools: [],
+ workflowTools: [],
+ mcpTools: [],
})
-
- it('renders strategy data, forwards strategy and form updates, and exposes output vars', async () => {
- const user = userEvent.setup()
- const setInputs = vi.fn()
- const onFormChange = vi.fn()
- const handleMemoryChange = vi.fn()
-
- mockUseConfig.mockReturnValue(
- createConfigResult({
- setInputs,
- onFormChange,
- handleMemoryChange,
+ queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
+ for (const [provider, name] of [
+ ['provider/agent', 'react'],
+ ['provider/updated', 'updated'],
+ ]) {
+ queryClient.setQueryData(
+ consoleQuery.workspaces.current.agentProvider.byProviderName.get.queryKey({
+ input: { params: { provider_name: provider! } },
}),
+ zAgentProviderResponse.parse(
+ createProvider([
+ createStrategy({
+ identity: {
+ author: 'provider',
+ name: name!,
+ provider: provider!,
+ label: { en_US: name! },
+ },
+ parameters: [createStrategyParam()],
+ features,
+ }),
+ ]),
+ ),
)
+ }
+ return renderNodePanel(Panel, data, {
+ queryClient,
+ initialStoreState: { canvasReadOnly: readOnly },
+ resource: { kind: 'app', appId: 'app-1', mode: isChatflow ? 'advanced-chat' : 'workflow' },
+ })
+}
- render(<Panel id="agent-node" data={createData()} panelProps={panelProps} />)
-
- await user.click(screen.getByText('workflow.nodes.common.outputVars'))
+describe('agent/panel', () => {
+ it('saves strategy, form and memory updates and exposes output variables', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel()
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
expect(screen.getByText('summary output')).toBeInTheDocument()
expect(screen.getByText('workflow.nodes.agent.outputVars.text')).toBeInTheDocument()
expect(screen.getByText('React Agent')).toBeInTheDocument()
expect(screen.getByRole('textbox', { name: 'Instruction' })).toHaveValue('Plan and answer')
-
await user.click(screen.getByRole('button', { name: 'change-strategy' }))
- const instruction = screen.getByRole('textbox', { name: 'Instruction' }) as HTMLInputElement
+ const instruction = screen.getByRole<HTMLInputElement>('textbox', { name: 'Instruction' })
await user.click(instruction)
instruction.select()
await user.paste('Use the tool')
await user.click(screen.getAllByRole('switch')[1]!)
-
- expect(setInputs).toHaveBeenCalledWith(
- expect.objectContaining({
- agent_strategy_provider_name: 'provider/updated',
- agent_strategy_name: 'updated',
- agent_strategy_label: 'Updated Strategy',
- plugin_unique_identifier: 'provider/updated:1.0.0',
- output_schema: expect.objectContaining({
- properties: expect.objectContaining({
- structured: expect.any(Object),
- }),
- }),
- }),
- )
- expect(onFormChange).toHaveBeenCalledWith({ instruction: 'Use the tool' })
- expect(handleMemoryChange).toHaveBeenCalledWith(
- expect.objectContaining({
- window: { enabled: true, size: 3 },
- query_prompt_template: '',
- }),
- )
+ expect(data()).toMatchObject({
+ agent_strategy_provider_name: 'provider/updated',
+ agent_strategy_name: 'updated',
+ agent_strategy_label: 'Updated Strategy',
+ plugin_unique_identifier: 'provider/updated:1.0.0',
+ output_schema: {
+ properties: { structured: { type: 'string', description: 'structured output' } },
+ },
+ agent_parameters: { instruction: { type: VarKindType.constant, value: 'Use the tool' } },
+ memory: { window: { enabled: true, size: 3 }, query_prompt_template: '' },
+ })
+ expect(screen.getByText('Updated Strategy')).toBeInTheDocument()
+ expect(screen.getByText('structured output')).toBeInTheDocument()
})
it('keeps a saved strategy selected without optional plugin installation metadata', () => {
- const inputs = createData({ plugin_unique_identifier: undefined })
- mockUseConfig.mockReturnValue(createConfigResult({ inputs }))
- render(<Panel id="agent-node" data={inputs} panelProps={panelProps} />)
+ renderPanel(createData({ plugin_unique_identifier: undefined }))
expect(screen.getByText('React Agent')).toBeInTheDocument()
expect(screen.getByRole('textbox', { name: 'Instruction' })).toHaveValue('Plan and answer')
})
it('prevents editing memory in readonly mode', async () => {
const user = userEvent.setup()
- const handleMemoryChange = vi.fn()
- mockUseConfig.mockReturnValue(createConfigResult({ readOnly: true, handleMemoryChange }))
- render(<Panel id="agent-node" data={createData()} panelProps={panelProps} />)
-
+ const { data } = renderPanel(createData(), { readOnly: true })
for (const toggle of screen.getAllByRole('switch')) {
expect(toggle).toHaveAttribute('aria-disabled', 'true')
await user.click(toggle)
}
- expect(handleMemoryChange).not.toHaveBeenCalled()
+ expect(data().memory).toEqual(createData().memory)
})
it.each([
{ isChatflow: false, features: ['history-messages' as const] },
{ isChatflow: true, features: [] },
- ])(
- 'hides memory without chat mode or history support ($isChatflow/$features)',
- ({ isChatflow, features }) => {
- mockUseConfig.mockReturnValue(
- createConfigResult({
- isChatflow,
- currentStrategy: {
- ...createConfigResult().currentStrategy!,
- features,
- },
- }),
- )
-
- render(<Panel id="agent-node" data={createData()} panelProps={panelProps} />)
-
- expect(screen.queryByRole('switch')).not.toBeInTheDocument()
- expect(screen.queryByText('workflow.nodes.common.memory.memory')).not.toBeInTheDocument()
- },
- )
+ ])('hides memory without chat mode or history support ($isChatflow/$features)', (options) => {
+ renderPanel(createData(), options)
+ expect(screen.queryByRole('switch')).not.toBeInTheDocument()
+ expect(screen.queryByText('workflow.nodes.common.memory.memory')).not.toBeInTheDocument()
+ })
})
diff --git a/web/app/components/workflow/nodes/code/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/code/__tests__/panel.spec.tsx
index b995649658f..abb96e9a7d3 100644
--- a/web/app/components/workflow/nodes/code/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/code/__tests__/panel.spec.tsx
@@ -1,18 +1,15 @@
import type { ReactNode } from 'react'
import type { CodeNodeType } from '../types'
-import type useConfig from '../use-config'
-import type { NodePanelProps } from '@/app/components/workflow/types'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
+import { createEdge, createNode } from '../../../__tests__/fixtures'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
import { CodeLanguage } from '../types'
-const mockUseConfig = vi.hoisted(() => vi.fn())
const generatedCode = 'function main(foo, newParam) { return { result: foo } }'
-vi.mock('../use-config', () => ({ default: (...args: unknown[]) => mockUseConfig(...args) }))
-
// The editor owns Monaco and code generation; the panel owns parsing generated code.
vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
default: (props: {
@@ -57,52 +54,15 @@ const createData = (overrides: Partial<CodeNodeType> = {}): CodeNodeType => ({
...overrides,
})
-const createConfig = (
- overrides: Partial<ReturnType<typeof useConfig>> = {},
-): ReturnType<typeof useConfig> => ({
- readOnly: false,
- inputs: createData(),
- outputKeyOrders: ['result'],
- handleCodeAndVarsChange: vi.fn(),
- handleVarListChange: vi.fn(),
- handleAddVariable: vi.fn(),
- handleRemoveVariable: vi.fn(),
- handleSyncFunctionSignature: vi.fn(),
- handleCodeChange: vi.fn(),
- handleCodeLanguageChange: vi.fn(),
- handleVarsChange: vi.fn(),
- handleAddOutputVariable: vi.fn(),
- filterVar: vi.fn(() => true),
- isShowRemoveVarConfirm: false,
- hideRemoveVarConfirm: vi.fn(),
- onRemoveVarConfirm: vi.fn(),
- ...overrides,
-})
-
-const renderPanel = (config = createConfig()) => {
- mockUseConfig.mockReturnValue(config)
- const props: NodePanelProps<CodeNodeType> = {
- id: 'code-node',
- data: config.inputs,
- panelProps: {
- getInputVars: vi.fn(() => []),
- toVarInputs: vi.fn(() => []),
- runInputData: {},
- runInputDataRef: { current: {} },
- setRunInputData: vi.fn(),
- runResult: null,
- },
- }
- render(<Panel {...props} />)
- return config
-}
+const renderPanel = (data = createData(), readOnly = false) =>
+ renderNodePanel(Panel, data, {
+ initialStoreState: { canvasReadOnly: readOnly },
+ })
describe('code panel', () => {
- beforeEach(() => vi.clearAllMocks())
-
it('adds inputs and outputs, synchronizes the signature, and removes outputs by row index', async () => {
const user = userEvent.setup()
- const config = renderPanel()
+ const { data } = renderPanel()
await user.click(
screen.getByRole('button', { name: 'common.operation.add workflow.nodes.code.inputVars' }),
)
@@ -112,52 +72,55 @@ describe('code panel', () => {
await user.click(
screen.getByRole('button', { name: 'common.operation.add workflow.nodes.code.outputVars' }),
)
- const removeButtons = screen.getAllByRole('button', { name: /operation.remove/ })
- await user.click(removeButtons[0]!)
- await user.click(removeButtons[1]!)
- expect(config.handleAddVariable).toHaveBeenCalledOnce()
- expect(config.handleSyncFunctionSignature).toHaveBeenCalledOnce()
- expect(config.handleAddOutputVariable).toHaveBeenCalledOnce()
- expect(config.handleVarListChange).toHaveBeenCalledWith([])
- expect(config.handleRemoveVariable).toHaveBeenCalledWith(0)
+ expect(data().variables).toEqual([
+ createData().variables[0],
+ { variable: '', value_selector: [] },
+ ])
+ expect(data().code).toBe('function main({foo, }) { return { result: foo } }')
+ expect(data().outputs).toEqual({
+ result: { type: VarType.string, children: null },
+ var_2: { type: VarType.string, children: null },
+ })
+ await user.click(screen.getAllByRole('button', { name: /operation.remove/ })[0]!)
+ await user.click(screen.getAllByRole('button', { name: /operation.remove/ })[1]!)
+ expect(data().variables).toEqual([{ variable: '', value_selector: [] }])
+ expect(data().outputs).toEqual({ var_2: { type: VarType.string, children: null } })
})
it('changes the output type through the real type picker', async () => {
const user = userEvent.setup()
- const config = renderPanel()
+ const { data } = renderPanel()
await user.click(screen.getByRole('combobox'))
await user.click(screen.getByRole('option', { name: 'number' }))
- expect(config.handleVarsChange).toHaveBeenCalledWith({
+ expect(data().outputs).toEqual({
result: { type: VarType.number, children: null },
})
})
it('parses generated code while retaining bindings for surviving parameters', async () => {
const user = userEvent.setup()
- const config = renderPanel(
- createConfig({
- inputs: createData({
- variables: [
- { variable: 'foo', value_selector: ['start', 'foo'], value_type: VarType.string },
- { variable: 'removed', value_selector: ['start', 'removed'] },
- ],
- }),
+ const { data } = renderPanel(
+ createData({
+ variables: [
+ { variable: 'foo', value_selector: ['start', 'foo'], value_type: VarType.string },
+ { variable: 'removed', value_selector: ['start', 'removed'] },
+ ],
}),
)
await user.click(screen.getByRole('button', { name: 'Generate code' }))
- expect(config.handleCodeAndVarsChange).toHaveBeenCalledExactlyOnceWith(
- generatedCode,
- [
+ expect(data()).toMatchObject({
+ code: generatedCode,
+ variables: [
{ variable: 'foo', value_selector: ['start', 'foo'], value_type: VarType.string },
{ variable: 'newParam', value_selector: [] },
],
- { result: { type: VarType.string, children: null } },
- )
+ outputs: { result: { type: VarType.string, children: null } },
+ })
})
it('prevents adding outputs or changing the language and variable names while readonly', async () => {
const user = userEvent.setup()
- const config = renderPanel(createConfig({ readOnly: true }))
+ const { data } = renderPanel(createData(), true)
expect(screen.queryByRole('button', { name: /operation.add/ })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /syncFunctionSignature/ })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /operation.remove/ })).not.toBeInTheDocument()
@@ -166,21 +129,36 @@ describe('code panel', () => {
await user.type(screen.getByDisplayValue('result'), 'changed')
await user.click(screen.getByText('JavaScript'))
expect(screen.queryByText('Python3')).not.toBeInTheDocument()
- expect(config.handleVarsChange).not.toHaveBeenCalled()
- expect(config.handleCodeLanguageChange).not.toHaveBeenCalled()
+ expect(data()).toMatchObject(createData())
})
it.each(['confirm', 'cancel'] as const)(
'handles removal %s through the real confirmation dialog',
async (action) => {
const user = userEvent.setup()
- const config = renderPanel(createConfig({ isShowRemoveVarConfirm: true }))
+ const initial = createData()
+ const consumer = createNode({
+ id: 'consumer',
+ data: {
+ type: BlockEnum.TemplateTransform,
+ variables: [{ variable: 'value', value_selector: ['node', 'result'] }],
+ template: '{{ value }}',
+ },
+ })
+ const { data, getNode } = renderNodePanel(Panel, initial, {
+ nodes: [createNode({ id: 'node', data: initial }), consumer],
+ edges: [createEdge({ source: 'node', target: 'consumer' })],
+ })
+ await user.click(screen.getAllByRole('button', { name: /operation.remove/ })[1]!)
+ expect(data().outputs).toEqual(initial.outputs)
await user.click(screen.getByRole('button', { name: `common.operation.${action}` }))
- if (action === 'confirm') expect(config.onRemoveVarConfirm).toHaveBeenCalledOnce()
- else {
- expect(config.hideRemoveVarConfirm).toHaveBeenCalledOnce()
- expect(config.onRemoveVarConfirm).not.toHaveBeenCalled()
- }
+ expect(data().outputs).toEqual(action === 'confirm' ? {} : initial.outputs)
+ expect(getNode('consumer')?.data.variables).toEqual([
+ { variable: 'value', value_selector: action === 'confirm' ? [] : ['node', 'result'] },
+ ])
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.confirm' }),
+ ).not.toBeInTheDocument()
},
)
})
diff --git a/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx
index 2300c2e284b..e883a092d55 100644
--- a/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx
@@ -1,19 +1,11 @@
import type { HttpNodeType } from '../types'
-import type { NodePanelProps } from '@/app/components/workflow/types'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { renderWorkflowFlowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum } from '@/app/components/workflow/types'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
import { AuthorizationType, BodyType, Method } from '../types'
-const mockUseConfig = vi.hoisted(() => vi.fn())
-
-vi.mock('../use-config', () => ({ default: (...args: unknown[]) => mockUseConfig(...args) }))
-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
- default: () => ({ availableVars: [], availableNodesWithParent: [], availableNodes: [] }),
-}))
-
const createData = (overrides: Partial<HttpNodeType> = {}): HttpNodeType => ({
title: 'HTTP Request',
desc: '',
@@ -30,55 +22,23 @@ const createData = (overrides: Partial<HttpNodeType> = {}): HttpNodeType => ({
...overrides,
})
-const panelProps = {} as NodePanelProps<HttpNodeType>['panelProps']
-
-describe('http/panel', () => {
- const handleMethodChange = vi.fn()
- const handleUrlChange = vi.fn()
- const setHeaders = vi.fn()
- const addHeader = vi.fn()
- const setParams = vi.fn()
- const addParam = vi.fn()
- const setBody = vi.fn()
- const setAuthorization = vi.fn()
- const setTimeout = vi.fn()
- const handleCurlImport = vi.fn()
-
- const createConfigResult = (overrides: Record<string, unknown> = {}) => ({
- readOnly: false,
- isDataReady: true,
- inputs: createData({
- authorization: { type: AuthorizationType.apiKey, config: null },
- }),
- handleMethodChange,
- handleUrlChange,
- headers: [{ key: 'accept', value: 'application/json' }],
- setHeaders,
- addHeader,
- params: [{ key: 'page', value: '1' }],
- setParams,
- addParam,
- setBody,
- setAuthorization,
- setTimeout,
- handleCurlImport,
- handleSSLVerifyChange: vi.fn(),
- ...overrides,
- })
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseConfig.mockReturnValue(createConfigResult())
+const renderPanel = (readOnly = false, ready = true) =>
+ renderNodePanel(Panel, createData(), {
+ initialStoreState: {
+ canvasReadOnly: readOnly,
+ nodesDefaultConfigs: ready ? { [BlockEnum.HttpRequest]: createData() } : {},
+ },
})
+describe('http/panel', () => {
it('commits the selected method, body format and timeout from real controls', async () => {
const user = userEvent.setup()
- render(<Panel id="http-node" data={createData()} panelProps={panelProps} />)
+ const { data } = renderPanel()
await user.click(screen.getByText('get'))
await user.click(screen.getByText('POST'))
- expect(handleMethodChange).toHaveBeenCalledExactlyOnceWith(Method.post)
+ expect(data().method).toBe(Method.post)
await user.click(screen.getByRole('radio', { name: 'JSON' }))
- expect(setBody).toHaveBeenCalledExactlyOnceWith({ type: BodyType.json, data: [] })
+ expect(data().body).toMatchObject({ type: BodyType.json })
await user.click(
screen.getByRole('button', { name: 'workflowIntegrations.nodes.http.timeout.title' }),
)
@@ -87,7 +47,11 @@ describe('http/panel', () => {
})
await user.clear(connect)
await user.type(connect, '9')
- expect(setTimeout).toHaveBeenLastCalledWith({ connect: 9, read: 10, write: 15 })
+ expect(data()).toMatchObject({
+ method: Method.post,
+ body: { type: BodyType.json },
+ timeout: { connect: 9, read: 10, write: 15 },
+ })
await user.click(
screen.getByRole('button', { name: 'workflowIntegrations.nodes.http.curl.title' }),
)
@@ -97,22 +61,16 @@ describe('http/panel', () => {
})
it('keeps request controls unavailable until config data is ready', () => {
- mockUseConfig.mockReturnValue(createConfigResult({ isDataReady: false }))
- render(<Panel id="http-node" data={createData()} panelProps={panelProps} />)
+ renderPanel(false, false)
expect(screen.queryByRole('radio', { name: 'JSON' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'workflowIntegrations.nodes.http.curl.title' }),
).not.toBeInTheDocument()
})
- it('blocks request changes when the panel becomes read-only', async () => {
+ it('blocks request changes in a read-only workflow', async () => {
const user = userEvent.setup()
- const { rerender } = render(
- <Panel id="http-node" data={createData()} panelProps={panelProps} />,
- )
- expect(screen.getByRole('button', { name: /authorization.authorization/ })).toBeEnabled()
- mockUseConfig.mockReturnValue(createConfigResult({ readOnly: true }))
- rerender(<Panel id="http-node" data={createData()} panelProps={panelProps} />)
+ const { data } = renderPanel(true)
expect(
screen.queryByRole('button', { name: /authorization.authorization/ }),
).not.toBeInTheDocument()
@@ -131,8 +89,6 @@ describe('http/panel', () => {
})
expect(connect).toHaveAttribute('readonly')
await user.type(connect, '9')
- expect(handleMethodChange).not.toHaveBeenCalled()
- expect(setBody).not.toHaveBeenCalled()
- expect(setTimeout).not.toHaveBeenCalled()
+ expect(data()).toMatchObject(createData())
})
})
diff --git a/web/app/components/workflow/nodes/human-input/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/human-input/__tests__/panel.spec.tsx
index ab843728257..2ea77404da3 100644
--- a/web/app/components/workflow/nodes/human-input/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/__tests__/panel.spec.tsx
@@ -1,22 +1,15 @@
-import type useConfig from '../hooks/use-config'
import type { HumanInputNodeType } from '../types'
-import type { NodePanelProps } from '@/app/components/workflow/types'
-import { screen, within } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import copy from 'copy-to-clipboard'
-import { renderWorkflowFlowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
-import { consoleQuery } from '@/service/console'
-import { createConsoleQueryWrapper } from '@/test/console/query-data'
-import { seedToolProviders } from '@/test/console/tool-providers'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
import { DeliveryMethodType, UserActionButtonType } from '../types'
-const mockUseConfig = vi.hoisted(() => vi.fn())
vi.mock('copy-to-clipboard', () => ({ default: vi.fn() }))
vi.mock('@/app/notifications', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
-vi.mock('../hooks/use-config', () => ({ default: (...args: unknown[]) => mockUseConfig(...args) }))
// Delivery configuration has its own interaction suite; these cases exercise panel-owned controls.
vi.mock('../components/delivery-method', () => ({ default: () => null }))
@@ -75,87 +68,41 @@ const createData = (overrides: Partial<HumanInputNodeType> = {}): HumanInputNode
...overrides,
})
-const createConfigResult = (
- overrides: Partial<ReturnType<typeof useConfig>> = {},
-): ReturnType<typeof useConfig> => ({
- readOnly: false,
- inputs: createData(),
- handleDeliveryMethodChange: vi.fn(),
- handleUserActionAdd: vi.fn(),
- handleUserActionChange: vi.fn(),
- handleUserActionDelete: vi.fn(),
- handleTimeoutChange: vi.fn(),
- handleFormContentChange: vi.fn(),
- handleFormInputsChange: vi.fn(),
- handleFormInputItemRename: vi.fn(),
- handleFormInputItemRemove: vi.fn(),
- editorKey: 1,
- structuredOutputCollapsed: false,
- setStructuredOutputCollapsed: vi.fn(),
- ...overrides,
-})
-
-const renderPanel = (data: HumanInputNodeType = createData()) => {
- const { queryClient } = createConsoleQueryWrapper()
- seedToolProviders(queryClient, {
- builtInTools: [],
- customTools: [],
- workflowTools: [],
- mcpTools: [],
- })
- queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
-
- const props: NodePanelProps<HumanInputNodeType> = {
- id: 'human-input-node',
- data,
- panelProps: {
- getInputVars: vi.fn(() => []),
- toVarInputs: vi.fn(() => []),
- runInputData: {},
- runInputDataRef: { current: {} },
- setRunInputData: vi.fn(),
- runResult: null,
- },
- }
-
- return render(<Panel {...props} />, { queryClient })
-}
+const renderPanel = (data = createData(), readOnly = false) =>
+ renderNodePanel(Panel, data, { initialStoreState: { canvasReadOnly: readOnly } })
describe('human-input/panel', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseConfig.mockReturnValue(createConfigResult())
- })
-
- it('adds an action using the next index and forwards edits and deletion from real controls', async () => {
+ it('persists action additions, edits, deletion and timeout changes', async () => {
const user = userEvent.setup()
- const config = createConfigResult()
- mockUseConfig.mockReturnValue(config)
- renderPanel()
+ const { data } = renderPanel()
await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
- expect(config.handleUserActionAdd).toHaveBeenCalledWith({
- id: 'action_2',
- title: 'Button Text 2',
- button_style: UserActionButtonType.Default,
- })
- const title = screen.getByRole<HTMLInputElement>('textbox', {
- name: 'workflowHumanInput.nodes.humanInput.userActions.buttonTextPlaceholder',
- })
+ expect(data().user_actions).toEqual([
+ createData().user_actions[0],
+ {
+ id: 'action_2',
+ title: 'Button Text 2',
+ button_style: UserActionButtonType.Default,
+ },
+ ])
+ const title = screen.getByDisplayValue<HTMLInputElement>('Approve')
await user.click(title)
title.select()
await user.paste('Accept request')
- expect(config.handleUserActionChange).toHaveBeenCalledWith(0, {
+ expect(data().user_actions[0]).toEqual({
id: 'approve',
title: 'Accept request',
button_style: UserActionButtonType.Primary,
})
- await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
- expect(config.handleUserActionDelete).toHaveBeenCalledWith('approve')
+ await user.click(screen.getAllByRole('button', { name: 'common.operation.delete' })[0]!)
+ expect(data().user_actions).toEqual([
+ { id: 'action_2', title: 'Button Text 2', button_style: UserActionButtonType.Default },
+ ])
+ expect(screen.queryByDisplayValue('Accept request')).not.toBeInTheDocument()
await user.click(
screen.getByRole('radio', { name: 'workflowHumanInput.nodes.humanInput.timeout.hours' }),
)
- expect(config.handleTimeoutChange).toHaveBeenCalledWith({ timeout: 3, unit: 'hour' })
+ expect(data()).toMatchObject({ timeout: 3, timeout_unit: 'hour' })
})
it('copies form content, expands the editor and opens and closes the real preview', async () => {
@@ -185,9 +132,7 @@ describe('human-input/panel', () => {
it('prevents edits in readonly mode', async () => {
const user = userEvent.setup()
- const config = createConfigResult({ readOnly: true })
- mockUseConfig.mockReturnValue(config)
- renderPanel()
+ const { data } = renderPanel(createData(), true)
expect(screen.getByRole('textbox', { name: 'Form content' })).toHaveAttribute('readonly')
expect(screen.getByDisplayValue('Approve')).toBeDisabled()
@@ -200,7 +145,7 @@ describe('human-input/panel', () => {
})
expect(hours).toBeDisabled()
await user.click(hours)
- expect(config.handleTimeoutChange).not.toHaveBeenCalled()
+ expect(data()).toMatchObject(createData())
expect(screen.queryByRole('button', { name: 'common.operation.add' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'common.operation.delete' }),
@@ -214,51 +159,48 @@ describe('human-input/panel', () => {
it('offers the first action when the action list is empty', async () => {
const user = userEvent.setup()
- const config = createConfigResult({ inputs: createData({ user_actions: [] }) })
- mockUseConfig.mockReturnValue(config)
- renderPanel()
+ const { data } = renderPanel(createData({ user_actions: [] }))
expect(
screen.getByText('workflowHumanInput.nodes.humanInput.userActions.emptyTip'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
- expect(config.handleUserActionAdd).toHaveBeenCalledWith({
- id: 'action_1',
- title: 'Button Text 1',
- button_style: UserActionButtonType.Default,
- })
+ expect(data().user_actions).toEqual([
+ {
+ id: 'action_1',
+ title: 'Button Text 1',
+ button_style: UserActionButtonType.Default,
+ },
+ ])
})
- it('exposes file-aware input outputs alongside action metadata', () => {
- mockUseConfig.mockReturnValue(
- createConfigResult({
- inputs: createData({
- inputs: [
- {
- type: InputVarType.singleFile,
- output_variable_name: 'attachment',
- allowed_file_extensions: [],
- allowed_file_types: [],
- allowed_file_upload_methods: [],
- },
- {
- type: InputVarType.multiFiles,
- output_variable_name: 'attachments',
- allowed_file_extensions: [],
- allowed_file_types: [],
- allowed_file_upload_methods: [],
- number_limits: 3,
- },
- ],
- }),
+ it('exposes file-aware input outputs alongside action metadata', async () => {
+ const user = userEvent.setup()
+ renderPanel(
+ createData({
+ inputs: [
+ {
+ type: InputVarType.singleFile,
+ output_variable_name: 'attachment',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ },
+ {
+ type: InputVarType.multiFiles,
+ output_variable_name: 'attachments',
+ allowed_file_extensions: [],
+ allowed_file_types: [],
+ allowed_file_upload_methods: [],
+ number_limits: 3,
+ },
+ ],
}),
)
- renderPanel()
- expect(
- within(screen.getByText('attachment').parentElement!).getByText('file'),
- ).toBeInTheDocument()
- expect(
- within(screen.getByText('attachments').parentElement!).getByText('array[file]'),
- ).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
+ expect(screen.getByText('attachment')).toBeInTheDocument()
+ expect(screen.getByText('file', { exact: true })).toBeInTheDocument()
+ expect(screen.getByText('attachments')).toBeInTheDocument()
+ expect(screen.getByText('array[file]', { exact: true })).toBeInTheDocument()
expect(screen.getByText('__action_id')).toBeInTheDocument()
expect(screen.getByText('__action_value')).toBeInTheDocument()
expect(screen.getByText('__rendered_content')).toBeInTheDocument()
diff --git a/web/app/components/workflow/nodes/knowledge-retrieval-v2/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/knowledge-retrieval-v2/__tests__/panel.spec.tsx
index 6660f3c4e6f..b23fd8dd0bf 100644
--- a/web/app/components/workflow/nodes/knowledge-retrieval-v2/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/knowledge-retrieval-v2/__tests__/panel.spec.tsx
@@ -1,22 +1,15 @@
import type { KnowledgeRetrievalV2NodeType } from '../types'
-import type useConfig from '../use-config'
-import type { PanelProps } from '@/types/workflow'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MetadataFilteringModeEnum } from '@/app/components/workflow/nodes/knowledge-retrieval/types'
import { BlockEnum } from '@/app/components/workflow/types'
-import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
const service = vi.hoisted(() => ({
listMetadata: vi.fn(),
listSpaces: vi.fn(),
}))
-const configState = vi.hoisted(() => ({
- handleSpacesChange: vi.fn(),
- handleTopNChange: vi.fn(),
-}))
-
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses, withConsoleResponses } =
@@ -32,9 +25,6 @@ vi.mock('@/service/console', async (importOriginal) => {
}
})
-// Node configuration editing has its own hook suite; this panel suite renders a given config.
-const useConfigMock = vi.hoisted(() => vi.fn())
-vi.mock('../use-config', () => ({ default: useConfigMock }))
// These children have their own interaction suites and only receive panel-owned values.
vi.mock('../components/add-knowledge-space', () => ({ default: () => null }))
vi.mock('../components/recall-settings', () => ({
@@ -68,15 +58,6 @@ vi.mock(
}),
)
-const panelProps: PanelProps = {
- getInputVars: () => [],
- toVarInputs: () => [],
- runInputData: {},
- runInputDataRef: { current: {} },
- setRunInputData: vi.fn(),
- runResult: undefined,
-}
-
const space = (controlSpaceId: string, name: string, technicalStatus = 'available') => ({
control_space_id: controlSpaceId,
created_at: '2026-08-18T00:00:00Z',
@@ -122,35 +103,7 @@ const nodeData = (
})
function renderPanel(data = nodeData()) {
- useConfigMock.mockReturnValue({
- readOnly: false,
- inputs: data,
- availableNumberNodesWithParent: [],
- availableNumberVars: [],
- availableStringNodesWithParent: [],
- availableStringVars: [],
- filterFileVar: vi.fn(),
- filterStringVar: vi.fn(),
- handleAddCondition: vi.fn(),
- handleMetadataCompletionParamsChange: vi.fn(),
- handleMetadataFilterChange: vi.fn(),
- handleMetadataFilterModeChange: vi.fn(),
- handleMetadataModelChange: vi.fn(),
- handleModeChange: vi.fn(),
- handleNodeKindToggle: vi.fn(),
- handleQueryAttachmentChange: vi.fn(),
- handleQueryVarChange: vi.fn(),
- handleRerankingModelChange: vi.fn(),
- handleRemoveCondition: vi.fn(),
- handleScoreThresholdChange: vi.fn(),
- handleSpacesChange: configState.handleSpacesChange,
- handleTopNChange: configState.handleTopNChange,
- handleToggleConditionLogicalOperator: vi.fn(),
- handleUpdateCondition: vi.fn(),
- } satisfies Partial<ReturnType<typeof useConfig>>)
- return renderWithConsoleQuery(
- <Panel id="knowledge-retrieval-v2-1" data={data} panelProps={panelProps} />,
- )
+ return renderNodePanel(Panel, data)
}
describe('KnowledgeRetrievalV2Panel', () => {
@@ -171,20 +124,22 @@ describe('KnowledgeRetrievalV2Panel', () => {
it('lists the selected spaces by name and routes recall changes to the node config', async () => {
const user = userEvent.setup()
- renderPanel()
+ const { data } = renderPanel()
expect(await screen.findByText('Product docs')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'recall top 10' }))
- expect(configState.handleTopNChange).toHaveBeenCalledWith(12)
+ expect(data().top_n).toBe(12)
+ expect(screen.getByRole('button', { name: 'recall top 12' })).toBeInTheDocument()
})
it('keeps a selected space visible after it becomes unavailable so it can be removed', async () => {
const user = userEvent.setup()
- renderPanel(nodeData({ control_space_ids: ['space-2'] }))
+ const { data } = renderPanel(nodeData({ control_space_ids: ['space-2'] }))
expect(await screen.findByText('Archived docs')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
- expect(configState.handleSpacesChange).toHaveBeenCalledWith([])
+ expect(data().control_space_ids).toEqual([])
+ expect(screen.queryByText('Archived docs')).not.toBeInTheDocument()
})
it('offers only user metadata shared by every selected space with the same type', async () => {
diff --git a/web/app/components/workflow/nodes/knowledge-retrieval-v2/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/knowledge-retrieval-v2/__tests__/use-config.spec.ts
index cc079f44f37..97379d8cba6 100644
--- a/web/app/components/workflow/nodes/knowledge-retrieval-v2/__tests__/use-config.spec.ts
+++ b/web/app/components/workflow/nodes/knowledge-retrieval-v2/__tests__/use-config.spec.ts
@@ -1,6 +1,5 @@
import type { KnowledgeRetrievalV2NodeType } from '../types'
-import { act, renderHook } from '@testing-library/react'
-import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
+import { act } from '@testing-library/react'
import {
ComparisonOperator,
LogicalOperator,
@@ -8,24 +7,9 @@ import {
MetadataFilteringVariableType,
} from '@/app/components/workflow/nodes/knowledge-retrieval/types'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
+import { renderNodeConfig } from '../../__tests__/render-node-config'
import useConfig from '../use-config'
-const mockSetInputs = vi.fn()
-
-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({
- default: vi.fn(),
-}))
-
-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
- default: () => ({ availableNodesWithParent: [], availableVars: [] }),
-}))
-
-vi.mock('../../../hooks/use-workflow', () => ({
- useNodesReadOnly: () => ({ nodesReadOnly: false }),
-}))
-
-const mockUseNodeCrud = vi.mocked(useNodeCrud)
-
const createData = (
overrides: Partial<KnowledgeRetrievalV2NodeType> = {},
): KnowledgeRetrievalV2NodeType => ({
@@ -39,21 +23,24 @@ const createData = (
})
describe('knowledge-retrieval-v2/use-config', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
const setup = (inputs = createData()) => {
- mockUseNodeCrud.mockReturnValue({ inputs, setInputs: mockSetInputs } as never)
- return renderHook(() => useConfig('node-1', inputs))
+ const rendered = renderNodeConfig(useConfig, inputs)
+ return {
+ result: {
+ get current() {
+ return rendered.result.current.config
+ },
+ },
+ data: () => rendered.result.current.flow.getNode('node')!.data,
+ }
}
it('updates the query selector', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() => result.current.handleQueryVarChange(['start', 'question']))
- expect(mockSetInputs).toHaveBeenCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
query_variable_selector: ['start', 'question'],
}),
@@ -61,20 +48,24 @@ describe('knowledge-retrieval-v2/use-config', () => {
})
it('updates an optional image selector and only accepts file variables', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() => result.current.handleQueryAttachmentChange(['start', 'images']))
- expect(mockSetInputs).toHaveBeenCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({ query_attachment_selector: ['start', 'images'] }),
)
- expect(result.current.filterFileVar({ type: VarType.file } as never)).toBe(true)
- expect(result.current.filterFileVar({ type: VarType.arrayFile } as never)).toBe(true)
- expect(result.current.filterFileVar({ type: VarType.string } as never)).toBe(false)
+ expect(result.current.filterFileVar({ variable: 'attachment', type: VarType.file })).toBe(true)
+ expect(result.current.filterFileVar({ variable: 'attachment', type: VarType.arrayFile })).toBe(
+ true,
+ )
+ expect(result.current.filterFileVar({ variable: 'attachment', type: VarType.string })).toBe(
+ false,
+ )
})
it('keeps the selected space summary with the graph configuration', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() =>
result.current.handleSpaceToggle({
@@ -84,7 +75,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
}),
)
- expect(mockSetInputs).toHaveBeenCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
control_space_ids: ['space-1', 'space-2'],
_control_spaces: expect.arrayContaining([
@@ -95,7 +86,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
})
it('replaces the selected spaces in the same order returned by the selector', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() =>
result.current.handleSpacesChange([
@@ -104,7 +95,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
]),
)
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
control_space_ids: ['space-2', 'space-1'],
_control_spaces: [
@@ -116,7 +107,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
})
it('stores a custom rerank model and restores the system default by clearing the override', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() =>
result.current.handleRerankingModelChange({
@@ -124,7 +115,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
model: 'rerank-v3.5',
}),
)
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
reranking_model: {
provider: 'langgenius/cohere/cohere',
@@ -133,53 +124,28 @@ describe('knowledge-retrieval-v2/use-config', () => {
}),
)
- const { result: configuredResult } = setup(
- createData({
- reranking_model: {
- provider: 'langgenius/cohere/cohere',
- model: 'rerank-v3.5',
- },
- }),
- )
- act(() => configuredResult.current.handleRerankingModelChange(undefined))
- expect(mockSetInputs.mock.lastCall?.[0]).toHaveProperty('reranking_model', undefined)
+ act(() => result.current.handleRerankingModelChange(undefined))
+ expect(data()).toHaveProperty('reranking_model', undefined)
})
it('stores a bounded score threshold and supports disabling it', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() => result.current.handleScoreThresholdChange(0.72))
- expect(mockSetInputs).toHaveBeenLastCalledWith(
- expect.objectContaining({ score_threshold: 0.72 }),
- )
+ expect(data()).toEqual(expect.objectContaining({ score_threshold: 0.72 }))
act(() => result.current.handleScoreThresholdChange(null))
- expect(mockSetInputs).toHaveBeenLastCalledWith(
- expect.objectContaining({ score_threshold: null }),
- )
+ expect(data()).toEqual(expect.objectContaining({ score_threshold: null }))
- mockSetInputs.mockClear()
act(() => result.current.handleScoreThresholdChange(1.1))
- expect(mockSetInputs).not.toHaveBeenCalled()
- })
-
- it('removes empty metadata filter collections', () => {
- const { result } = setup(createData({ metadata_filters: { tags: ['policy'] } }))
-
- act(() => result.current.handleMetadataFilterChange('tags', []))
-
- expect(mockSetInputs).toHaveBeenCalledWith(
- expect.not.objectContaining({
- metadata_filters: expect.anything(),
- }),
- )
+ expect(data().score_threshold).toBeNull()
})
it('adds a typed user metadata condition and enables manual filtering', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() => result.current.handleMetadataFilterModeChange(MetadataFilteringModeEnum.manual))
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({ metadata_filtering_mode: MetadataFilteringModeEnum.manual }),
)
@@ -191,7 +157,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
}),
)
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
metadata_filtering_conditions: {
logical_operator: LogicalOperator.and,
@@ -217,7 +183,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
name: 'department',
value: 'finance',
}
- const { result } = setup(
+ const { result, data } = setup(
createData({
metadata_filters: { tags: ['legacy'] },
metadata_filtering_conditions: {
@@ -233,7 +199,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
value: 'legal',
}),
)
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
metadata_filters: { tags: ['legacy'] },
metadata_filtering_conditions: expect.objectContaining({
@@ -243,7 +209,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
)
act(() => result.current.handleToggleConditionLogicalOperator())
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
metadata_filtering_conditions: expect.objectContaining({
logical_operator: LogicalOperator.or,
@@ -269,7 +235,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
name: 'priority',
value: 3,
}
- const { result } = setup(
+ const { result, data } = setup(
createData({
metadata_filtering_conditions: {
conditions: [firstCondition, secondCondition],
@@ -285,7 +251,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
type: MetadataFilteringVariableType.time,
}),
)
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
metadata_filtering_conditions: expect.objectContaining({
conditions: expect.arrayContaining([
@@ -300,39 +266,36 @@ describe('knowledge-retrieval-v2/use-config', () => {
)
act(() => result.current.handleRemoveCondition('condition-1'))
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
metadata_filtering_conditions: expect.objectContaining({
- conditions: [expect.objectContaining({ id: 'condition-2' })],
+ conditions: [
+ expect.objectContaining({ id: 'condition-2' }),
+ expect.objectContaining({ name: 'reviewed_at' }),
+ ],
}),
}),
)
})
- it('enables automatic metadata filtering and normalizes unknown modes to disabled', () => {
- const { result } = setup()
+ it('enables automatic metadata filtering', () => {
+ const { result, data } = setup()
act(() => result.current.handleMetadataFilterModeChange(MetadataFilteringModeEnum.automatic))
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({ metadata_filtering_mode: MetadataFilteringModeEnum.automatic }),
)
-
- act(() => result.current.handleMetadataFilterModeChange('unknown' as MetadataFilteringModeEnum))
-
- expect(mockSetInputs).toHaveBeenLastCalledWith(
- expect.objectContaining({ metadata_filtering_mode: MetadataFilteringModeEnum.disabled }),
- )
})
it('stores the automatic metadata filtering model with default completion params', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() =>
result.current.handleMetadataModelChange({ provider: 'openai', modelId: 'gpt-4o-mini' }),
)
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
metadata_model_config: {
provider: 'openai',
@@ -345,7 +308,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
})
it('keeps tuned completion params when the automatic metadata model changes', () => {
- const { result } = setup(
+ const { result, data } = setup(
createData({
metadata_model_config: {
provider: 'openai',
@@ -364,7 +327,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
}),
)
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
metadata_model_config: {
provider: 'anthropic',
@@ -377,7 +340,7 @@ describe('knowledge-retrieval-v2/use-config', () => {
act(() => result.current.handleMetadataCompletionParamsChange({ temperature: 0.4 }))
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.objectContaining({
metadata_model_config: expect.objectContaining({
completion_params: { temperature: 0.4 },
@@ -387,20 +350,20 @@ describe('knowledge-retrieval-v2/use-config', () => {
})
it('ignores completion params until an automatic metadata model is selected', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() => result.current.handleMetadataCompletionParamsChange({ temperature: 0.4 }))
- expect(mockSetInputs).toHaveBeenLastCalledWith(
+ expect(data()).toEqual(
expect.not.objectContaining({ metadata_model_config: expect.anything() }),
)
})
it('rejects an out-of-range top n in the editor', () => {
- const { result } = setup()
+ const { result, data } = setup()
act(() => result.current.handleTopNChange(101))
- expect(mockSetInputs).not.toHaveBeenCalled()
+ expect(data().top_n).toBe(10)
})
})
diff --git a/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx
index be127204e99..dd29b253484 100644
--- a/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx
@@ -1,23 +1,17 @@
+import type { ToolApiEntity } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ToolNodeType } from '../types'
-import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import type { NodePanelProps } from '@/app/components/workflow/types'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { CollectionType } from '@/app/components/tools/types'
-import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum } from '@/app/components/workflow/types'
import { consoleQuery } from '@/service/console'
import { createConsoleQueryClient } from '@/test/console/query-data'
+import { createToolProviderFixture } from '@/test/console/tool-provider-fixture'
+import { seedToolProviders } from '@/test/console/tool-providers'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
-const mockUseConfig = vi.hoisted(() => vi.fn())
-vi.mock('../hooks/use-config', () => ({ default: (...args: unknown[]) => mockUseConfig(...args) }))
-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
- default: () => ({ availableVars: [], availableNodesWithParent: [] }),
-}))
-
const createNodeData = (overrides: Partial<ToolNodeType> = {}): ToolNodeType => ({
title: 'Google Search',
desc: '',
@@ -32,207 +26,115 @@ const createNodeData = (overrides: Partial<ToolNodeType> = {}): ToolNodeType =>
...overrides,
})
-const createSchemaItem = (variable: string): CredentialFormSchema => ({
- name: variable,
- variable,
- label: { en_US: variable, zh_Hans: variable },
- type: FormTypeEnum.textNumber,
- required: false,
- show_on: [],
+const createTool = (output_schema: ToolApiEntity['output_schema'] = {}): ToolApiEntity => ({
+ name: 'google_search',
+ author: 'Dify',
+ label: { en_US: 'Google Search' },
+ description: { en_US: 'Search' },
+ parameters: [
+ { name: 'count', form: 'llm', type: 'number', label: { en_US: 'count' }, required: false },
+ { name: 'limit', form: 'form', type: 'number', label: { en_US: 'limit' }, required: false },
+ ],
+ output_schema,
})
-
-const renderPanel = (
- data: ToolNodeType = createNodeData(),
- definitions: { name: string; schema: Record<string, unknown> }[] = [],
-) => {
+const renderPanel = ({
+ tool = createTool(),
+ authorized = true,
+ definitions = [] as { name: string; schema: Record<string, unknown> }[],
+} = {}) => {
const queryClient = createConsoleQueryClient()
+ seedToolProviders(queryClient, {
+ builtInTools: [
+ createToolProviderFixture({
+ id: 'google_search',
+ name: 'google_search',
+ allow_delete: true,
+ is_team_authorization: authorized,
+ tools: [tool],
+ }),
+ ],
+ customTools: [],
+ workflowTools: [],
+ mcpTools: [],
+ })
queryClient.setQueryData(
- consoleQuery.spec.schemaDefinitions.get.queryOptions().queryKey,
+ consoleQuery.spec.schemaDefinitions.get.queryKey(),
definitions.map((definition) => ({ label: definition.name, ...definition })),
)
- const props: NodePanelProps<ToolNodeType> = {
- id: 'tool-node-1',
- data,
- panelProps: {
- getInputVars: vi.fn(() => []),
- toVarInputs: vi.fn(() => []),
- runInputData: {},
- runInputDataRef: { current: {} },
- setRunInputData: vi.fn(),
- runResult: null,
- },
- }
-
- return renderWorkflowFlowComponent(<Panel {...props} />, {
- queryClient,
- nodes: [],
- edges: [],
- resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },
- })
+ return renderNodePanel(
+ Panel,
+ createNodeData({
+ tool_parameters: { count: { type: VarKindType.constant, value: 2 } },
+ tool_configurations: { limit: { type: VarKindType.constant, value: 10 } },
+ }),
+ { queryClient, resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' } },
+ )
}
-const createConfigResult = (overrides: Record<string, unknown> = {}) => ({
- readOnly: false,
- inputs: {
- tool_parameters: {},
- tool_configurations: {},
- },
- toolInputVarSchema: [] as CredentialFormSchema[],
- setInputVar: vi.fn(),
- toolSettingSchema: [] as CredentialFormSchema[],
- toolSettingValue: {},
- setToolSettingValue: vi.fn(),
- currCollection: { name: 'google_search' },
- isShowAuthBtn: false,
- isLoading: false,
- outputSchema: [],
- hasObjectOutput: false,
- currTool: { name: 'google_search' },
- ...overrides,
-})
-
describe('ToolPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseConfig.mockReturnValue(createConfigResult())
- })
-
- describe('Loading State', () => {
- it('should render loading when config data is still loading', () => {
- mockUseConfig.mockReturnValue(
- createConfigResult({
- isLoading: true,
- }),
- )
-
- renderPanel()
-
- expect(screen.getByRole('progressbar')).toBeInTheDocument()
- expect(screen.queryByText('workflow.nodes.tool.inputVars')).not.toBeInTheDocument()
- expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
- })
- })
-
- describe('Form Rendering', () => {
- it('edits input and settings independently and collapses the real settings form', async () => {
- const user = userEvent.setup()
- const setInputVar = vi.fn()
- const setToolSettingValue = vi.fn()
- mockUseConfig.mockReturnValue(
- createConfigResult({
- inputs: { tool_parameters: { count: { type: VarKindType.constant, value: 2 } } },
- toolInputVarSchema: [createSchemaItem('count')],
- toolSettingSchema: [createSchemaItem('limit')],
- toolSettingValue: { limit: { type: VarKindType.constant, value: 10 } },
- setInputVar,
- setToolSettingValue,
- }),
- )
- renderPanel()
- const count = screen.getByRole<HTMLInputElement>('textbox', { name: 'count' })
- await user.click(count)
- count.select()
- await user.paste('3')
- expect(setInputVar).toHaveBeenLastCalledWith({
- count: { type: VarKindType.constant, value: 3 },
- })
- expect(setToolSettingValue).not.toHaveBeenCalled()
- const limit = screen.getByRole<HTMLInputElement>('textbox', { name: 'limit' })
- await user.click(limit)
- limit.select()
- await user.paste('20')
- expect(setToolSettingValue).toHaveBeenLastCalledWith({
- limit: { type: VarKindType.constant, value: 20 },
- })
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.tool.settings', expanded: true }),
- )
- expect(screen.queryByRole('textbox', { name: 'limit' })).not.toBeInTheDocument()
- expect(screen.getByRole('textbox', { name: 'count' })).toBeInTheDocument()
+ it('saves input and settings independently and collapses the real settings form', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel()
+ const count = screen.getByRole<HTMLInputElement>('textbox', { name: 'count' })
+ await user.click(count)
+ count.select()
+ await user.paste('3')
+ expect(data()).toMatchObject({
+ tool_parameters: { count: { type: VarKindType.constant, value: 3 } },
+ tool_configurations: { limit: { type: VarKindType.constant, value: 10 } },
})
-
- it('should hide editable forms when the auth button is shown but keep output variables visible', async () => {
- const user = userEvent.setup()
- mockUseConfig.mockReturnValue(
- createConfigResult({
- isShowAuthBtn: true,
- toolInputVarSchema: [createSchemaItem('query')],
- toolSettingSchema: [createSchemaItem('region')],
- }),
- )
-
- renderPanel()
-
- await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
-
- expect(screen.queryByText('workflow.nodes.tool.inputVars')).not.toBeInTheDocument()
- expect(screen.queryByText('workflow.nodes.tool.settings')).not.toBeInTheDocument()
- expect(screen.getByText('text')).toBeInTheDocument()
- expect(screen.getByText('files')).toBeInTheDocument()
- expect(screen.getByText('json')).toBeInTheDocument()
- expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
+ const limit = screen.getByRole<HTMLInputElement>('textbox', { name: 'limit' })
+ await user.click(limit)
+ limit.select()
+ await user.paste('20')
+ expect(data()).toMatchObject({
+ tool_parameters: { count: { type: VarKindType.constant, value: 3 } },
+ tool_configurations: { limit: { type: VarKindType.constant, value: 20 } },
})
+ await user.click(
+ screen.getByRole('button', { name: 'workflow.nodes.tool.settings', expanded: true }),
+ )
+ expect(screen.queryByRole('textbox', { name: 'limit' })).not.toBeInTheDocument()
+ expect(screen.getByRole('textbox', { name: 'count' })).toHaveValue('3')
})
- describe('Output Schema', () => {
- it('should render scalar and structured outputs with matched schema types', async () => {
- const user = userEvent.setup()
- mockUseConfig.mockReturnValue(
- createConfigResult({
- hasObjectOutput: true,
- outputSchema: [
- {
- name: 'summary',
- type: 'String',
- description: 'Summary field',
- value: { type: 'string' },
- },
- {
- name: 'details',
- type: 'Object',
- description: 'Details field',
- value: { type: 'object', properties: {} },
- },
- ],
- }),
- )
-
- renderPanel(createNodeData(), [
- { name: 'qa_structured', schema: { type: 'string' } },
- { name: 'object_structured', schema: { type: 'object', properties: {} } },
- ])
-
- await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
+ it('hides editable forms when authorization is required and keeps output variables visible', async () => {
+ const user = userEvent.setup()
+ renderPanel({ authorized: false })
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
+ expect(screen.queryByText('workflow.nodes.tool.inputVars')).not.toBeInTheDocument()
+ expect(screen.queryByText('workflow.nodes.tool.settings')).not.toBeInTheDocument()
+ for (const name of ['text', 'files', 'json']) expect(screen.getByText(name)).toBeInTheDocument()
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
+ })
- expect(screen.getByText('summary')).toBeInTheDocument()
- expect(screen.getByText('string (qa_structured)')).toBeInTheDocument()
- expect(screen.getByText('Summary field')).toBeInTheDocument()
- expect(screen.getByText('details')).toBeInTheDocument()
- expect(screen.getByText('object (object_structured)')).toBeInTheDocument()
+ it('renders scalar outputs and matches structured outputs to schema definitions', async () => {
+ const user = userEvent.setup()
+ renderPanel({
+ tool: createTool({
+ properties: {
+ summary: { type: 'string', description: 'Summary field' },
+ details: { type: 'object', properties: {} },
+ },
+ }),
+ definitions: [{ name: 'object_structured', schema: { type: 'object', properties: {} } }],
})
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
+ expect(screen.getByText('summary')).toBeInTheDocument()
+ expect(screen.getByText('Summary field')).toBeInTheDocument()
+ expect(screen.getByText('details')).toBeInTheDocument()
+ expect(screen.getByText('object (object_structured)')).toBeInTheDocument()
+ })
- it('should render scalar outputs without a schema suffix when no schema type matches', async () => {
- const user = userEvent.setup()
- mockUseConfig.mockReturnValue(
- createConfigResult({
- outputSchema: [
- {
- name: 'summary',
- type: 'String',
- description: 'Summary field',
- value: { type: 'string' },
- },
- ],
- }),
- )
-
- renderPanel()
-
- await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
-
- expect(screen.getByText('summary')).toBeInTheDocument()
- expect(screen.queryByText(/qa_structured/)).not.toBeInTheDocument()
+ it('renders scalar outputs without a schema suffix when no schema matches', async () => {
+ const user = userEvent.setup()
+ renderPanel({
+ tool: createTool({
+ properties: { summary: { type: 'string', description: 'Summary field' } },
+ }),
})
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
+ expect(screen.getByText('summary')).toBeInTheDocument()
+ expect(screen.queryByText(/qa_structured/)).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx
index 1eee2cb3072..75650ae9a32 100644
--- a/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx
@@ -1,24 +1,17 @@
import type { ScheduleTriggerNodeType } from '../types'
-import type { PanelProps } from '@/types/workflow'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { BlockEnum } from '@/app/components/workflow/types'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
-import useConfig from '../use-config'
-vi.mock('../use-config', () => ({
- default: vi.fn(),
-}))
-
-vi.mock('../components/next-execution-times', () => ({
- default: () => null,
-}))
-
-const mockUseConfig = vi.mocked(useConfig)
+// Execution previews own their scheduling service; this suite edits the persisted schedule.
+vi.mock('../components/next-execution-times', () => ({ default: () => null }))
const createData = (overrides: Partial<ScheduleTriggerNodeType> = {}): ScheduleTriggerNodeType => ({
title: 'Schedule Trigger',
desc: '',
- type: 'trigger-schedule' as ScheduleTriggerNodeType['type'],
+ type: BlockEnum.TriggerSchedule,
mode: 'visual',
frequency: 'daily',
timezone: 'UTC',
@@ -31,248 +24,143 @@ const createData = (overrides: Partial<ScheduleTriggerNodeType> = {}): ScheduleT
...overrides,
})
-const panelProps: PanelProps = {
- getInputVars: vi.fn(() => []),
- toVarInputs: vi.fn(() => []),
- runInputData: {},
- runInputDataRef: { current: {} },
- setRunInputData: vi.fn(),
- runResult: null,
-}
-
-const renderPanel = (id: string, data: ScheduleTriggerNodeType) =>
- render(<Panel id={id} data={data} panelProps={panelProps} />)
+const renderPanel = (data = createData(), readOnly = false) =>
+ renderNodePanel(Panel, data, {
+ initialStoreState: { canvasReadOnly: readOnly },
+ })
+const cronButton = () =>
+ screen.getByRole('button', {
+ name: 'workflowIntegrations.nodes.triggerSchedule.useCronExpression',
+ })
+const frequencyPicker = () => screen.getByRole('combobox', { name: /frequencyLabel/ })
describe('TriggerSchedulePanel', () => {
- const setInputs = vi.fn()
- const handleModeChange = vi.fn()
- const handleFrequencyChange = vi.fn()
- const handleCronExpressionChange = vi.fn()
- const handleWeekdaysChange = vi.fn()
- const handleTimeChange = vi.fn()
- const handleOnMinuteChange = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseConfig.mockReturnValue({
- readOnly: false,
- inputs: createData(),
- setInputs,
- handleModeChange,
- handleFrequencyChange,
- handleCronExpressionChange,
- handleWeekdaysChange,
- handleTimeChange,
- handleOnMinuteChange,
- })
+ it('prevents time editing when the workflow is read only', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel(createData(), true)
+ const trigger = screen.getByRole('button', { name: /11:30 AM.*UTC/ })
+ await user.click(trigger)
+ expect(trigger).toHaveAttribute('aria-disabled', 'true')
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(data()).toMatchObject(createData())
})
- // The panel should wire the visual and cron controls back to the schedule config handlers.
- describe('Panel Wiring', () => {
- it('prevents time editing when the workflow is read only', async () => {
- const user = userEvent.setup()
- mockUseConfig.mockReturnValue({ ...mockUseConfig('node-1', createData()), readOnly: true })
- renderPanel('node-1', createData())
- const trigger = screen.getByRole('button', { name: /11:30 AM.*UTC/ })
- await user.click(trigger)
- expect(trigger).toHaveAttribute('aria-disabled', 'true')
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
- expect(handleTimeChange).not.toHaveBeenCalled()
- })
- it('should render the visual controls and forward their callbacks', async () => {
- const user = userEvent.setup()
- renderPanel('node-1', createData())
-
- await user.click(
- screen.getByRole('button', {
- name: 'workflowIntegrations.nodes.triggerSchedule.useCronExpression',
- }),
- )
- await user.click(screen.getByRole('combobox', { name: /frequencyLabel/ }))
- await user.click(
- screen.getByRole('option', {
- name: 'workflowIntegrations.nodes.triggerSchedule.frequency.weekly',
- }),
- )
- await user.click(screen.getByText('workflow.nodes.triggerSchedule.time', { exact: true }))
- const timeTrigger = screen.getByRole('button', { name: /11:30 AM.*UTC/ })
- expect(timeTrigger).toHaveFocus()
- expect(timeTrigger).toHaveAttribute('aria-expanded', 'false')
- await user.keyboard('{Enter}')
- await user.click(screen.getByRole('option', { name: '2' }))
- await user.click(screen.getByText('45'))
- await user.click(screen.getByText('PM'))
- await user.click(screen.getByRole('button', { name: /operation\.ok/i }))
-
- expect(handleModeChange).toHaveBeenCalledWith('cron')
- expect(handleFrequencyChange).toHaveBeenCalledWith('weekly')
- expect(handleTimeChange).toHaveBeenCalledWith('2:45 PM')
- })
-
- it('updates weekly and monthly selections while preserving other schedule settings', async () => {
- const user = userEvent.setup()
- const config = mockUseConfig('node-1', createData())
- mockUseConfig.mockReturnValue({ ...config, inputs: createData({ frequency: 'weekly' }) })
- const { rerender } = renderPanel('node-1', createData())
- await user.click(screen.getByRole('button', { name: 'Wed' }))
- expect(handleWeekdaysChange).toHaveBeenCalledWith(['mon', 'wed'])
- const monthly = createData({ frequency: 'monthly' })
- mockUseConfig.mockReturnValue({ ...config, inputs: monthly })
- rerender(<Panel id="node-1" data={monthly} panelProps={panelProps} />)
- await user.click(
- screen.getByRole('button', {
- name: 'workflowIntegrations.nodes.triggerSchedule.lastDay',
- pressed: false,
- }),
- )
- expect(setInputs).toHaveBeenCalledWith({
- ...monthly,
- visual_config: { ...monthly.visual_config, monthly_days: [1, 'last'] },
- })
+ it('saves frequency and time before switching to cron mode', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel()
+ await user.click(frequencyPicker())
+ await user.click(
+ screen.getByRole('option', {
+ name: 'workflowIntegrations.nodes.triggerSchedule.frequency.weekly',
+ }),
+ )
+ await user.click(screen.getByText('workflow.nodes.triggerSchedule.time', { exact: true }))
+ const trigger = screen.getByRole('button', { name: /11:30 AM.*UTC/ })
+ expect(trigger).toHaveFocus()
+ await user.keyboard('{Enter}')
+ await user.click(screen.getByRole('option', { name: '2' }))
+ await user.click(screen.getByText('45'))
+ await user.click(screen.getByText('PM'))
+ await user.click(screen.getByRole('button', { name: /operation\.ok/i }))
+ expect(data()).toMatchObject({
+ frequency: 'weekly',
+ visual_config: { time: '2:45 PM' },
+ timezone: 'UTC',
})
+ expect(screen.getByRole('button', { name: /2:45 PM.*UTC/ })).toBeInTheDocument()
+ await user.click(cronButton())
+ expect(data().mode).toBe('cron')
+ expect(
+ screen.getByRole('textbox', { name: 'workflow.nodes.triggerSchedule.cronExpression' }),
+ ).toBeInTheDocument()
+ })
- it('should render cron mode and forward expression changes', () => {
- mockUseConfig.mockReturnValue({
- readOnly: false,
- inputs: createData({ mode: 'cron', frequency: undefined, cron_expression: '0 0 * * *' }),
- setInputs,
- handleModeChange,
- handleFrequencyChange,
- handleCronExpressionChange,
- handleWeekdaysChange,
- handleTimeChange,
- handleOnMinuteChange,
- })
-
- renderPanel('node-3', createData({ mode: 'cron' }))
-
- fireEvent.change(
- screen.getByRole('textbox', {
- name: 'workflow.nodes.triggerSchedule.cronExpression',
- }),
- { target: { value: '*/5 * * * *' } },
- )
-
- expect(handleCronExpressionChange).toHaveBeenCalledWith('*/5 * * * *')
+ it('updates weekly and monthly selections while preserving other schedule settings', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel(createData({ frequency: 'weekly' }))
+ await user.click(screen.getByRole('button', { name: 'Wed' }))
+ expect(data().visual_config?.weekdays).toEqual(['mon', 'wed'])
+ await user.click(frequencyPicker())
+ await user.click(
+ screen.getByRole('option', {
+ name: 'workflowIntegrations.nodes.triggerSchedule.frequency.monthly',
+ }),
+ )
+ await user.click(
+ screen.getByRole('button', {
+ name: 'workflowIntegrations.nodes.triggerSchedule.lastDay',
+ pressed: false,
+ }),
+ )
+ expect(data()).toMatchObject({
+ frequency: 'monthly',
+ timezone: 'UTC',
+ visual_config: { monthly_days: [1, 'last'], time: '11:30 AM' },
})
+ })
- it('should use daily and empty cron defaults when the schedule values are missing', () => {
- mockUseConfig.mockReturnValue({
- readOnly: false,
- inputs: createData({ frequency: undefined }),
- setInputs,
- handleModeChange,
- handleFrequencyChange,
- handleCronExpressionChange,
- handleWeekdaysChange,
- handleTimeChange,
- handleOnMinuteChange,
- })
-
- const { rerender } = renderPanel('node-6', createData({ frequency: undefined }))
- expect(screen.getByRole('combobox', { name: /frequencyLabel/ })).toHaveTextContent(
- 'workflowIntegrations.nodes.triggerSchedule.frequency.daily',
- )
- expect(screen.getByRole('button', { name: /11:30 AM/ })).toBeInTheDocument()
-
- mockUseConfig.mockReturnValue({
- readOnly: false,
- inputs: createData({
- mode: 'cron',
- frequency: undefined,
- cron_expression: undefined as any,
- }),
- setInputs,
- handleModeChange,
- handleFrequencyChange,
- handleCronExpressionChange,
- handleWeekdaysChange,
- handleTimeChange,
- handleOnMinuteChange,
- })
-
- rerender(
- <Panel
- id="node-7"
- data={createData({
- mode: 'cron',
- frequency: undefined,
- cron_expression: undefined as any,
- })}
- panelProps={panelProps}
- />,
- )
- expect(
- screen.getByRole('textbox', {
- name: 'workflow.nodes.triggerSchedule.cronExpression',
- }),
- ).toHaveValue('')
+ it('saves an edited cron expression', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel(
+ createData({ mode: 'cron', frequency: undefined, cron_expression: '0 0 * * *' }),
+ )
+ const input = screen.getByRole('textbox', {
+ name: 'workflow.nodes.triggerSchedule.cronExpression',
})
+ await user.clear(input)
+ await user.type(input, '*/5 * * * *')
+ expect(data().cron_expression).toBe('*/5 * * * *')
+ expect(input).toHaveValue('*/5 * * * *')
+ })
- it('should render the hourly minute selector when the frequency is hourly', async () => {
- const user = userEvent.setup()
- mockUseConfig.mockReturnValue({
- readOnly: false,
- inputs: createData({ frequency: 'hourly' }),
- setInputs,
- handleModeChange,
- handleFrequencyChange,
- handleCronExpressionChange,
- handleWeekdaysChange,
- handleTimeChange,
- handleOnMinuteChange,
- })
+ it('uses daily and empty cron defaults when schedule values are missing', async () => {
+ const user = userEvent.setup()
+ renderPanel(createData({ frequency: undefined }))
+ expect(frequencyPicker()).toHaveTextContent(
+ 'workflowIntegrations.nodes.triggerSchedule.frequency.daily',
+ )
+ expect(screen.getByRole('button', { name: /11:30 AM/ })).toBeInTheDocument()
+ await user.click(cronButton())
+ expect(
+ screen.getByRole('textbox', { name: 'workflow.nodes.triggerSchedule.cronExpression' }),
+ ).toHaveValue('')
+ })
- renderPanel('node-4', createData({ frequency: 'hourly' }))
- screen.getByRole('slider').focus()
- await user.keyboard('{ArrowRight}')
- expect(handleOnMinuteChange).toHaveBeenCalledWith(16, expect.anything())
- })
+ it('saves the hourly minute selected with the slider', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel(createData({ frequency: 'hourly' }))
+ screen.getByRole('slider').focus()
+ await user.keyboard('{ArrowRight}')
+ expect(data().visual_config?.on_minute).toBe(16)
})
+
it.each(['weekly', 'monthly', 'hourly'] as const)(
'disables schedule editing in read-only %s mode',
async (frequency) => {
const user = userEvent.setup()
- mockUseConfig.mockReturnValue({
- ...mockUseConfig('node-1', createData()),
- inputs: createData({ frequency }),
- readOnly: true,
- })
- renderPanel('node-1', createData())
- const mode = screen.getByRole('button', {
- name: 'workflowIntegrations.nodes.triggerSchedule.useCronExpression',
- })
- expect(mode).toBeDisabled()
- await user.click(mode)
- expect(screen.getByRole('combobox', { name: /frequencyLabel/ })).toBeDisabled()
- if (frequency === 'weekly') {
- expect(screen.getByRole('button', { name: 'Wed' })).toBeDisabled()
- await user.click(screen.getByRole('button', { name: 'Wed' }))
- }
- if (frequency === 'monthly') {
- expect(screen.getByRole('button', { name: '2' })).toBeDisabled()
- await user.click(screen.getByRole('button', { name: '2' }))
- }
- if (frequency === 'hourly') expect(screen.getByRole('slider')).toBeDisabled()
- expect(handleModeChange).not.toHaveBeenCalled()
- expect(handleWeekdaysChange).not.toHaveBeenCalled()
- expect(setInputs).not.toHaveBeenCalled()
+ const initial = createData({ frequency })
+ const { data } = renderPanel(initial, true)
+ expect(cronButton()).toBeDisabled()
+ await user.click(cronButton())
+ expect(frequencyPicker()).toBeDisabled()
+ if (frequency !== 'hourly') {
+ const day = screen.getByRole('button', { name: frequency === 'weekly' ? 'Wed' : '2' })
+ expect(day).toBeDisabled()
+ await user.click(day)
+ } else expect(screen.getByRole('slider')).toBeDisabled()
+ expect(data()).toMatchObject(initial)
},
)
it('keeps cron expressions read-only when editing is denied', async () => {
const user = userEvent.setup()
- mockUseConfig.mockReturnValue({
- ...mockUseConfig('node-1', createData()),
- inputs: createData({ mode: 'cron', cron_expression: '0 0 * * *' }),
- readOnly: true,
- })
- renderPanel('node-1', createData())
+ const initial = createData({ mode: 'cron', cron_expression: '0 0 * * *' })
+ const { data } = renderPanel(initial, true)
const input = screen.getByRole('textbox', {
name: 'workflow.nodes.triggerSchedule.cronExpression',
})
await user.type(input, '5')
expect(input).toHaveValue('0 0 * * *')
- expect(handleCronExpressionChange).not.toHaveBeenCalled()
+ expect(data()).toMatchObject(initial)
})
})
diff --git a/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
index a7da0ddfc1d..d8ca974e96f 100644
--- a/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
@@ -1,78 +1,34 @@
import type { WebhookTriggerNodeType } from '../types'
-import type { NodePanelProps } from '@/app/components/workflow/types'
-import type { PanelProps } from '@/types/workflow'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
-const {
- mockHandleStatusCodeChange,
- mockGenerateWebhookUrl,
- mockHandleMethodChange,
- mockHandleContentTypeChange,
- mockHandleHeadersChange,
- mockHandleParamsChange,
- mockHandleBodyChange,
- mockHandleResponseBodyChange,
-} = vi.hoisted(() => ({
- mockHandleStatusCodeChange: vi.fn(),
- mockGenerateWebhookUrl: vi.fn(),
- mockHandleMethodChange: vi.fn(),
- mockHandleContentTypeChange: vi.fn(),
- mockHandleHeadersChange: vi.fn(),
- mockHandleParamsChange: vi.fn(),
- mockHandleBodyChange: vi.fn(),
- mockHandleResponseBodyChange: vi.fn(),
-}))
-
-const mockConfigState: {
- readOnly: boolean
- inputs: Pick<
- WebhookTriggerNodeType,
- | 'method'
- | 'webhook_url'
- | 'webhook_debug_url'
- | 'content_type'
- | 'headers'
- | 'params'
- | 'body'
- | 'status_code'
- | 'response_body'
- | 'variables'
- >
-} = {
- readOnly: false,
- inputs: {
- method: 'POST',
- webhook_url: 'https://example.com/webhook',
- webhook_debug_url: '',
- content_type: 'application/json',
- headers: [],
- params: [],
- body: [],
- status_code: 200,
- response_body: 'ok',
- variables: [],
- },
-}
-
-vi.mock('../use-config', () => ({
- DEFAULT_STATUS_CODE: 200,
- MAX_STATUS_CODE: 399,
- useConfig: () => ({
- readOnly: mockConfigState.readOnly,
- inputs: mockConfigState.inputs,
- handleMethodChange: mockHandleMethodChange,
- handleContentTypeChange: mockHandleContentTypeChange,
- handleHeadersChange: mockHandleHeadersChange,
- handleParamsChange: mockHandleParamsChange,
- handleBodyChange: mockHandleBodyChange,
- handleStatusCodeChange: mockHandleStatusCodeChange,
- handleResponseBodyChange: mockHandleResponseBodyChange,
- generateWebhookUrl: mockGenerateWebhookUrl,
- }),
-}))
+const request = vi.hoisted(() => vi.fn())
+vi.mock('@/service/console/browser', () => ({ consoleBrowserLink: { call: request } }))
+const createData = (overrides: Partial<WebhookTriggerNodeType> = {}): WebhookTriggerNodeType => ({
+ title: 'Webhook',
+ desc: 'Webhook',
+ type: BlockEnum.TriggerWebhook,
+ method: 'POST',
+ webhook_url: 'https://example.com/webhook',
+ webhook_debug_url: '',
+ content_type: 'application/json',
+ headers: [],
+ params: [],
+ body: [],
+ async_mode: false,
+ status_code: 200,
+ response_body: 'ok',
+ variables: [],
+ ...overrides,
+})
+const renderPanel = (data = createData(), readOnly = false) =>
+ renderNodePanel(Panel, data, {
+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
+ initialStoreState: { canvasReadOnly: readOnly },
+ })
const getStatusCodeInput = () =>
screen.getByRole('textbox', {
@@ -80,93 +36,59 @@ const getStatusCodeInput = () =>
})
describe('WebhookTriggerPanel', () => {
- const panelProps: NodePanelProps<WebhookTriggerNodeType> = {
- id: 'node-1',
- data: {
- title: 'Webhook',
- desc: 'Webhook',
- type: BlockEnum.TriggerWebhook,
- method: 'POST',
- content_type: 'application/json',
- headers: [],
- params: [],
- body: [],
- async_mode: false,
- status_code: 200,
- response_body: 'ok',
- variables: [],
- },
- panelProps: {} as PanelProps,
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockConfigState.readOnly = false
- mockConfigState.inputs = {
- method: 'POST',
- webhook_url: 'https://example.com/webhook',
- webhook_debug_url: '',
- content_type: 'application/json',
- headers: [],
- params: [],
- body: [],
- status_code: 200,
- response_body: 'ok',
- variables: [],
- }
- })
+ beforeEach(() => request.mockReset())
describe('Rendering', () => {
it('should render the real panel fields without generating a new webhook url when one already exists', () => {
- render(<Panel {...panelProps} />)
+ renderPanel()
expect(screen.getByDisplayValue('https://example.com/webhook')).toBeInTheDocument()
expect(screen.getAllByText('application/json')[0]).toBeInTheDocument()
expect(screen.getByDisplayValue('ok')).toBeInTheDocument()
- expect(mockGenerateWebhookUrl).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
})
it('should request a webhook url when the node is writable and missing one', async () => {
- mockConfigState.inputs = {
- ...mockConfigState.inputs,
- webhook_url: '',
- }
-
- render(<Panel {...panelProps} />)
-
- await waitFor(() => {
- expect(mockGenerateWebhookUrl).toHaveBeenCalledTimes(1)
+ request.mockResolvedValue({
+ webhook_url: 'https://example.com/generated',
+ webhook_debug_url: 'https://example.com/debug',
})
+ const { data } = renderPanel(createData({ webhook_url: '' }))
+ expect(await screen.findByDisplayValue('https://example.com/generated')).toBeInTheDocument()
+ expect(data().webhook_url).toBe('https://example.com/generated')
+ expect(request).toHaveBeenCalledWith(
+ ['apps', 'byAppId', 'workflows', 'triggers', 'webhook', 'get'],
+ { params: { app_id: 'app-1' }, query: { node_id: 'node' } },
+ expect.any(Object),
+ )
})
})
describe('Status Code Input', () => {
- it('should update the status code when users enter a parseable value', () => {
- render(<Panel {...panelProps} />)
-
- fireEvent.change(getStatusCodeInput(), { target: { value: '201' } })
-
- expect(mockHandleStatusCodeChange).toHaveBeenCalledWith(201)
+ it('saves a parseable status code', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel()
+ await user.clear(getStatusCodeInput())
+ await user.type(getStatusCodeInput(), '201')
+ expect(data().status_code).toBe(201)
})
- it('should ignore clear changes until the value is committed', () => {
- render(<Panel {...panelProps} />)
-
+ it('keeps the saved code while empty and restores the default on blur', async () => {
+ const user = userEvent.setup()
+ const { data } = renderPanel(createData({ status_code: 201 }))
const input = getStatusCodeInput()
- fireEvent.change(input, { target: { value: '' } })
-
- expect(mockHandleStatusCodeChange).not.toHaveBeenCalled()
-
- fireEvent.blur(input)
-
- expect(mockHandleStatusCodeChange).toHaveBeenCalledWith(200)
+ await user.clear(input)
+ expect(data().status_code).toBe(201)
+ await user.tab()
+ expect(data().status_code).toBe(200)
+ expect(input).toHaveValue('200')
})
})
describe('Interactions', () => {
it('copies the labeled readonly webhook URL without editing it', async () => {
const user = userEvent.setup()
- render(<Panel {...panelProps} />)
+ renderPanel()
const input = screen.getByRole('textbox', {
name: 'workflowIntegrations.nodes.triggerWebhook.webhookUrl',
})
@@ -184,18 +106,12 @@ describe('WebhookTriggerPanel', () => {
it('should handle method, content type, table, and response actions', async () => {
const user = userEvent.setup()
- render(<Panel {...panelProps} />)
+ const { data } = renderPanel()
await user.click(
screen.getByRole('combobox', { name: 'workflowIntegrations.nodes.triggerWebhook.method' }),
)
await user.click(await screen.findByRole('option', { name: 'GET' }))
- await user.click(
- screen.getByRole('combobox', {
- name: 'workflowIntegrations.nodes.triggerWebhook.contentType',
- }),
- )
- await user.click(await screen.findByRole('option', { name: 'text/plain' }))
const [query, header, body] = screen.getAllByRole('textbox', {
name: 'workflowIntegrations.nodes.triggerWebhook.varName',
})
@@ -210,31 +126,35 @@ describe('WebhookTriggerPanel', () => {
responseBody.select()
await user.paste('updated body')
- expect(mockHandleMethodChange).toHaveBeenCalledWith('GET')
- expect(mockHandleContentTypeChange).toHaveBeenCalledWith('text/plain')
- expect(mockHandleParamsChange).toHaveBeenCalledWith([
- { name: 'search', type: VarType.string, required: false },
- ])
- expect(mockHandleHeadersChange).toHaveBeenCalledWith([
- { name: 'Authorization', required: false },
- ])
- expect(mockHandleBodyChange).toHaveBeenCalledWith([
- { name: 'message', type: VarType.string, required: false },
- ])
- expect(mockHandleResponseBodyChange).toHaveBeenCalledWith('updated body')
+ expect(data()).toMatchObject({
+ method: 'GET',
+ params: [{ name: 'search', type: VarType.string, required: false }],
+ headers: [{ name: 'Authorization', required: false }],
+ body: [{ name: 'message', type: VarType.string, required: false }],
+ response_body: 'updated body',
+ })
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'workflowIntegrations.nodes.triggerWebhook.contentType',
+ }),
+ )
+ await user.click(await screen.findByRole('option', { name: 'text/plain' }))
+ expect(data()).toMatchObject({
+ content_type: 'text/plain',
+ body: [],
+ response_body: 'updated body',
+ })
})
it('prevents configuration changes and URL generation in readonly mode', async () => {
const user = userEvent.setup()
- mockConfigState.readOnly = true
- mockConfigState.inputs = {
- ...mockConfigState.inputs,
+ const initial = createData({
webhook_url: '',
headers: [{ name: 'Authorization', required: true }],
params: [{ name: 'search', type: VarType.string, required: false }],
body: [{ name: 'message', type: VarType.string, required: false }],
- }
- render(<Panel {...panelProps} />)
+ })
+ const { data } = renderPanel(initial, true)
for (const input of screen.getAllByRole('textbox', {
name: 'workflowIntegrations.nodes.triggerWebhook.varName',
@@ -246,20 +166,13 @@ describe('WebhookTriggerPanel', () => {
expect(getStatusCodeInput()).toBeDisabled()
expect(screen.getByDisplayValue('ok')).toBeDisabled()
expect(screen.queryByRole('button', { name: 'Delete row' })).not.toBeInTheDocument()
- expect(mockGenerateWebhookUrl).not.toHaveBeenCalled()
- expect(mockHandleHeadersChange).not.toHaveBeenCalled()
- expect(mockHandleParamsChange).not.toHaveBeenCalled()
- expect(mockHandleBodyChange).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
+ expect(data()).toMatchObject(initial)
})
it('copies the debug URL from the keyboard and announces success while keeping its visible name', async () => {
const user = userEvent.setup()
- mockConfigState.inputs = {
- ...mockConfigState.inputs,
- webhook_debug_url: 'http://127.0.0.1:8000/debug',
- }
-
- render(<Panel {...panelProps} />)
+ renderPanel(createData({ webhook_debug_url: 'http://127.0.0.1:8000/debug' }))
const button = screen.getByRole('button', {
name: 'workflowIntegrations.nodes.triggerWebhook.debugUrlTitle http://127.0.0.1:8000/debug workflowIntegrations.nodes.triggerWebhook.debugUrlCopy',
diff --git a/web/app/components/workflow/nodes/variable-assigner/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/variable-assigner/__tests__/panel.spec.tsx
index 6230c8ad016..a8a37f2a469 100644
--- a/web/app/components/workflow/nodes/variable-assigner/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/variable-assigner/__tests__/panel.spec.tsx
@@ -1,17 +1,10 @@
import type { VariableAssignerNodeType } from '../types'
-import type { PanelProps } from '@/types/workflow'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
+import { createEdge, createNode } from '../../../__tests__/fixtures'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
-import { renderAssigner as render } from './test-helpers'
-
-const mockUseConfig = vi.hoisted(() => vi.fn())
-
-vi.mock('../use-config', () => ({
- __esModule: true,
- default: (...args: unknown[]) => mockUseConfig(...args),
-}))
const createData = (
overrides: Partial<VariableAssignerNodeType> = {},
@@ -41,104 +34,104 @@ const createData = (
...overrides,
})
-const panelProps = {} as PanelProps
-
-describe('variable-assigner/panel', () => {
- const handleGroupEnabledChange = vi.fn()
- const handleAddGroup = vi.fn()
- const hideRemoveVarConfirm = vi.fn()
- const onRemoveVarConfirm = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseConfig.mockReturnValue({
- readOnly: false,
- inputs: createData(),
- handleListOrTypeChange: vi.fn(),
- isEnableGroup: true,
- handleGroupEnabledChange,
- handleAddGroup,
- handleListOrTypeChangeInGroup: vi.fn(() => vi.fn()),
- handleGroupRemoved: vi.fn(() => vi.fn()),
- handleVarGroupNameChange: vi.fn(() => vi.fn()),
- isShowRemoveVarConfirm: false,
- hideRemoveVarConfirm,
- onRemoveVarConfirm,
- getAvailableVars: vi.fn(() => []),
- filterVar: vi.fn(() => vi.fn(() => true)),
- })
+const source = createNode({
+ id: 'source-node',
+ data: {
+ type: BlockEnum.Code,
+ title: 'Source',
+ outputs: { rootVar: { type: VarType.string }, groupVar: { type: VarType.string } },
+ },
+})
+const renderPanel = (data = createData(), readOnly = false) =>
+ renderNodePanel(Panel, data, {
+ nodes: [source, createNode({ id: 'node', data })],
+ edges: [createEdge({ source: source.id, target: 'node' })],
+ initialStoreState: { canvasReadOnly: readOnly },
})
- it('renders grouped panels and adds or disables aggregation groups', async () => {
+describe('variable-assigner/panel', () => {
+ it('adds aggregation groups and preserves the first group when aggregation is disabled', async () => {
const user = userEvent.setup()
-
- render(<Panel id="assigner-node" data={createData()} panelProps={panelProps} />)
-
+ const { data } = renderPanel()
expect(screen.getByText('Group1')).toBeInTheDocument()
expect(screen.getByText('Group2')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
expect(screen.getByText('Group1.output')).toBeInTheDocument()
expect(screen.getByText('Group2.output')).toBeInTheDocument()
-
+ await user.click(
+ screen.getByRole('button', { name: 'workflowLogic.nodes.variableAssigner.addGroup' }),
+ )
+ expect(data().advanced_settings?.groups).toEqual([
+ ...createData().advanced_settings!.groups,
+ expect.objectContaining({ group_name: 'Group3', output_type: VarType.any, variables: [] }),
+ ])
+ expect(screen.getByText('Group3')).toBeInTheDocument()
await user.click(screen.getByRole('switch'))
- await user.click(screen.getByText('workflowLogic.nodes.variableAssigner.addGroup'))
-
- expect(handleGroupEnabledChange).toHaveBeenCalledWith(false, expect.anything())
- expect(handleAddGroup).toHaveBeenCalledTimes(1)
+ expect(data()).toMatchObject({
+ advanced_settings: { group_enabled: false },
+ variables: [['source-node', 'groupVar']],
+ output_type: VarType.string,
+ })
+ expect(screen.queryByText('Group1.output')).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'workflowLogic.nodes.variableAssigner.addGroup' }),
+ ).not.toBeInTheDocument()
})
it('renders a single root group and hides output vars when aggregation is disabled', () => {
- mockUseConfig.mockReturnValue({
- readOnly: false,
- inputs: createData({
- advanced_settings: {
- group_enabled: false,
- groups: [],
- },
- }),
- handleListOrTypeChange: vi.fn(),
- isEnableGroup: false,
- handleGroupEnabledChange,
- handleAddGroup,
- handleListOrTypeChangeInGroup: vi.fn(() => vi.fn()),
- handleGroupRemoved: vi.fn(() => vi.fn()),
- handleVarGroupNameChange: vi.fn(() => vi.fn()),
- isShowRemoveVarConfirm: false,
- hideRemoveVarConfirm,
- onRemoveVarConfirm,
- getAvailableVars: vi.fn(() => []),
- filterVar: vi.fn(() => vi.fn(() => true)),
- })
-
- render(<Panel id="assigner-node" data={createData()} panelProps={panelProps} />)
-
+ renderPanel(createData({ advanced_settings: { group_enabled: false, groups: [] } }))
expect(screen.getByText('rootVar')).toBeInTheDocument()
expect(
screen.getByText('workflowLogic.nodes.variableAssigner.aggregationGroup'),
).toBeInTheDocument()
expect(screen.queryByText('Group1.output')).not.toBeInTheDocument()
})
+
it('prevents adding or renaming groups in read-only mode', async () => {
const user = userEvent.setup()
- mockUseConfig.mockReturnValue({ ...mockUseConfig(), readOnly: true })
- render(<Panel id="assigner-node" data={createData()} panelProps={panelProps} />)
+ const { data } = renderPanel(createData(), true)
expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
expect(
screen.queryByRole('button', { name: 'workflowLogic.nodes.variableAssigner.addGroup' }),
).not.toBeInTheDocument()
await user.click(screen.getByText('Group1'))
expect(screen.queryByDisplayValue('Group1')).not.toBeInTheDocument()
- expect(handleAddGroup).not.toHaveBeenCalled()
+ expect(data()).toMatchObject(createData())
})
it.each(['cancel', 'confirm'])(
- 'forwards the real confirmation dialog %s action',
+ 'handles %s when disabling groups would remove a referenced output',
async (action) => {
const user = userEvent.setup()
- mockUseConfig.mockReturnValue({ ...mockUseConfig(), isShowRemoveVarConfirm: true })
- render(<Panel id="assigner-node" data={createData()} panelProps={panelProps} />)
+ const initial = createData()
+ const consumer = createNode({
+ id: 'consumer',
+ data: {
+ type: BlockEnum.TemplateTransform,
+ variables: [{ variable: 'value', value_selector: ['node', 'Group2', 'output'] }],
+ template: '{{ value }}',
+ },
+ })
+ const { data, getNode } = renderNodePanel(Panel, initial, {
+ nodes: [source, createNode({ id: 'node', data: initial }), consumer],
+ edges: [
+ createEdge({ source: source.id, target: 'node' }),
+ createEdge({ source: 'node', target: 'consumer' }),
+ ],
+ })
+ await user.click(screen.getByRole('switch'))
+ expect(data().advanced_settings?.group_enabled).toBe(true)
await user.click(screen.getByRole('button', { name: `common.operation.${action}` }))
- expect(action === 'cancel' ? hideRemoveVarConfirm : onRemoveVarConfirm).toHaveBeenCalled()
+ expect(data().advanced_settings?.group_enabled).toBe(action === 'cancel')
+ expect(getNode('consumer')?.data.variables).toEqual([
+ {
+ variable: 'value',
+ value_selector: action === 'confirm' ? [] : ['node', 'Group2', 'output'],
+ },
+ ])
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.confirm' }),
+ ).not.toBeInTheDocument()
},
)
})