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): replace AP1/AP3/AP32 mocks with behavioral tests (#44958)

Stephen Zhou3c26fe8905a5
diff --git a/web/app/components/app/configuration/dataset-config/card-item/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/card-item/__tests__/index.spec.tsx
index 5ae3d6f6454..03999f6c6ac 100644
--- a/web/app/components/app/configuration/dataset-config/card-item/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/card-item/__tests__/index.spec.tsx
@@ -2,41 +2,26 @@ import type { DatasetDetailWithPartialMembersResponse } from '@dify/contracts/ap
import type * as React from 'react'
import type { IndexingType } from '@/app/components/datasets/create/step-two'
import type { RetrievalConfig } from '@/types/app'
-import { render, screen, waitFor } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ChunkingMode, DataSourceType } from '@/models/datasets'
import { PermissionLevel } from '@/models/permission'
+import { consoleQuery } from '@/service/console'
+import { updateDatasetSetting } from '@/service/datasets'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createConsoleQueryWrapper, renderWithConsoleQuery } from '@/test/console/query-data'
import { createDatasetFixture } from '@/test/fixtures/dataset'
+import { createNuqsTestRenderer } from '@/test/nuqs-testing'
import { RETRIEVE_METHOD } from '@/types/app'
import Item from '../index'
-vi.mock('../../settings-modal', () => ({
- default: ({
- onSave,
- onCancel,
- currentDataset,
- }: {
- currentDataset: DatasetDetailWithPartialMembersResponse
- onCancel: () => void
- onSave: (newDataset: DatasetDetailWithPartialMembersResponse) => void
- }) => (
- <div>
- <div>Mock settings modal</div>
- <button
- onClick={() =>
- onSave({
- ...currentDataset,
- retrieval_model_dict: { ...currentDataset.retrieval_model_dict, top_k: 6 },
- })
- }
- >
- Save changes
- </button>
- <button onClick={onCancel}>Close</button>
- </div>
- ),
+vi.mock('@/service/datasets', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/datasets')>()),
+ updateDatasetSetting: vi.fn(),
}))
+const render = createNuqsTestRenderer(renderWithConsoleQuery)
+
const baseRetrievalConfig: RetrievalConfig = {
search_method: RETRIEVE_METHOD.semantic,
reranking_enable: false,
@@ -124,14 +109,22 @@ const renderItem = (
const onSave = vi.fn()
const onRemove = vi.fn()
- render(<Item config={config} onSave={onSave} onRemove={onRemove} {...props} />)
+ const { queryClient } = createConsoleQueryWrapper()
+ seedModelProviderQueries(queryClient, [])
+ queryClient.setQueryData(consoleQuery.workspaces.current.members.get.queryKey({ input: {} }), {
+ accounts: [],
+ })
+ queryClient.setQueryData(consoleQuery.datasets.retrievalSetting.get.queryKey(), {
+ retrieval_method: [RETRIEVE_METHOD.semantic],
+ })
+ render(<Item config={config} onSave={onSave} onRemove={onRemove} {...props} />, { queryClient })
return { onSave, onRemove }
}
describe('dataset-config/card-item', () => {
beforeEach(() => {
- vi.clearAllMocks()
+ vi.mocked(updateDatasetSetting).mockResolvedValue(createDataset())
})
it('should render dataset details with indexing and external badges', () => {
@@ -176,9 +169,25 @@ describe('dataset-config/card-item', () => {
})
await user.click(editButton)
- expect(await screen.findByText('Mock settings modal'))!.toBeInTheDocument()
- await user.click(await screen.findByText('Save changes'))
-
+ const topK = await screen.findByRole('textbox', { name: 'appDebug.datasetConfig.top_k' })
+ await user.click(topK)
+ await user.keyboard('{ControlOrMeta>}a{/ControlOrMeta}6{Tab}')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: dataset.id,
+ body: expect.objectContaining({
+ name: dataset.name,
+ retrieval_model: expect.objectContaining({
+ search_method: RETRIEVE_METHOD.semantic,
+ top_k: 6,
+ score_threshold: 0,
+ }),
+ }),
+ },
+ { silent: true },
+ )
await waitFor(() => {
expect(onSave).toHaveBeenCalledWith(
expect.objectContaining({
@@ -188,7 +197,9 @@ describe('dataset-config/card-item', () => {
)
})
await waitFor(() => {
- expect(screen.queryByText('Mock settings modal')).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('textbox', { name: 'appDebug.datasetConfig.top_k' }),
+ ).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx
index 7e16d6b0d52..ed620afff0d 100644
--- a/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx
+++ b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx
@@ -1,14 +1,26 @@
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { mockEmojiData, renderWithEmoji as render } from '@/test/emoji-picker'
+import { mockEmojiData, renderWithEmoji } from '@/test/emoji-picker'
+import { createNuqsTestRenderer } from '@/test/nuqs-testing'
import ExternalDataToolModal from '../external-data-tool-modal'
+const render = createNuqsTestRenderer(renderWithEmoji)
+
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apiBasedExtension.get': () =>
+ Promise.resolve([
+ {
+ id: 'extension-1',
+ name: 'Search endpoint',
+ api_endpoint: 'https://search.example.com',
+ api_key: 'secret',
+ },
+ ]),
'codeBasedExtension.get': () =>
Promise.resolve({
module: 'external_data_tool',
@@ -52,23 +64,12 @@ vi.mock('#i18n', async (importOriginal) => ({
useLocale: () => mockLocale,
}))
-vi.mock('@/app/components/header/account-setting/api-based-extension-page/selector', () => ({
- ApiBasedExtensionSelector: ({
- onChange,
- value,
- }: {
- onChange: (value: string) => void
- value: string
- }) => <button onClick={() => onChange('extension-1')}>{value || 'pick-extension'}</button>,
-}))
-
describe('ExternalDataToolModal', () => {
const mockOnCancel = vi.fn()
const mockOnSave = vi.fn()
const mockOnValidateBeforeSave = vi.fn()
beforeEach(() => {
- vi.clearAllMocks()
mockLocale = 'en-US'
})
@@ -117,7 +118,15 @@ describe('ExternalDataToolModal', () => {
),
'search_api',
)
- await user.click(screen.getByText('pick-extension'))
+ await user.click(
+ screen.getByRole('button', { name: 'common.apiBasedExtension.selector.placeholder' }),
+ )
+ await user.click(
+ await screen.findByRole('button', { name: 'Search endpoint https://search.example.com' }),
+ )
+ expect(
+ screen.getByRole('button', { name: 'Search endpoint https://search.example.com' }),
+ ).toHaveAttribute('aria-expanded', 'false')
await user.click(screen.getByRole('button', { name: 'app.iconPicker.title' }))
await waitFor(() => {
expect(screen.getByPlaceholderText('app.iconPicker.search')).toBeInTheDocument()
diff --git a/web/app/components/datasets/documents/create-from-pipeline/preview/__tests__/online-document-preview.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/preview/__tests__/online-document-preview.spec.tsx
index a5b776d7b18..fd4347dcebc 100644
--- a/web/app/components/datasets/documents/create-from-pipeline/preview/__tests__/online-document-preview.spec.tsx
+++ b/web/app/components/datasets/documents/create-from-pipeline/preview/__tests__/online-document-preview.spec.tsx
@@ -2,8 +2,12 @@ import type { NotionPage } from '@/models/common'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
-import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import DatasetDetailContext from '@/context/dataset-detail'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
+import { createDatasetFixture } from '@/test/fixtures/dataset'
+import { createDataSourceStore } from '../../data-source/store'
+import { DataSourceContext } from '../../data-source/store/provider'
import OnlineDocumentPreview from '../online-document-preview'
// Uses global react-i18next mock from web/vitest.setup.ts
@@ -23,17 +27,6 @@ vi.mock('@/app/notifications', async (importOriginal) => {
}
})
-// Mock dataset-detail context - needs mock to control return values
-const mockPipelineId = vi.fn()
-vi.mock('@/context/dataset-detail', () => ({
- useDatasetDetailContextWithSelector: (
- _selector: (s: { dataset: { pipeline_id: string } }) => string,
- ) => {
- return mockPipelineId()
- },
-}))
-
-// Mock usePreviewOnlineDocument hook - needs mock to control mutation behavior
const mockMutateAsync = vi.fn()
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
@@ -48,16 +41,20 @@ vi.mock('@/service/console', async (importOriginal) => {
}
})
-// Mock data source store - needs mock to control store state
-const mockCurrentCredentialId = 'credential-123'
-const mockGetState = vi.fn(() => ({
- currentCredentialId: mockCurrentCredentialId,
-}))
-vi.mock('../../data-source/store', () => ({
- useDataSourceStore: () => ({
- getState: mockGetState,
- }),
-}))
+const render = (ui: React.ReactElement, credential = 'credential-123') => {
+ const store = createDataSourceStore()
+ store.getState().setCurrentCredentialId(credential)
+ const wrap = (children: React.ReactNode) => (
+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its Provider API.
+ <DatasetDetailContext.Provider
+ value={{ dataset: createDatasetFixture({ pipeline_id: 'pipeline-123' }) }}
+ >
+ <DataSourceContext value={store}>{children}</DataSourceContext>
+ </DatasetDetailContext.Provider>
+ )
+ const result = renderWithConsoleQuery(wrap(ui))
+ return { ...result, rerender: (next: React.ReactElement) => result.rerender(wrap(next)) }
+}
// Test data factory
const createMockNotionPage = (overrides?: Partial<NotionPage>): NotionPage => ({
@@ -79,15 +76,11 @@ const defaultProps = {
describe('OnlineDocumentPreview', () => {
beforeEach(() => {
- vi.clearAllMocks()
- mockPipelineId.mockReturnValue('pipeline-123')
- mockGetState.mockReturnValue({ currentCredentialId: mockCurrentCredentialId })
mockMutateAsync.mockReset().mockResolvedValue({ content: 'Test content' })
})
it('requests the current page using the pipeline, node, workspace and credential', async () => {
- mockGetState.mockReturnValue({ currentCredentialId: 'custom-credential' })
- render(<OnlineDocumentPreview {...defaultProps} />)
+ render(<OnlineDocumentPreview {...defaultProps} />, 'custom-credential')
expect(await screen.findByText('Test content')).toBeInTheDocument()
expect(screen.getByText('Test Notion Page')).toBeInTheDocument()
expect(screen.getByText('page')).toBeInTheDocument()
diff --git a/web/app/components/workflow/__tests__/edge-contextmenu.spec.tsx b/web/app/components/workflow/__tests__/edge-contextmenu.spec.tsx
index 1c50a1f0c59..33d274ddd74 100644
--- a/web/app/components/workflow/__tests__/edge-contextmenu.spec.tsx
+++ b/web/app/components/workflow/__tests__/edge-contextmenu.spec.tsx
@@ -8,17 +8,6 @@ import { renderWorkflowFlowComponent } from '../__tests__/workflow-test-env'
import { EdgeContextmenu } from '../edge-contextmenu'
import { useEdgesInteractions } from '../hooks/use-edges-interactions'
-const mockSaveStateToHistory = vi.fn()
-
-vi.mock('../hooks/use-workflow-history', () => ({
- useWorkflowHistory: () => ({ saveStateToHistory: mockSaveStateToHistory }),
- WorkflowHistoryEvent: {
- EdgeDelete: 'EdgeDelete',
- EdgeDeleteByDeleteBranch: 'EdgeDeleteByDeleteBranch',
- EdgeSourceHandleChange: 'EdgeSourceHandleChange',
- },
-}))
-
type EdgeRuntimeState = {
_hovering?: boolean
_isBundled?: boolean
@@ -124,6 +113,7 @@ function renderEdgeMenu(options?: {
nodes,
edges,
initialStoreState,
+ historyStore: { nodes, edges },
hooksStoreProps,
reactFlowProps: { fitView: false },
})
@@ -131,10 +121,10 @@ function renderEdgeMenu(options?: {
describe('EdgeContextmenu', () => {
beforeEach(() => {
- vi.clearAllMocks()
latestNodes = []
latestEdges = []
})
+ afterEach(() => vi.useRealTimers())
it('should not render when edge context menu target is absent', () => {
renderWorkflowFlowComponent(
@@ -189,7 +179,6 @@ describe('EdgeContextmenu', () => {
expect(store.getState().contextMenuTarget).toBeUndefined()
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
})
- expect(mockSaveStateToHistory).toHaveBeenCalledWith('EdgeDelete')
})
it('should not render the menu when the referenced edge no longer exists', () => {
@@ -211,23 +200,34 @@ describe('EdgeContextmenu', () => {
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
})
- it('should delete the right-clicked edge and close the menu when delete is clicked', async () => {
- const user = userEvent.setup()
-
- renderEdgeMenu()
+ it('should delete the right-clicked edge and retain undoable history', async () => {
+ const { store } = renderEdgeMenu()
fireEvent.contextMenu(screen.getByRole('button', { name: 'Right-click edge e2' }), {
clientX: 320,
clientY: 180,
})
- await user.click(await screen.findByRole('menuitem', { name: /common\.operation\.delete/i }))
+ const deleteItem = await screen.findByRole('menuitem', { name: /common\.operation\.delete/i })
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ const timedUser = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
+ await timedUser.click(deleteItem)
+ await act(async () => vi.advanceTimersByTimeAsync(500))
+ vi.useRealTimers()
await waitFor(() => {
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
expect(latestEdges.map((edge) => edge.id)).toEqual(['e1'])
})
- expect(mockSaveStateToHistory).toHaveBeenCalledWith('EdgeDelete')
+ expect(store.getState().workflowHistory).toMatchObject({
+ workflowHistoryEvent: 'EdgeDelete',
+ edges: [expect.objectContaining({ id: 'e1', selected: false })],
+ })
+ expect(store.temporal.getState().pastStates).toHaveLength(1)
+ act(() => store.temporal.getState().undo())
+ expect(store.getState().workflowHistory.edges.map((edge) => edge.id)).toEqual(['e1', 'e2'])
+ act(() => store.temporal.getState().redo())
+ expect(store.getState().workflowHistory.edges.map((edge) => edge.id)).toEqual(['e1'])
})
it.each([
@@ -372,6 +372,10 @@ describe('EdgeContextmenu', () => {
expect(latestEdges.map((edge) => edge.id)).toEqual(['e1', 'e2'])
await user.click(item)
expect(latestEdges.map((edge) => edge.id)).toEqual(['e1', 'e2'])
- expect(mockSaveStateToHistory).not.toHaveBeenCalled()
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ await act(async () => vi.advanceTimersByTimeAsync(500))
+ vi.useRealTimers()
+ expect(store.temporal.getState().pastStates).toEqual([])
+ expect(store.getState().workflowHistory.edges.map((edge) => edge.id)).toEqual(['e1', 'e2'])
})
})
diff --git a/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/branches.spec.tsx b/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/branches.spec.tsx
index 3ac542c822c..3a156804c81 100644
--- a/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/branches.spec.tsx
+++ b/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/branches.spec.tsx
@@ -1,122 +1,125 @@
import type { ComponentProps } from 'react'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { VarType } from '@/app/components/workflow/types'
+import { useState } from 'react'
+import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
+import { BlockEnum, VarType } from '@/app/components/workflow/types'
+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 { AssignerNodeInputType, WriteMode } from '../../../types'
import VarList from '../index'
-vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
- __esModule: true,
- default: ({
- popupFor = 'assigned',
- onOpen,
- onChange,
- }: {
- popupFor?: string
- onOpen?: () => void
- onChange: (value: string[]) => void
- }) => (
- <div>
- <button type="button" data-testid={`${popupFor}-picker-trigger`} onClick={onOpen}>
- open-
- {popupFor}
- </button>
- <button
- type="button"
- onClick={() =>
- onChange(popupFor === 'assigned' ? ['node-b', 'total'] : ['node-c', 'result'])
- }
- >
- select-
- {popupFor}
- </button>
- </div>
- ),
-}))
-
-const createOperation = (
- overrides: Partial<ComponentProps<typeof VarList>['list'][number]> = {},
-): ComponentProps<typeof VarList>['list'][number] => ({
- variable_selector: ['node-a', 'flag'],
+type Operation = ComponentProps<typeof VarList>['list'][number]
+const createOperation = (overrides: Partial<Operation> = {}): Operation => ({
+ variable_selector: ['conversation', 'flag'],
input_type: AssignerNodeInputType.variable,
operation: WriteMode.overwrite,
- value: ['node-a', 'answer'],
+ value: ['producer', 'answer'],
...overrides,
})
-const renderVarList = (props: Partial<ComponentProps<typeof VarList>> = {}) => {
- const handleChange = vi.fn()
- const handleOpen = vi.fn()
-
- const result = render(
- <VarList
- readonly={false}
- nodeId="node-current"
- list={[]}
- onChange={handleChange}
- onOpen={handleOpen}
- getAssignedVarType={() => VarType.string}
- getToAssignedVarType={() => VarType.string}
- writeModeTypes={[WriteMode.overwrite, WriteMode.clear, WriteMode.set]}
- writeModeTypesArr={[WriteMode.overwrite, WriteMode.clear]}
- writeModeTypesNum={[WriteMode.increment]}
- {...props}
- />,
+function ControlledList({ initialList }: { initialList: Operation[] }) {
+ const [list, setList] = useState(initialList)
+ const [opened, setOpened] = useState<number>()
+ return (
+ <>
+ <VarList
+ readonly={false}
+ nodeId="node-current"
+ list={list}
+ onChange={setList}
+ onOpen={setOpened}
+ filterVar={(_variable, selector) => selector[0] === 'conversation'}
+ getAssignedVarType={(selector) =>
+ selector[1] === 'count' ? VarType.number : VarType.string
+ }
+ getToAssignedVarType={(type) => type}
+ writeModeTypes={[WriteMode.overwrite, WriteMode.clear, WriteMode.set]}
+ writeModeTypesArr={[WriteMode.overwrite, WriteMode.clear]}
+ writeModeTypesNum={[WriteMode.increment]}
+ />
+ <output aria-label="Assignments">{JSON.stringify(list)}</output>
+ <output aria-label="Editing assignment">{opened}</output>
+ </>
)
-
- return {
- ...result,
- handleChange,
- handleOpen,
- }
}
-describe('assigner/var-list branches', () => {
- beforeEach(() => {
- vi.clearAllMocks()
+function renderVarList(initialList: Operation[]) {
+ const { queryClient } = createConsoleQueryWrapper({ appDslVersion: '0.6.0' })
+ seedModelProviderQueries(queryClient, [])
+ seedToolProviders(queryClient, {
+ builtInTools: [],
+ customTools: [],
+ workflowTools: [],
+ mcpTools: [],
})
-
- it('resets operation metadata when the assigned variable changes', async () => {
- const user = userEvent.setup()
- const { handleChange, handleOpen } = renderVarList({
- list: [
- createOperation({
- operation: WriteMode.set,
- input_type: AssignerNodeInputType.constant,
- value: 'stale',
- }),
+ queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
+ const producer = createNode({
+ id: 'producer',
+ data: {
+ type: BlockEnum.Code,
+ title: 'Answer source',
+ outputs: { answer: { type: VarType.string, children: null } },
+ },
+ })
+ const assigner = createNode({
+ id: 'node-current',
+ data: { type: BlockEnum.Assigner, title: 'Assign' },
+ })
+ return renderWorkflowFlowComponent(<ControlledList initialList={initialList} />, {
+ queryClient,
+ resource: { kind: 'app', appId: 'app-1', mode: 'advanced-chat' },
+ nodes: [producer, assigner],
+ edges: [createEdge({ source: producer.id, target: assigner.id })],
+ initialStoreState: {
+ conversationVariables: [
+ { id: 'flag', name: 'flag', value_type: ChatVarType.String, value: '', description: '' },
+ { id: 'total', name: 'total', value_type: ChatVarType.String, value: '', description: '' },
+ { id: 'count', name: 'count', value_type: ChatVarType.Number, value: 1, description: '' },
],
- })
+ },
+ })
+}
- await user.click(screen.getByTestId('assigned-picker-trigger'))
- await user.click(screen.getByRole('button', { name: 'select-assigned' }))
+const assignments = () => JSON.parse(screen.getByLabelText('Assignments').textContent!)
- expect(handleOpen).toHaveBeenCalledWith(0)
- expect(handleChange).toHaveBeenLastCalledWith(
- [
- createOperation({
- variable_selector: ['node-b', 'total'],
- operation: WriteMode.overwrite,
- input_type: AssignerNodeInputType.variable,
- value: undefined,
- }),
- ],
- ['node-b', 'total'],
- )
+describe('assigner/var-list branches', () => {
+ it('resets stale constant metadata when selecting another destination, then assigns a graph output', async () => {
+ const user = userEvent.setup()
+ renderVarList([
+ createOperation({
+ operation: WriteMode.set,
+ input_type: AssignerNodeInputType.constant,
+ value: 'stale',
+ }),
+ ])
+ await user.click(screen.getByText('flag'))
+ expect(screen.getByLabelText('Editing assignment')).toHaveTextContent('0')
+ await user.click(await screen.findByText('total'))
+ expect(assignments()).toEqual([
+ createOperation({ variable_selector: ['conversation', 'total'], value: undefined }),
+ ])
+ expect(screen.queryByRole('textbox', { name: 'conversation.flag' })).not.toBeInTheDocument()
+ await user.click(screen.getByText('workflowLogic.nodes.assigner.setParameter'))
+ await user.click(await screen.findByText('answer'))
+ expect(assignments()).toEqual([
+ createOperation({ variable_selector: ['conversation', 'total'] }),
+ ])
})
- it('switches back to variable mode when the selected operation no longer requires a constant', async () => {
+ it('clears constant input when switching to overwrite', async () => {
const user = userEvent.setup()
- const { handleChange } = renderVarList({
- list: [
- createOperation({
- operation: WriteMode.set,
- input_type: AssignerNodeInputType.constant,
- value: 'hello',
- }),
- ],
- })
-
+ renderVarList([
+ createOperation({
+ operation: WriteMode.set,
+ input_type: AssignerNodeInputType.constant,
+ value: 'hello',
+ }),
+ ])
await user.click(
screen.getByRole('button', { name: 'workflowLogic.nodes.assigner.operations.set' }),
)
@@ -125,105 +128,45 @@ describe('assigner/var-list branches', () => {
name: 'workflowLogic.nodes.assigner.operations.over-write',
}),
)
-
- expect(handleChange).toHaveBeenLastCalledWith([
- createOperation({
- operation: WriteMode.overwrite,
- input_type: AssignerNodeInputType.variable,
- value: '',
- }),
- ])
+ expect(assignments()).toEqual([createOperation({ value: '' })])
+ expect(screen.queryByRole('textbox', { name: 'conversation.flag' })).not.toBeInTheDocument()
+ expect(screen.getByText('workflowLogic.nodes.assigner.setParameter')).toBeInTheDocument()
})
- it('updates string and number constant inputs through the inline editors', async () => {
+ it('edits string and numeric constants without changing neighboring assignments', async () => {
const user = userEvent.setup()
- const { handleChange, rerender } = renderVarList({
- list: [
- createOperation({
- operation: WriteMode.set,
- input_type: AssignerNodeInputType.constant,
- value: 1,
- }),
- ],
- getAssignedVarType: () => VarType.number,
- getToAssignedVarType: () => VarType.number,
+ const text = createOperation({
+ operation: WriteMode.set,
+ input_type: AssignerNodeInputType.constant,
+ value: 'hello',
})
-
- await user.clear(screen.getByRole('textbox', { name: 'node-a.flag' }))
- await user.type(screen.getByRole('textbox', { name: 'node-a.flag' }), '2')
-
- expect(handleChange).toHaveBeenLastCalledWith(
- [
- createOperation({
- operation: WriteMode.set,
- input_type: AssignerNodeInputType.constant,
- value: 2,
- }),
- ],
- undefined,
- )
-
- rerender(
- <VarList
- readonly={false}
- nodeId="node-current"
- list={[
- createOperation({
- operation: WriteMode.set,
- input_type: AssignerNodeInputType.constant,
- value: 'hello',
- }),
- ]}
- onChange={handleChange}
- onOpen={vi.fn()}
- getAssignedVarType={() => VarType.string}
- getToAssignedVarType={() => VarType.string}
- writeModeTypes={[WriteMode.overwrite, WriteMode.clear, WriteMode.set]}
- writeModeTypesArr={[WriteMode.overwrite, WriteMode.clear]}
- writeModeTypesNum={[WriteMode.increment]}
- />,
- )
-
- await user.tripleClick(screen.getByRole('textbox'))
- await user.paste('updated')
-
- expect(handleChange).toHaveBeenLastCalledWith(
- [
- createOperation({
- operation: WriteMode.set,
- input_type: AssignerNodeInputType.constant,
- value: 'updated',
- }),
- ],
- undefined,
- )
+ const number = createOperation({
+ variable_selector: ['conversation', 'count'],
+ operation: WriteMode.set,
+ input_type: AssignerNodeInputType.constant,
+ value: 1,
+ })
+ renderVarList([text, number])
+ await user.clear(screen.getByRole('textbox', { name: 'conversation.flag' }))
+ await user.type(screen.getByRole('textbox', { name: 'conversation.flag' }), 'updated')
+ await user.clear(screen.getByRole('textbox', { name: 'conversation.count' }))
+ await user.type(screen.getByRole('textbox', { name: 'conversation.count' }), '2')
+ expect(assignments()).toEqual([
+ { ...text, value: 'updated' },
+ { ...number, value: 2 },
+ ])
})
- it('updates numeric write-mode inputs through the dedicated number field', async () => {
+ it('edits a numeric increment through the number field', async () => {
const user = userEvent.setup()
- const { handleChange } = renderVarList({
- list: [
- createOperation({
- operation: WriteMode.increment,
- value: 2,
- }),
- ],
- getAssignedVarType: () => VarType.number,
- getToAssignedVarType: () => VarType.number,
- writeModeTypesNum: [WriteMode.increment],
+ const operation = createOperation({
+ variable_selector: ['conversation', 'count'],
+ operation: WriteMode.increment,
+ value: 2,
})
-
- await user.clear(screen.getByRole('textbox', { name: 'node-a.flag' }))
- await user.type(screen.getByRole('textbox', { name: 'node-a.flag' }), '5')
-
- expect(handleChange).toHaveBeenLastCalledWith(
- [
- createOperation({
- operation: WriteMode.increment,
- value: 5,
- }),
- ],
- undefined,
- )
+ renderVarList([operation])
+ await user.clear(screen.getByRole('textbox', { name: 'conversation.count' }))
+ await user.type(screen.getByRole('textbox', { name: 'conversation.count' }), '5')
+ expect(assignments()).toEqual([{ ...operation, value: 5 }])
})
})
diff --git a/web/app/components/workflow/nodes/start-placeholder/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/start-placeholder/__tests__/panel.spec.tsx
index d81895465fd..f6723210ac8 100644
--- a/web/app/components/workflow/nodes/start-placeholder/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/start-placeholder/__tests__/panel.spec.tsx
@@ -1,94 +1,151 @@
-import type {
- AvailableNodesMetaData,
- SyncDraftCallback,
-} from '@/app/components/workflow/hooks-store'
+import type { ReactNode } from 'react'
+import type { AvailableNodesMetaData } from '@/app/components/workflow/hooks-store'
import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store'
-import { act, screen } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
import { useNodes } from 'reactflow'
+import { FeaturesContext } from '@/app/components/base/features/context'
+import { createFeaturesStore } from '@/app/components/base/features/store'
+import { useNodesSyncDraft } from '@/app/components/workflow-app/hooks/use-nodes-sync-draft'
import { createWorkflowSlice } from '@/app/components/workflow-app/store/workflow/workflow-slice'
+import { HooksStoreContext } from '@/app/components/workflow/hooks-store/provider'
+import { createHooksStore } from '@/app/components/workflow/hooks-store/store'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
import { createNode } from '../../../__tests__/fixtures'
import { renderWorkflowFlowComponent } from '../../../__tests__/workflow-test-env'
import { BlockEnum } from '../../../types'
-import startDefault from '../../start/default'
+import webhookDefault from '../../trigger-webhook/default'
import Panel from '../panel'
-const syncDraft =
- vi.fn<(sync?: boolean, notRefresh?: boolean, callback?: SyncDraftCallback) => void>()
-const generateUrl = vi.fn()
-// Catalog selection and URL generation are independent boundaries; graph replacement stays real.
-vi.mock('@/app/components/workflow/block-selector/all-start-blocks', () => ({
- default: ({ onSelect }: { onSelect: (type: BlockEnum) => void }) => (
- <button type="button" onClick={() => onSelect(BlockEnum.Start)}>
- Select User Input
- </button>
- ),
-}))
-vi.mock('../../../hooks/use-nodes-sync-draft', () => ({
- useNodesSyncDraft: () => ({ handleSyncWorkflowDraft: syncDraft }),
-}))
-vi.mock('../../../hooks/use-auto-generate-webhook-url', () => ({
- useAutoGenerateWebhookUrl: () => generateUrl,
-}))
+const persistDraft = vi.fn()
+const fetchWebhook = vi.fn()
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: {
+ ...actual.consoleClient,
+ apps: {
+ byAppId: { workflows: { draft: { post: (...args: unknown[]) => persistDraft(...args) } } },
+ },
+ },
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflows.triggers.webhook.get': (input: unknown) => fetchWebhook(input),
+ }),
+ }
+})
+
+const selectedStart = {
+ metaData: webhookDefault.metaData,
+ checkValid: () => ({ isValid: true }),
+ defaultValue: { ...webhookDefault.defaultValue, title: 'Webhook', desc: '' },
+}
+
+const nodesMap: Partial<NonNullable<AvailableNodesMetaData['nodesMap']>> = {
+ [BlockEnum.TriggerWebhook]: selectedStart,
+}
+
+function DraftOwner({ children }: { children: ReactNode }) {
+ const sync = useNodesSyncDraft()
+ const [hooks] = useState(() =>
+ createHooksStore({
+ ...sync,
+ availableNodesMetaData: {
+ nodes: [selectedStart],
+ nodesMap: nodesMap as AvailableNodesMetaData['nodesMap'],
+ },
+ }),
+ )
+ return <HooksStoreContext value={hooks}>{children}</HooksStoreContext>
+}
+
function GraphState() {
- const nodes = useNodes()
- return <output aria-label="Graph">{JSON.stringify(nodes)}</output>
+ return <output aria-label="Graph">{JSON.stringify(useNodes())}</output>
}
-it('replaces the placeholder, deselects its neighbor and waits for draft persistence before generating URLs', async () => {
+it('replaces the placeholder and generates webhook URLs only after the graph is persisted', async () => {
const user = userEvent.setup()
+ const pending = createDeferred<{ hash: string; updated_at: number }>()
+ persistDraft.mockReturnValue(pending.promise)
+ fetchWebhook.mockResolvedValue({
+ webhook_url: 'https://hooks.example.com/live',
+ webhook_debug_url: 'https://hooks.example.com/debug',
+ })
const placeholder = createNode({
id: 'placeholder-1',
data: { type: BlockEnum.StartPlaceholder, selected: true },
})
- const selectedStart = {
- metaData: startDefault.metaData,
- checkValid: () => ({ isValid: true }),
- defaultValue: { ...startDefault.defaultValue, title: 'User Input', desc: '' },
- }
- // Only the Start catalog entry is exposed by the selector boundary in this scenario.
- const nodesMap: Partial<NonNullable<AvailableNodesMetaData['nodesMap']>> = {
- [BlockEnum.Start]: selectedStart,
- }
+ const { queryClient } = createConsoleQueryWrapper({
+ appDslVersion: '0.6.0',
+ systemFeatures: { enable_marketplace: false, enable_collaboration_mode: false },
+ })
+ queryClient.setQueryData(consoleQuery.workspaces.current.triggers.get.queryKey({ input: {} }), [])
const { store } = renderWorkflowFlowComponent(
- <>
- <Panel
- panelProps={{
- getInputVars: () => [],
- toVarInputs: () => [],
- runInputData: {},
- runInputDataRef: { current: {} },
- setRunInputData: () => {},
- runResult: null,
- }}
- id={placeholder.id}
- data={placeholder.data}
- />
- <GraphState />
- </>,
+ <FeaturesContext value={createFeaturesStore()}>
+ <DraftOwner>
+ <Panel
+ panelProps={{
+ getInputVars: () => [],
+ toVarInputs: () => [],
+ runInputData: {},
+ runInputDataRef: { current: {} },
+ setRunInputData: () => {},
+ runResult: null,
+ }}
+ id={placeholder.id}
+ data={placeholder.data}
+ />
+ <GraphState />
+ </DraftOwner>
+ </FeaturesContext>,
{
+ queryClient,
injectWorkflowStoreSliceFn: createWorkflowSlice as InjectWorkflowStoreSliceFn,
+ initialStoreState: { isWorkflowDataLoaded: true },
nodes: [placeholder, createNode({ id: 'other-node', data: { selected: true } })],
- hooksStoreProps: {
- availableNodesMetaData: {
- nodes: [selectedStart],
- nodesMap: nodesMap as AvailableNodesMetaData['nodesMap'],
- },
- },
},
)
- await user.click(screen.getByRole('button', { name: 'Select User Input' }))
+ await user.click(await screen.findByRole('button', { name: 'workflow.blocks.trigger-webhook' }))
const nodes = JSON.parse(screen.getByLabelText('Graph').textContent!)
expect(nodes[0]).toMatchObject({
id: 'placeholder-1',
- data: { type: BlockEnum.Start, title: 'User Input', selected: true, variables: [] },
+ data: { type: BlockEnum.TriggerWebhook, title: 'Webhook', selected: true, webhook_url: '' },
})
expect(nodes[1].data.selected).toBe(false)
expect(store.getState().hasSelectedStartNode).toBe(true)
expect(store.getState().shouldAutoOpenStartNodeSelector).toBe(true)
- expect(generateUrl).not.toHaveBeenCalled()
- const [sync, notRefresh, callback] = syncDraft.mock.calls[0]!
- expect([sync, notRefresh]).toEqual([true, false])
- act(() => callback?.onSuccess?.())
- expect(generateUrl).toHaveBeenCalledWith('placeholder-1')
+ expect(persistDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: { app_id: 'app-1' },
+ body: expect.objectContaining({
+ graph: expect.objectContaining({
+ nodes: expect.arrayContaining([
+ expect.objectContaining({
+ id: 'placeholder-1',
+ data: expect.objectContaining({ type: BlockEnum.TriggerWebhook }),
+ }),
+ ]),
+ }),
+ }),
+ }),
+ expect.anything(),
+ )
+ expect(fetchWebhook).not.toHaveBeenCalled()
+ await act(async () => pending.resolve({ hash: 'saved-hash', updated_at: 123 }))
+ await waitFor(() =>
+ expect(JSON.parse(screen.getByLabelText('Graph').textContent!)[0].data).toMatchObject({
+ webhook_url: 'https://hooks.example.com/live',
+ webhook_debug_url: 'https://hooks.example.com/debug',
+ }),
+ )
+ expect(fetchWebhook).toHaveBeenCalledWith({
+ params: { app_id: 'app-1' },
+ query: { node_id: 'placeholder-1' },
+ })
+ expect(store.getState().syncWorkflowDraftHash).toBe('saved-hash')
+ expect(store.getState().draftUpdatedAt).toBe(123000)
})
diff --git a/web/app/components/workflow/panel/chat-variable-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/chat-variable-panel/__tests__/index.spec.tsx
index fb5918d93d8..d2db34f454e 100644
--- a/web/app/components/workflow/panel/chat-variable-panel/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/panel/chat-variable-panel/__tests__/index.spec.tsx
@@ -3,38 +3,47 @@ import type { CodeNodeType } from '@/app/components/workflow/nodes/code/types'
import type { ConversationVariable, Node } from '@/app/components/workflow/types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { useLayoutEffect } from 'react'
-import { ReactFlowProvider, useStoreApi } from 'reactflow'
-import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { useState } from 'react'
+import { useStoreApi } from 'reactflow'
+import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { HooksStoreContext } from '@/app/components/workflow/hooks-store/provider'
+import { createHooksStore } from '@/app/components/workflow/hooks-store/store'
+import {
+ useConversationVarValues,
+ useInvalidateConversationVarValues,
+} from '@/service/use-workflow'
import ChatVariablePanel from '../index'
import { ChatVarType } from '../type'
-const mockInvalidateConversationVarValues = vi.fn()
const mockUpdateConversationVariables = vi.fn().mockResolvedValue(undefined)
let mockConversationVariables: ConversationVariable[] = []
let mockFlowNodes: Node<CodeNodeType>[] = []
let flowStore: ReturnType<typeof useStoreApi>
-function FlowFixture({ children }: { children: ReactNode }) {
- const store = useStoreApi()
- useLayoutEffect(() => {
- flowStore = store
- store.getState().setNodes(mockFlowNodes)
- }, [store])
- return children
+function InspectVariables({ children }: { children: ReactNode }) {
+ flowStore = useStoreApi()
+ const invalidateConversationVarValues = useInvalidateConversationVarValues({
+ kind: 'app',
+ appId: 'app-1',
+ mode: 'advanced-chat',
+ })
+ const [hooks] = useState(() => createHooksStore({ invalidateConversationVarValues }))
+ const { data } = useConversationVarValues({ kind: 'app', appId: 'app-1', mode: 'advanced-chat' })
+ return (
+ <HooksStoreContext value={hooks}>
+ {children}
+ <output aria-label="Inspected conversation variables">{JSON.stringify(data)}</output>
+ </HooksStoreContext>
+ )
}
const render = (ui: ReactElement) =>
- renderWorkflowComponent(
- <ReactFlowProvider>
- <FlowFixture>{ui}</FlowFixture>
- </ReactFlowProvider>,
- {
- initialStoreState: {
- conversationVariables: mockConversationVariables,
- showChatVariablePanel: true,
- },
+ renderWorkflowFlowComponent(<InspectVariables>{ui}</InspectVariables>, {
+ nodes: mockFlowNodes,
+ initialStoreState: {
+ conversationVariables: mockConversationVariables,
+ showChatVariablePanel: true,
},
- )
+ })
const createConversationVariable = (
overrides: Partial<ConversationVariable> = {},
@@ -67,12 +76,29 @@ vi.mock('@/service/workflow', async (importOriginal) => ({
updateConversationVariables: (...args: unknown[]) => mockUpdateConversationVariables(...args),
}))
-vi.mock('../../../hooks/use-inspect-vars-crud', () => ({
- default: () => ({
- invalidateConversationVarValues: mockInvalidateConversationVarValues,
- }),
-}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflows.draft.conversationVariables.get': () =>
+ Promise.resolve({
+ items: [
+ {
+ id: 'var-added',
+ name: 'fresh_var',
+ value: 'server value',
+ value_type: 'string',
+ selector: ['conversation', 'fresh_var'],
+ },
+ ],
+ }),
+ }),
+ }
+})
+// VariableItem exposes only unnamed SVG edit/delete targets; keep this minimal action boundary.
vi.mock('@/app/components/workflow/panel/chat-variable-panel/components/variable-item', () => ({
default: ({
item,
@@ -91,64 +117,8 @@ vi.mock('@/app/components/workflow/panel/chat-variable-panel/components/variable
),
}))
-vi.mock(
- '@/app/components/workflow/panel/chat-variable-panel/components/variable-modal-trigger',
- () => ({
- default: ({
- open,
- showTip,
- chatVar,
- onSave,
- onClose,
- }: {
- open: boolean
- showTip: boolean
- chatVar?: ConversationVariable
- onSave: (chatVar: ConversationVariable) => void
- onClose: () => void
- }) => (
- <div data-testid="variable-modal-trigger">
- <span>{open ? 'open' : 'closed'}</span>
- <span>{showTip ? 'tip-on' : 'tip-off'}</span>
- <span>{chatVar?.name || 'new-variable'}</span>
- <button
- type="button"
- onClick={() =>
- onSave({
- id: 'var-added',
- name: 'fresh_var',
- value_type: ChatVarType.String,
- value: '',
- description: 'Added variable',
- })
- }
- >
- save-add
- </button>
- {chatVar && (
- <button
- type="button"
- onClick={() =>
- onSave({
- ...chatVar,
- name: `${chatVar.name}_next`,
- })
- }
- >
- save-edit
- </button>
- )}
- <button type="button" onClick={onClose}>
- close-trigger
- </button>
- </div>
- ),
- }),
-)
-
describe('ChatVariablePanel', () => {
beforeEach(() => {
- vi.clearAllMocks()
mockConversationVariables = [createConversationVariable()]
mockFlowNodes = [createNode('node-1'), createNode('node-2')]
mockUpdateConversationVariables.mockResolvedValue(undefined)
@@ -178,26 +148,33 @@ describe('ChatVariablePanel', () => {
expect(store.getState().showChatVariablePanel).toBe(false)
})
- it('should prepend newly added variables and sync the workflow draft', async () => {
+ it('should prepend new variables, persist them and refresh inspector values', async () => {
const user = userEvent.setup()
const { store } = render(<ChatVariablePanel />)
- await user.click(screen.getByRole('button', { name: 'save-add' }))
+ await user.click(screen.getByRole('button', { name: 'workflow.chatVariable.button' }))
+ await user.type(
+ screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
+ 'fresh_var',
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => {
expect(store.getState().conversationVariables).toEqual([
- expect.objectContaining({ id: 'var-added', name: 'fresh_var' }),
+ expect.objectContaining({ id: expect.any(String), name: 'fresh_var' }),
createConversationVariable(),
])
expect(mockUpdateConversationVariables).toHaveBeenCalledWith({
appId: 'app-1',
conversationVariables: [
- expect.objectContaining({ id: 'var-added', name: 'fresh_var' }),
+ expect.objectContaining({ id: expect.any(String), name: 'fresh_var' }),
createConversationVariable(),
],
})
- expect(mockInvalidateConversationVarValues).toHaveBeenCalledTimes(1)
+ expect(screen.getByLabelText('Inspected conversation variables')).toHaveTextContent(
+ 'server value',
+ )
})
})
@@ -219,7 +196,10 @@ describe('ChatVariablePanel', () => {
const { store } = render(<ChatVariablePanel />)
await user.click(screen.getByRole('button', { name: 'edit-conversation_var' }))
- await user.click(screen.getByRole('button', { name: 'save-edit' }))
+ const name = screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder')
+ await user.clear(name)
+ await user.type(name, 'conversation_var_next')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(store.getState().conversationVariables).toEqual([
expect.objectContaining({ id: 'var-1', name: 'conversation_var_next' }),