Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

test(web): exercise real snippet, workflow and publishing owners (#44924)

Stephen Zhou1df4a0834110
diff --git a/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx
index 08c32a391eb..952883336e4 100644
--- a/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx
@@ -1,9 +1,17 @@
-import type { ComponentProps, ReactElement } from 'react'
-import { render as rtlRender, screen, waitFor, within } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FeaturesContext } from '@/app/components/base/features/context'
import { createFeaturesStore } from '@/app/components/base/features/store'
+import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
+import {
+ createCatalogModelFixture,
+ createModelCatalogFixture,
+ seedModelProviderQueries,
+} from '@/test/console/model-provider'
+import { createConsoleQueryWrapper, seedAppDetail } from '@/test/console/query-data'
+import { createAppDetailFixture } from '@/test/fixtures/app'
import {
createModelConfigFixture,
createPublishedConfigurationFixture,
@@ -35,43 +43,20 @@ const mockFeatures = {
number_limits: 3,
},
}
-vi.mock('@/app/components/app/app-publisher', () => ({
- AppPublisher: (
- props: ComponentProps<typeof import('@/app/components/app/app-publisher').AppPublisher>,
- ) => {
- return (
- <div>
- <button
- type="button"
- onClick={() =>
- props.onPublish?.({
- id: 'model-1',
- model: 'gpt-4o',
- provider: 'openai',
- parameters: {},
- })
- }
- >
- publish-through-wrapper
- </button>
- <button
- type="button"
- onClick={() => props.onPublish?.(undefined, { showSuccessToast: false })}
- >
- publish-silently-through-wrapper
- </button>
- <button type="button" onClick={() => props.onRestore?.()}>
- restore-through-wrapper
- </button>
- </div>
- )
- },
-}))
-
let store: ReturnType<typeof createFeaturesStore>
function render(ui: ReactElement) {
store = createFeaturesStore({ features: mockFeatures })
- return rtlRender(<FeaturesContext.Provider value={store}>{ui}</FeaturesContext.Provider>)
+ const { queryClient } = createConsoleQueryWrapper()
+ seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: 'chat' }))
+ seedModelProviderQueries(queryClient, [
+ createModelCatalogFixture({
+ provider: 'openai',
+ models: [createCatalogModelFixture({ model: 'gpt-4o', label: { en_US: 'GPT-4o' } })],
+ }),
+ ])
+ return renderWorkflowComponent(<FeaturesContext value={store}>{ui}</FeaturesContext>, {
+ queryClient,
+ })
}
describe('FeaturesWrappedAppPublisher', () => {
@@ -108,60 +93,54 @@ describe('FeaturesWrappedAppPublisher', () => {
}),
})
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
it('should pass current features through to onPublish', async () => {
const user = userEvent.setup()
render(
<FeaturesWrappedAppPublisher
appId="app-1"
+ publishedAt={1710000100000}
publishedConfig={publishedConfig}
onPublish={mockOnPublish}
+ debugWithMultipleModel
+ multipleModelConfigs={[
+ { id: 'model-1', model: 'gpt-4o', provider: 'openai', parameters: {} },
+ ]}
/>,
)
- await user.click(screen.getByText('publish-through-wrapper'))
+ await user.click(screen.getByRole('button', { name: 'workflow.common.publish' }))
+ await user.click(screen.getByRole('button', { name: 'appDebug.operation.applyConfig' }))
+ await user.click(await screen.findByRole('menuitem', { name: /GPT-4o/ }))
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'appDebug.operation.applyConfig' })).toBeDisabled(),
+ )
await waitFor(() => {
expect(mockOnPublish).toHaveBeenCalledWith(
- { id: 'model-1', model: 'gpt-4o', provider: 'openai', parameters: {} },
+ expect.objectContaining({
+ id: 'model-1',
+ model: 'gpt-4o',
+ provider: 'openai',
+ parameters: {},
+ }),
mockFeatures,
)
})
})
- it('should pass publish notification options through to onPublish', async () => {
- const user = userEvent.setup()
- render(
- <FeaturesWrappedAppPublisher
- appId="app-1"
- publishedConfig={publishedConfig}
- onPublish={mockOnPublish}
- />,
- )
-
- await user.click(screen.getByText('publish-silently-through-wrapper'))
-
- await waitFor(() => {
- expect(mockOnPublish).toHaveBeenCalledWith(undefined, mockFeatures, {
- showSuccessToast: false,
- })
- })
- })
-
it('should restore published features after confirmation', async () => {
const user = userEvent.setup()
render(
<FeaturesWrappedAppPublisher
appId="app-1"
+ publishedAt={1710000100000}
publishedConfig={publishedConfig}
resetAppConfig={resetAppConfig}
/>,
)
- await user.click(screen.getByText('restore-through-wrapper'))
+ await user.click(screen.getByRole('button', { name: 'workflow.common.publish' }))
+ await user.click(screen.getByRole('button', { name: 'workflow.common.restore' }))
expect(store.getState().features).toEqual(mockFeatures)
expect(resetAppConfig).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: /(?:^|\.)operation\.confirm(?=$|:)/ }))
@@ -193,12 +172,14 @@ describe('FeaturesWrappedAppPublisher', () => {
render(
<FeaturesWrappedAppPublisher
appId="app-1"
+ publishedAt={1710000100000}
publishedConfig={publishedConfig}
resetAppConfig={resetAppConfig}
/>,
)
- await user.click(screen.getByText('restore-through-wrapper'))
+ await user.click(screen.getByRole('button', { name: 'workflow.common.publish' }))
+ await user.click(screen.getByRole('button', { name: 'workflow.common.restore' }))
const dialog = screen.getByRole('alertdialog')
await user.click(
diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/component.spec.tsx b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/component.spec.tsx
index a04943f01ec..e14f21afe8c 100644
--- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/component.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/component.spec.tsx
@@ -10,6 +10,7 @@ import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { $createParagraphNode, $getRoot } from 'lexical'
+import { useStoreApi } from 'reactflow'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { Type } from '@/app/components/workflow/nodes/llm/types'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
@@ -18,13 +19,6 @@ import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { UPDATE_WORKFLOW_NODES_MAP } from '../index'
import { $createWorkflowVariableBlockNode, WorkflowVariableBlockNode } from '../node'
-// The editor owns the jump coordinates; ReactFlow owns applying them to its canvas.
-const setViewport = vi.hoisted(() => vi.fn())
-vi.mock('reactflow', async (importOriginal) => {
- const actual = await importOriginal<typeof import('reactflow')>()
- return { ...actual, useReactFlow: () => ({ ...actual.useReactFlow(), setViewport }) }
-})
-
type Props = Omit<ComponentProps<typeof WorkflowVariableBlockComponent>, 'nodeKey'>
const nodeMap: WorkflowNodesMap = {
'node-1': {
@@ -40,9 +34,11 @@ const availableVariables = [
]
function renderVariables(props: Props[], hasContainer = true) {
+ let flowStore: ReturnType<typeof useStoreApi>
let editor: LexicalEditor
function Capture() {
;[editor] = useLexicalComposerContext()
+ flowStore = useStoreApi()
return null
}
const { queryClient } = createConsoleQueryWrapper()
@@ -89,19 +85,17 @@ function renderVariables(props: Props[], hasContainer = true) {
Object.defineProperty(container, 'clientWidth', { value: 1000, configurable: true })
Object.defineProperty(container, 'clientHeight', { value: 800, configurable: true })
}
- return { ...view, editor: editor! }
+ return { ...view, editor: editor!, flowStore: flowStore! }
}
describe('WorkflowVariableBlockComponent', () => {
it('requests a canvas jump to the referenced node while preserving zoom', async () => {
const user = userEvent.setup()
- renderVariables([
+ const { flowStore } = renderVariables([
{ variables: ['node-1', 'output'], workflowNodesMap: nodeMap, availableVariables },
])
await user.click(await screen.findByText('output'))
- await waitFor(() =>
- expect(setViewport).toHaveBeenCalledExactlyOnceWith({ x: 0, y: 140, zoom: 2 }),
- )
+ await waitFor(() => expect(flowStore.getState().transform).toEqual([0, 140, 2]))
})
it('updates every rendered variable after a workflow node-map broadcast', async () => {
@@ -135,7 +129,7 @@ describe('WorkflowVariableBlockComponent', () => {
expect(screen.getByText('Renamed B')).toBeInTheDocument()
expect(screen.queryByText('Node A')).not.toBeInTheDocument()
expect(screen.queryByText('Node B')).not.toBeInTheDocument()
- await user.hover(screen.getByText('output').closest('[data-base-ui-tooltip-trigger]')!)
+ await user.hover(screen.getByText('output'))
expect(await screen.findByText('workflow.errorMsg.invalidVariable')).toBeInTheDocument()
})
@@ -144,15 +138,13 @@ describe('WorkflowVariableBlockComponent', () => {
renderVariables([
{ variables: ['node-1', 'missing'], workflowNodesMap: nodeMap, availableVariables },
])
- await user.hover(
- (await screen.findByText('missing')).closest('[data-base-ui-tooltip-trigger]')!,
- )
+ await user.hover(await screen.findByText('missing'))
expect(await screen.findByText('workflow.errorMsg.invalidVariable')).toBeInTheDocument()
})
it('shows the nested path and computed type in the real preview', async () => {
const user = userEvent.setup()
- const getVarType = vi.fn(() => Type.number)
+ const getVarType = () => Type.number
renderVariables([
{
variables: ['node-1', 'output', 'field'],
@@ -162,12 +154,6 @@ describe('WorkflowVariableBlockComponent', () => {
},
])
await user.hover(await screen.findByText('field'))
- await waitFor(() =>
- expect(getVarType).toHaveBeenCalledWith({
- nodeId: 'node-1',
- valueSelector: ['node-1', 'output', 'field'],
- }),
- )
expect(await screen.findByText('output')).toBeInTheDocument()
expect(screen.getByText('number')).toBeInTheDocument()
})
@@ -177,27 +163,27 @@ describe('WorkflowVariableBlockComponent', () => {
async (namespace) => {
const user = userEvent.setup()
const variables = namespace === 'rag' ? ['rag', 'shared', 'answer'] : [namespace, 'answer']
- renderVariables([{ variables, workflowNodesMap: {} }])
+ const { flowStore } = renderVariables([{ variables, workflowNodesMap: {} }])
const label = await screen.findByText(namespace === 'sys' ? 'sys.answer' : 'answer')
await user.click(label)
- expect(setViewport).not.toHaveBeenCalled()
+ expect(flowStore.getState().transform).toEqual([0, 0, 2])
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument()
},
)
it('does not jump when the canvas container is absent', async () => {
const user = userEvent.setup()
- renderVariables(
+ const { flowStore } = renderVariables(
[{ variables: ['node-1', 'output'], workflowNodesMap: nodeMap, availableVariables }],
false,
)
await user.click(await screen.findByText('output'))
- expect(setViewport).not.toHaveBeenCalled()
+ expect(flowStore.getState().transform).toEqual([0, 0, 2])
})
it('keeps the viewport finite when a source node has not been measured', async () => {
const user = userEvent.setup()
- renderVariables([
+ const { flowStore } = renderVariables([
{
variables: ['node-1', 'output'],
workflowNodesMap: {
@@ -207,8 +193,6 @@ describe('WorkflowVariableBlockComponent', () => {
},
])
await user.click(await screen.findByText('output'))
- await waitFor(() =>
- expect(setViewport).toHaveBeenCalledExactlyOnceWith({ x: 200, y: 240, zoom: 2 }),
- )
+ await waitFor(() => expect(flowStore.getState().transform).toEqual([200, 240, 2]))
})
})
diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/permissions.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/permissions.spec.tsx
index 160e5f5ea4c..d4b621fabe0 100644
--- a/web/app/components/datasets/documents/detail/completed/__tests__/permissions.spec.tsx
+++ b/web/app/components/datasets/documents/detail/completed/__tests__/permissions.spec.tsx
@@ -3,11 +3,15 @@ import type {
SegmentResponse,
} from '@dify/contracts/api/console/datasets/types.gen'
import type { ParentMode } from '@/models/datasets'
-import { screen, within } from '@testing-library/react'
+import type { consoleClient } from '@/service/console'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import DatasetDetailContext from '@/context/dataset-detail'
+import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
import { ChunkingMode } from '@/models/datasets'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { createDatasetFixture } from '@/test/fixtures/dataset'
import { DocumentContext } from '../../context'
import Completed from '../index'
@@ -53,75 +57,101 @@ const segment: SegmentResponse = {
}
let parentMode: ParentMode = 'paragraph'
-const onChangeSwitch = vi.fn()
-const onDelete = vi.fn()
-const onUpdate = vi.fn()
-const onDeleteChildChunk = vi.fn()
-const onUpdateChildChunk = vi.fn()
-
-// Keep selection, cards, action bars and drawers real; isolate their data and mutation hooks.
-vi.mock('../hooks/use-segment-list-data', () => ({
- useSegmentListData: () => ({
- segments: [segment],
- segmentListData: { total: 1 },
- totalText: '1 chunk',
- isLoadingSegmentList: false,
- isFullDocMode: parentMode === 'full-doc',
- onChangeSwitch,
- onDelete,
- handleUpdateSegment: onUpdate,
- }),
-}))
-
-vi.mock('../hooks/use-child-segment-data', () => ({
- useChildSegmentData: () => ({
- childSegments: [childChunk],
- childChunkListData: { total: 1 },
- isLoadingChildSegmentList: false,
- onDeleteChildChunk,
- handleUpdateChildChunk: onUpdateChildChunk,
- }),
-}))
-
-vi.mock('@/context/dataset-detail', () => ({
- useDatasetDetailContextWithSelector: (
- selector: (state: { dataset: { indexing_technique: string; runtime_mode: string } }) => unknown,
- ) => selector({ dataset: { indexing_technique: 'high_quality', runtime_mode: 'general' } }),
-}))
-
-vi.mock('@/app/components/base/markdown', () => ({
- Markdown: ({ content }: { content: string }) => <div>{content}</div>,
-}))
-
-vi.mock('@/app/components/datasets/common/image-uploader/image-uploader-in-chunk', () => ({
- default: () => null,
+const api = vi.hoisted(() => ({
+ list: vi.fn<typeof consoleClient.datasets.byDatasetId.documents.byDocumentId.segments.get>(),
+ switch:
+ vi.fn<
+ typeof consoleClient.datasets.byDatasetId.documents.byDocumentId.segment.byAction.patch
+ >(),
+ remove: vi.fn<typeof consoleClient.datasets.byDatasetId.documents.byDocumentId.segments.delete>(),
+ update:
+ vi.fn<
+ typeof consoleClient.datasets.byDatasetId.documents.byDocumentId.segments.bySegmentId.patch
+ >(),
+ children:
+ vi.fn<
+ typeof consoleClient.datasets.byDatasetId.documents.byDocumentId.segments.bySegmentId.childChunks.get
+ >(),
+ removeChild: vi.fn(),
+ updateChild: vi.fn(),
}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ const { createFileUploadConfigFixture } = await import('@/test/fixtures/file-upload-config')
+ const prefix = 'datasets.byDatasetId.documents.byDocumentId.'
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'files.upload.get': async () => createFileUploadConfigFixture(),
+ [`${prefix}segments.get`]: api.list,
+ [`${prefix}segment.byAction.patch`]: api.switch,
+ [`${prefix}segments.delete`]: api.remove,
+ [`${prefix}segments.bySegmentId.patch`]: api.update,
+ [`${prefix}segments.bySegmentId.childChunks.get`]: api.children,
+ [`${prefix}segments.bySegmentId.childChunks.byChildChunkId.delete`]: api.removeChild,
+ [`${prefix}segments.bySegmentId.childChunks.byChildChunkId.patch`]: api.updateChild,
+ }),
+ }
+})
+let serverSegments: SegmentResponse[]
-function renderChunks(canEdit: boolean, docForm: ChunkingMode = ChunkingMode.text) {
- return render(
- // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector contexts are not React 19 context components.
- <DocumentContext.Provider
- value={{ datasetId: 'dataset-1', documentId: 'document-1', docForm, parentMode, canEdit }}
- >
- <Completed
- embeddingAvailable
- showNewSegmentModal={false}
- onNewSegmentModalChange={vi.fn()}
- importStatus={undefined}
- />
- </DocumentContext.Provider>,
+async function renderChunks(canEdit: boolean, docForm: ChunkingMode = ChunkingMode.text) {
+ const view = render(
+ <EventEmitterContextProvider>
+ {/* oxlint-disable-next-line eslint-react/no-context-provider -- Dataset detail uses use-context-selector. */}
+ <DatasetDetailContext.Provider value={{ dataset: createDatasetFixture({ id: 'dataset-1' }) }}>
+ {/* oxlint-disable-next-line eslint-react/no-context-provider -- Document context uses use-context-selector. */}
+ <DocumentContext.Provider
+ value={{ datasetId: 'dataset-1', documentId: 'document-1', docForm, parentMode, canEdit }}
+ >
+ <Completed
+ embeddingAvailable
+ showNewSegmentModal={false}
+ onNewSegmentModalChange={vi.fn()}
+ importStatus={undefined}
+ />
+ </DocumentContext.Provider>
+ </DatasetDetailContext.Provider>
+ </EventEmitterContextProvider>,
)
+ await screen.findByText(parentMode === 'full-doc' ? 'Child chunk content' : 'Chunk content')
+ return view
}
describe('Chunk permissions', () => {
beforeEach(() => {
- vi.clearAllMocks()
+ serverSegments = [{ ...segment }]
+ api.list.mockImplementation(async () => ({
+ data: serverSegments,
+ total: serverSegments.length,
+ total_pages: 1,
+ page: 1,
+ limit: 10,
+ has_more: false,
+ }))
+ api.children.mockResolvedValue({
+ data: [childChunk],
+ total: 1,
+ total_pages: 1,
+ page: 1,
+ limit: 10,
+ })
+ api.switch.mockResolvedValue({ result: 'success' })
+ api.remove.mockImplementation(async () => {
+ serverSegments = []
+ return { result: 'success' }
+ })
+ api.update.mockImplementation(async ({ body }) => ({
+ data: { ...segment, ...body },
+ doc_form: ChunkingMode.text,
+ }))
parentMode = 'paragraph'
})
it('should pass read-only permission to the batch actions and allow cancelling selection', async () => {
const user = userEvent.setup()
- renderChunks(false)
+ await renderChunks(false)
const checkbox = screen.getByRole('checkbox', { name: 'datasetDocuments.segment.chunk 1' })
await user.click(checkbox)
@@ -131,8 +161,8 @@ describe('Chunk permissions', () => {
expect(button).toBeDisabled()
await user.click(button)
}
- expect(onChangeSwitch).not.toHaveBeenCalled()
- expect(onDelete).not.toHaveBeenCalled()
+ expect(api.switch).not.toHaveBeenCalled()
+ expect(api.remove).not.toHaveBeenCalled()
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'dataset.batchAction.cancel' }))
@@ -144,25 +174,41 @@ describe('Chunk permissions', () => {
it('should allow batch mutations with edit permission', async () => {
const user = userEvent.setup()
- renderChunks(true)
+ serverSegments = [{ ...segment, enabled: false }]
+ await renderChunks(true)
await user.click(screen.getByRole('checkbox', { name: 'datasetDocuments.segment.chunk 1' }))
await user.click(screen.getByRole('button', { name: 'dataset.batchAction.enable' }))
- expect(onChangeSwitch).toHaveBeenCalledWith(true, '')
+ await waitFor(() => expect(screen.getByRole('switch')).toBeChecked())
+ expect(api.switch).toHaveBeenCalledWith({
+ params: { dataset_id: 'dataset-1', document_id: 'document-1', action: 'enable' },
+ query: { segment_id: ['segment-1'] },
+ })
await user.click(screen.getByRole('button', { name: 'dataset.batchAction.disable' }))
- expect(onChangeSwitch).toHaveBeenCalledWith(false, '')
+ await waitFor(() => expect(screen.getByRole('switch')).not.toBeChecked())
+ expect(api.switch).toHaveBeenLastCalledWith({
+ params: { dataset_id: 'dataset-1', document_id: 'document-1', action: 'disable' },
+ query: { segment_id: ['segment-1'] },
+ })
await user.click(screen.getByRole('button', { name: 'dataset.batchAction.delete' }))
const dialog = await screen.findByRole('alertdialog')
await user.click(within(dialog).getByRole('button', { name: 'common.operation.sure' }))
- expect(onDelete).toHaveBeenCalledWith('')
+ await waitFor(() => expect(screen.queryByText('Chunk content')).not.toBeInTheDocument())
+ expect(api.remove).toHaveBeenCalledExactlyOnceWith({
+ params: { dataset_id: 'dataset-1', document_id: 'document-1' },
+ query: { segment_id: ['segment-1'] },
+ })
+ expect(
+ screen.queryByRole('checkbox', { name: 'datasetDocuments.segment.chunk 1' }),
+ ).not.toBeInTheDocument()
})
it.each([ChunkingMode.text, ChunkingMode.qa, ChunkingMode.parentChild])(
'should open %s chunk content in read-only mode without edit permission',
async (docForm) => {
const user = userEvent.setup()
- renderChunks(false, docForm)
+ await renderChunks(false, docForm)
await user.click(screen.getByText('Chunk content'))
const dialog = await screen.findByRole('dialog')
@@ -181,7 +227,7 @@ describe('Chunk permissions', () => {
within(dialog).queryByRole('button', { name: /common.operation.save/ }),
).not.toBeInTheDocument()
await user.keyboard('{Control>}s{/Control}{Meta>}s{/Meta}')
- expect(onUpdate).not.toHaveBeenCalled()
+ expect(api.update).not.toHaveBeenCalled()
await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
},
@@ -189,7 +235,7 @@ describe('Chunk permissions', () => {
it('should allow editing chunk content with edit permission', async () => {
const user = userEvent.setup()
- renderChunks(true)
+ await renderChunks(true)
await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
const dialog = await screen.findByRole('dialog')
@@ -197,15 +243,13 @@ describe('Chunk permissions', () => {
expect(input).toBeEnabled()
await user.type(input, ' updated')
await user.click(within(dialog).getByRole('button', { name: /common.operation.save/ }))
- expect(onUpdate).toHaveBeenCalledWith(
- 'segment-1',
- 'Chunk content updated',
- '',
- [],
- [],
- '',
- false,
- )
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(await screen.findByText('Chunk content updated')).toBeInTheDocument()
+ expect(screen.queryByText('Chunk content')).not.toBeInTheDocument()
+ expect(api.update).toHaveBeenCalledWith({
+ params: { dataset_id: 'dataset-1', document_id: 'document-1', segment_id: 'segment-1' },
+ body: { content: 'Chunk content updated', attachment_ids: [], summary: '' },
+ })
})
it.each(['paragraph', 'full-doc'] as const)(
@@ -213,7 +257,7 @@ describe('Chunk permissions', () => {
async (mode) => {
const user = userEvent.setup()
parentMode = mode
- renderChunks(false, ChunkingMode.parentChild)
+ await renderChunks(false, ChunkingMode.parentChild)
const addButton = screen.getByRole('button', { name: 'common.operation.add' })
expect(addButton).toBeDisabled()
@@ -228,7 +272,7 @@ describe('Chunk permissions', () => {
const deleteButton = await screen.findByRole('button', { name: 'common.operation.remove' })
expect(deleteButton).toBeDisabled()
await user.click(deleteButton)
- expect(onDeleteChildChunk).not.toHaveBeenCalled()
+ expect(api.removeChild).not.toHaveBeenCalled()
await user.click(content)
const dialog = (await screen.findAllByRole('dialog')).find((element) =>
@@ -241,7 +285,7 @@ describe('Chunk permissions', () => {
within(dialog).queryByRole('button', { name: /common.operation.save/ }),
).not.toBeInTheDocument()
await user.keyboard('{Control>}s{/Control}{Meta>}s{/Meta}')
- expect(onUpdateChildChunk).not.toHaveBeenCalled()
+ expect(api.updateChild).not.toHaveBeenCalled()
},
)
})
diff --git a/web/app/components/snippet-list/__tests__/index.spec.tsx b/web/app/components/snippet-list/__tests__/index.spec.tsx
index 167f1fd7721..e06f076c7a0 100644
--- a/web/app/components/snippet-list/__tests__/index.spec.tsx
+++ b/web/app/components/snippet-list/__tests__/index.spec.tsx
@@ -1,19 +1,21 @@
+import type { SnippetListItemResponse as Snippet } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ReactNode } from 'react'
-import { render, screen, waitFor, within } from '@testing-library/react'
+import type { consoleClient } from '@/service/console'
+import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
-import * as React from 'react'
import { SnippetDetailTop } from '@/app/components/snippets/components/snippet-detail-top'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
import SnippetList from '..'
-const mockUseInfiniteSnippetList = vi.hoisted(() => vi.fn())
-vi.mock('@/service/use-snippets', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/use-snippets')>()),
- useInfiniteSnippetList: (params: unknown, options: unknown) =>
- mockUseInfiniteSnippetList(params, options),
-}))
+type SnippetListResponse = Awaited<
+ ReturnType<typeof consoleClient.workspaces.current.customizedSnippets.get>
+>
+const listSnippets = vi.hoisted(() =>
+ vi.fn<typeof consoleClient.workspaces.current.customizedSnippets.get>(),
+)
const mockBindTags = vi.hoisted(() => vi.fn())
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
@@ -23,6 +25,7 @@ vi.mock('@/service/console', async (importOriginal) => {
...actual,
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'tagBindings.post': mockBindTags,
+ 'workspaces.current.customizedSnippets.get': listSnippets,
}),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.members.get': async () => ({
@@ -39,60 +42,12 @@ vi.mock('@/service/console', async (importOriginal) => {
}
})
-const mockWorkspacePermissionKeys = vi.fn(() => ['snippets.create_and_modify'])
-
-vi.mock('@/context/workspace-state', async () => {
- const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
- return createWorkspaceStateModuleMock(() => ({
- userProfile: { id: 'creator-1' },
- currentWorkspace: { id: 'workspace-1' },
- isLoadingCurrentWorkspace: false,
- workspacePermissionKeys: mockWorkspacePermissionKeys(),
- }))
-})
-vi.mock('@/context/permission-state', async () => {
- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
- return createPermissionStateModuleMock(() => ({
- userProfile: { id: 'creator-1' },
- currentWorkspace: { id: 'workspace-1' },
- isLoadingCurrentWorkspace: false,
- workspacePermissionKeys: mockWorkspacePermissionKeys(),
- }))
-})
-
+let workspacePermissionKeys = ['snippets.create_and_modify']
vi.mock('@/next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
useSearchParams: () => new URLSearchParams(''),
}))
-vi.mock('next/dynamic', () => ({
- default: () => {
- return function MockDynamicComponent(props: {
- show: boolean
- onClose: () => void
- onTagsChange: () => void
- }) {
- return React.createElement(
- 'div',
- {
- 'data-testid': 'tag-management-modal',
- 'data-show': String(props.show),
- },
- React.createElement(
- 'button',
- { type: 'button', onClick: props.onClose },
- 'close tag modal',
- ),
- React.createElement(
- 'button',
- { type: 'button', onClick: props.onTagsChange },
- 'refresh tags',
- ),
- )
- }
- },
-}))
-
let intersectionCallback: IntersectionObserverCallback | undefined
const mockObserve = vi.fn()
const mockDisconnect = vi.fn()
@@ -116,56 +71,65 @@ beforeEach(() => {
} as unknown as typeof IntersectionObserver,
)
})
-afterEach(() => vi.unstubAllGlobals())
-const mockRefetch = vi.fn()
-const mockFetchNextPage = vi.fn()
-
-const mockSnippetListState = {
- data: {
- pages: [
- {
- data: [
- {
- id: 'snippet-1',
- name: 'Sales Snippet',
- description: 'Builds a sales follow-up.',
- type: 'node',
- is_published: true,
- use_count: 12,
- tags: [],
- created_at: 1704067200,
- created_by: 'creator-1',
- updated_at: 1704153600,
- updated_by: 'creator-2',
- },
- ],
- page: 1,
- limit: 30,
- total: 1,
- has_more: false,
- },
- ],
- },
- isLoading: false,
- isFetching: false,
- isFetchingNextPage: false,
- hasNextPage: false,
- error: null as Error | null,
-}
+const snippet = (overrides: Partial<Snippet> = {}): Snippet => ({
+ id: 'snippet-1',
+ name: 'Sales Snippet',
+ description: 'Builds a sales follow-up.',
+ type: 'node',
+ is_published: true,
+ use_count: 12,
+ tags: [],
+ author_name: null,
+ icon_info: null,
+ version: 1,
+ created_at: 1704067200,
+ created_by: 'creator-1',
+ updated_at: 1704153600,
+ updated_by: 'creator-2',
+ ...overrides,
+})
+const page = (
+ data = [snippet()],
+ overrides: Partial<SnippetListResponse> = {},
+): SnippetListResponse => ({
+ data,
+ page: 1,
+ limit: 30,
+ total: data.length,
+ has_more: false,
+ ...overrides,
+})
+const fullPage = () =>
+ page(
+ Array.from({ length: 30 }, (_, index) =>
+ snippet({
+ id: `snippet-${index + 1}`,
+ name: index ? `Snippet ${index + 1}` : 'Sales Snippet',
+ }),
+ ),
+ { total: 31, has_more: true },
+ )
const renderList = ({
searchParams = '',
}: {
searchParams?: string
} = {}) => {
- const { wrapper: ConsoleQueryWrapper } = createConsoleQueryWrapper({
+ const { wrapper: ConsoleQueryWrapper, queryClient } = createConsoleQueryWrapper({
accountProfile: { id: 'creator-1' },
+ workspacePermissionKeys,
})
const onUrlUpdate = vi.fn()
const createRoute = (path: string, params: string, content: ReactNode) => (
<ConsoleQueryWrapper>
- <NuqsTestingAdapter key={path} searchParams={params} hasMemory onUrlUpdate={onUrlUpdate}>
+ <NuqsTestingAdapter
+ rateLimitFactor={0}
+ key={path}
+ searchParams={params}
+ hasMemory
+ onUrlUpdate={onUrlUpdate}
+ >
{content}
</NuqsTestingAdapter>
</ConsoleQueryWrapper>
@@ -175,6 +139,7 @@ const renderList = ({
return {
...rendered,
+ queryClient,
onUrlUpdate,
rerenderList: () => rendered.rerender(createList()),
showDetail: () =>
@@ -184,488 +149,306 @@ const renderList = ({
}
}
-describe('SnippetList', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockBindTags.mockResolvedValue({ result: 'success' })
- mockWorkspacePermissionKeys.mockReturnValue(['snippets.create_and_modify'])
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
- intersectionCallback = undefined
- })
-
- it('renders the dedicated snippets list layout', () => {
- renderList()
-
- expect(screen.getByRole('link', { name: 'navigation.menus.apps' })).toHaveAttribute(
- 'href',
- '/apps',
- )
- expect(screen.getByRole('heading', { name: 'workflow.tabs.snippets' })).toBeInTheDocument()
- const path = within(screen.getByRole('navigation', { name: 'workflow.tabs.snippets' }))
- expect(path.getByRole('link', { name: 'navigation.menus.apps' })).toHaveAttribute(
- 'href',
- '/apps',
- )
- expect(path.getByText('workflow.tabs.snippets')).toHaveAttribute('aria-current', 'page')
- expect(screen.getByText('app.studio.filters.creators')).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: /workflow\.common\.published \/ snippet\.draft/i }),
- ).toBeInTheDocument()
- expect(screen.getByText('common.tag.placeholder')).toBeInTheDocument()
- expect(screen.getByPlaceholderText('workflow.tabs.searchSnippets')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'snippet.create' })).toBeInTheDocument()
- expect(screen.getByRole('link', { name: /Sales Snippet/ })).toHaveAttribute(
- 'href',
- '/snippets/snippet-1/orchestrate',
- )
- expect(screen.getByTestId('tag-management-modal')).toBeInTheDocument()
- })
-
- it('combines URL search and tags with the selected creator when requesting snippets', async () => {
- const user = userEvent.setup()
- renderList({ searchParams: '?tagIDs=tag-1;tag-2&keywords=sales' })
- await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))
- await user.click(await screen.findByRole('option', { name: /Bob/ }))
- await waitFor(() =>
- expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(
- {
- page: 1,
- limit: 30,
- keyword: 'sales',
- tag_ids: ['tag-1', 'tag-2'],
- creator_ids: ['creator-2'],
- },
- { enabled: true },
- ),
- )
- })
-
- it('restores creator, tag and publication filters from the URL', () => {
- renderList({
- searchParams:
- '?creatorIDs=creator-1;creator-2&tagIDs=tag-1;tag-2&keywords=sales&publishStatus=draft',
- })
- expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(
- {
- page: 1,
- limit: 30,
- keyword: 'sales',
- creator_ids: ['creator-1', 'creator-2'],
- tag_ids: ['tag-1', 'tag-2'],
- is_published: false,
- },
- { enabled: true },
- )
- expect(screen.getByRole('button', { name: 'snippet.draft' })).toBeInTheDocument()
- })
-
- it('retains creator, tag and publication selections through the snippet return link', async () => {
- const user = userEvent.setup()
- const { onUrlUpdate, showDetail, showList } = renderList()
- await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))
- await user.click(await screen.findByRole('option', { name: /Alice/ }))
- await user.click(screen.getByRole('option', { name: /Bob/ }))
- await user.keyboard('{Escape}')
- await user.click(screen.getByRole('combobox', { name: 'common.tag.placeholder' }))
- await user.click(await screen.findByRole('option', { name: 'Sales' }))
- await user.keyboard('{Escape}')
- await user.click(
- screen.getByRole('button', { name: 'workflow.common.published / snippet.draft' }),
- )
- await user.click(await screen.findByRole('menuitemradio', { name: 'snippet.draft' }))
- await waitFor(() =>
- expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('publishStatus')).toBe('draft'),
- )
-
- showDetail()
- const href = screen.getByRole('link', { name: 'workflow.tabs.snippets' }).getAttribute('href')!
- const params = new URLSearchParams(href.split('?')[1])
- expect(params.get('creatorIDs')).toBe('creator-1;creator-2')
- expect(params.get('tagIDs')).toBe('tag-1')
- expect(params.get('publishStatus')).toBe('draft')
- showList(href)
- expect(screen.getByRole('button', { name: 'snippet.draft' })).toBeInTheDocument()
- expect(await screen.findByRole('combobox', { name: 'Sales' })).toBeInTheDocument()
- await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))
- expect(await screen.findByRole('option', { name: /Alice/ })).toHaveAttribute(
- 'aria-selected',
- 'true',
- )
- expect(screen.getByRole('option', { name: /Bob/ })).toHaveAttribute('aria-selected', 'true')
- expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(
- expect.objectContaining({
- creator_ids: ['creator-1', 'creator-2'],
- tag_ids: ['tag-1'],
- is_published: false,
- }),
- { enabled: true },
- )
- })
-
- it('does not restore cleared creators, tags or publication status', async () => {
- const user = userEvent.setup()
- const { onUrlUpdate, showDetail, showList } = renderList({
- searchParams: '?creatorIDs=creator-1&tagIDs=tag-1&publishStatus=published',
- })
- await user.click(screen.getByRole('button', { name: 'app.studio.filters.reset' }))
- await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))
- await user.click(screen.getByRole('button', { name: 'workflow.common.published' }))
- await user.click(await screen.findByRole('menuitemradio', { name: 'app.types.all' }))
- await waitFor(() => expect(onUrlUpdate.mock.lastCall?.[0].searchParams.toString()).toBe(''))
- showDetail()
- expect(screen.getByRole('link', { name: 'workflow.tabs.snippets' })).toHaveAttribute(
- 'href',
- '/snippets',
- )
- showList('/snippets')
- expect(
- screen.queryByRole('button', { name: 'app.studio.filters.reset' }),
- ).not.toBeInTheDocument()
- expect(screen.getByRole('combobox', { name: 'common.tag.placeholder' })).toBeInTheDocument()
- expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(
- { page: 1, limit: 30, keyword: '' },
- { enabled: true },
- )
- })
-
- it.each([
- { label: 'workflow.common.published', published: true },
- { label: 'snippet.draft', published: false },
- ])('filters $label and returns to all statuses', async ({ label, published }) => {
- const user = userEvent.setup()
- renderList()
- await user.click(
- screen.getByRole('button', { name: /workflow\.common\.published \/ snippet\.draft/i }),
- )
- await user.click(await screen.findByRole('menuitemradio', { name: label }))
- expect(screen.getByRole('button', { name: label })).toBeInTheDocument()
- expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(
- expect.objectContaining({ is_published: published }),
- { enabled: true },
- )
- await user.click(screen.getByRole('button', { name: label }))
- await user.click(await screen.findByRole('menuitemradio', { name: 'app.types.all' }))
- expect(
- screen.getByRole('button', { name: /workflow\.common\.published \/ snippet\.draft/i }),
- ).toBeInTheDocument()
- expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(
- expect.not.objectContaining({ is_published: expect.any(Boolean) }),
- { enabled: true },
- )
- })
-
- it('searches and clears the filter through actual query state', async () => {
- const user = userEvent.setup()
- const { onUrlUpdate } = renderList()
- const search = screen.getByRole('searchbox', { name: 'workflow.tabs.searchSnippets' })
- await user.type(search, 'summary')
- expect(search).toHaveValue('summary')
- await waitFor(() =>
- expect(mockUseInfiniteSnippetList.mock.lastCall?.[0].keyword).toBe('summary'),
- )
- await waitFor(() =>
- expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('keywords')).toBe('summary'),
- )
- await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))
- expect(search).toHaveValue('')
- await waitFor(() =>
- expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(
- expect.objectContaining({ keyword: '' }),
- { enabled: true },
- ),
- )
- await waitFor(() =>
- expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has('keywords')).toBe(false),
- )
- })
-
- it('fetches snippets without create action for users with snippet management permission', () => {
- mockWorkspacePermissionKeys.mockReturnValue(['snippets.management'])
-
- renderList()
-
- expect(mockUseInfiniteSnippetList).toHaveBeenCalledWith(expect.any(Object), {
- enabled: true,
- })
- expect(screen.getByRole('link', { name: /Sales Snippet/ })).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'snippet.create' })).not.toBeInTheDocument()
- })
-
- it('does not fetch or render snippets without snippet list permissions', () => {
- mockWorkspacePermissionKeys.mockReturnValue([])
-
- const { container } = renderList()
- const list = container.querySelector<HTMLElement>('[aria-busy]')
- if (!list) throw new Error('Snippet list did not render its result owner')
-
- expect(mockUseInfiniteSnippetList).toHaveBeenCalledWith(expect.any(Object), {
- enabled: false,
- })
- expect(screen.queryByRole('link', { name: /Sales Snippet/ })).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'snippet.create' })).not.toBeInTheDocument()
- expect(within(list).getByText('workflow.tabs.noSnippetsFound')).toBeInTheDocument()
- })
-
- it('shows an empty state when no snippets are returned', () => {
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- data: {
- pages: [
- {
- data: [],
- page: 1,
- limit: 30,
- total: 0,
- has_more: false,
- },
- ],
- },
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
-
- const { container } = renderList()
- const list = container.querySelector<HTMLElement>('[aria-busy]')
- if (!list) throw new Error('Snippet list did not render its result owner')
-
- expect(within(list).getByText('workflow.tabs.noSnippetsFound')).toBeInTheDocument()
- expect(screen.getByRole('status')).toHaveTextContent('workflow.tabs.noSnippetsFound')
- })
-
- it('announces request failures and preserves retry focus while refetching', async () => {
- const user = userEvent.setup()
- const requestError = new Error('Request failed')
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- data: { pages: [] },
- error: requestError,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
-
- const { rerenderList } = renderList()
- const status = screen.getByRole('status')
- const retryButton = screen.getByRole('button', { name: 'common.operation.retry' })
-
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
- expect(status).toHaveTextContent('common.errorBoundary.title')
- expect(status).not.toHaveTextContent('workflow.tabs.noSnippetsFound')
-
- await user.click(retryButton)
-
- expect(mockRefetch).toHaveBeenCalledTimes(1)
- expect(retryButton).toHaveFocus()
-
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- data: { pages: [] },
- error: requestError,
- isFetching: true,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
- rerenderList()
-
- expect(screen.getByRole('button', { name: 'common.operation.retry' })).toBe(retryButton)
- expect(retryButton).toHaveFocus()
- expect(status).toHaveTextContent('common.loading')
+beforeEach(() => {
+ listSnippets.mockReset().mockResolvedValue(page())
+ mockBindTags.mockReset().mockResolvedValue({ result: 'success' })
+ workspacePermissionKeys = ['snippets.create_and_modify']
+})
+afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+})
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- data: { pages: [] },
- error: requestError,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
- rerenderList()
+const salesCard = () => screen.findByRole('link', { name: /Sales Snippet/ })
+const searchParams = (query: Record<string, unknown>) => ({
+ query: { page: 1, limit: 30, ...query },
+})
- expect(screen.getByRole('button', { name: 'common.operation.retry' })).toBe(retryButton)
- expect(retryButton).toHaveFocus()
- expect(status).toHaveTextContent('common.errorBoundary.title')
- })
+it('renders the snippet layout and links after the request resolves', async () => {
+ renderList()
+ expect(await salesCard()).toHaveAttribute('href', '/snippets/snippet-1/orchestrate')
+ expect(screen.getByRole('heading', { name: 'workflow.tabs.snippets' })).toBeInTheDocument()
+ const path = within(screen.getByRole('navigation', { name: 'workflow.tabs.snippets' }))
+ expect(path.getByRole('link', { name: 'navigation.menus.apps' })).toHaveAttribute('href', '/apps')
+ expect(path.getByText('workflow.tabs.snippets')).toHaveAttribute('aria-current', 'page')
+ expect(screen.getByRole('button', { name: 'snippet.create' })).toBeInTheDocument()
+})
- it('announces the total result count when only the first page is loaded', () => {
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- data: {
- pages: [
- {
- ...mockSnippetListState.data.pages[0]!,
- total: 80,
- has_more: true,
- },
- ],
- },
- hasNextPage: true,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
+it('combines URL search and tags with the selected creator in the service request', async () => {
+ const user = userEvent.setup()
+ renderList({ searchParams: '?tagIDs=tag-1;tag-2&keywords=sales' })
+ await salesCard()
+ await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))
+ await user.click(await screen.findByRole('option', { name: /Bob/ }))
+ await waitFor(() =>
+ expect(listSnippets).toHaveBeenLastCalledWith(
+ searchParams({ keyword: 'sales', tag_ids: ['tag-1', 'tag-2'], creators: ['creator-2'] }),
+ ),
+ )
+})
- renderList()
+it('retains creator, tag and publication selections through the snippet return link', async () => {
+ const user = userEvent.setup()
+ const { onUrlUpdate, showDetail, showList } = renderList()
+ await salesCard()
+ await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))
+ await user.click(await screen.findByRole('option', { name: /Alice/ }))
+ await user.click(screen.getByRole('option', { name: /Bob/ }))
+ await user.keyboard('{Escape}')
+ await user.click(screen.getByRole('combobox', { name: 'common.tag.placeholder' }))
+ await user.click(await screen.findByRole('option', { name: 'Sales' }))
+ await user.keyboard('{Escape}')
+ await user.click(
+ screen.getByRole('button', { name: 'workflow.common.published / snippet.draft' }),
+ )
+ await user.click(await screen.findByRole('menuitemradio', { name: 'snippet.draft' }))
+ await waitFor(() =>
+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('publishStatus')).toBe('draft'),
+ )
+ showDetail()
+ const href = screen.getByRole('link', { name: 'workflow.tabs.snippets' }).getAttribute('href')!
+ const params = new URLSearchParams(href.split('?')[1])
+ expect(params.get('creatorIDs')).toBe('creator-1;creator-2')
+ expect(params.get('tagIDs')).toBe('tag-1')
+ expect(params.get('publishStatus')).toBe('draft')
+ showList(href)
+ await salesCard()
+ expect(screen.getByRole('button', { name: 'snippet.draft' })).toBeInTheDocument()
+ expect(await screen.findByRole('combobox', { name: 'Sales' })).toBeInTheDocument()
+ await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))
+ expect(await screen.findByRole('option', { name: /Alice/ })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ )
+ expect(screen.getByRole('option', { name: /Bob/ })).toHaveAttribute('aria-selected', 'true')
+ expect(listSnippets).toHaveBeenLastCalledWith(
+ searchParams({ creators: ['creator-1', 'creator-2'], tag_ids: ['tag-1'], is_published: false }),
+ )
+})
- expect(screen.getByRole('status')).toHaveTextContent(
- 'common.operation.searchCount:{"count":80,"content":"workflow.tabs.snippets"}',
- )
+it('does not restore cleared creators, tags or publication status', async () => {
+ const user = userEvent.setup()
+ const { onUrlUpdate, showDetail, showList } = renderList({
+ searchParams: '?creatorIDs=creator-1&tagIDs=tag-1&publishStatus=published',
})
+ await salesCard()
+ await user.click(screen.getByRole('button', { name: 'app.studio.filters.reset' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))
+ await user.click(screen.getByRole('button', { name: 'workflow.common.published' }))
+ await user.click(await screen.findByRole('menuitemradio', { name: 'app.types.all' }))
+ await waitFor(() => expect(onUrlUpdate.mock.lastCall?.[0].searchParams.toString()).toBe(''))
+ showDetail()
+ expect(screen.getByRole('link', { name: 'workflow.tabs.snippets' })).toHaveAttribute(
+ 'href',
+ '/snippets',
+ )
+ showList('/snippets')
+ await salesCard()
+ expect(screen.queryByRole('button', { name: 'app.studio.filters.reset' })).not.toBeInTheDocument()
+ expect(screen.getByRole('combobox', { name: 'common.tag.placeholder' })).toBeInTheDocument()
+ expect(listSnippets).toHaveBeenLastCalledWith(searchParams({}))
+})
- it('announces kept-data refreshes when the result count stays the same', () => {
- const { rerenderList } = renderList()
- const status = screen.getByRole('status')
- const grid = screen.getByRole('link', { name: /Sales Snippet/ }).closest('[aria-busy]')
-
- expect(status.closest('[aria-busy]')).toBeNull()
- expect(status).toHaveTextContent(
- 'common.operation.searchCount:{"count":1,"content":"workflow.tabs.snippets"}',
- )
-
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- isFetching: true,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
- rerenderList()
-
- expect(screen.getByRole('status')).toBe(status)
- expect(status).toHaveTextContent('common.loading')
- expect(grid).toHaveAttribute('aria-busy', 'true')
-
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- data: {
- pages: [
- {
- ...mockSnippetListState.data.pages[0]!,
- data: [
- {
- ...mockSnippetListState.data.pages[0]!.data[0]!,
- id: 'snippet-2',
- name: 'Support Snippet',
- },
- ],
- },
- ],
- },
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
- rerenderList()
+it.each([
+ { label: 'workflow.common.published', published: true },
+ { label: 'snippet.draft', published: false },
+])('filters $label and returns to all statuses', async ({ label, published }) => {
+ const user = userEvent.setup()
+ listSnippets.mockImplementation(
+ async ({ query }: NonNullable<Parameters<typeof listSnippets>[0]> = {}) =>
+ page([
+ snippet({
+ name: typeof query?.is_published === 'boolean' ? 'Filtered snippet' : 'Sales Snippet',
+ }),
+ ]),
+ )
+ renderList()
+ await salesCard()
+ await user.click(
+ screen.getByRole('button', { name: 'workflow.common.published / snippet.draft' }),
+ )
+ await user.click(await screen.findByRole('menuitemradio', { name: label }))
+ expect(await screen.findByRole('link', { name: /Filtered snippet/ })).toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: /Sales Snippet/ })).not.toBeInTheDocument()
+ expect(listSnippets).toHaveBeenLastCalledWith(searchParams({ is_published: published }))
+ await user.click(screen.getByRole('button', { name: label }))
+ await user.click(await screen.findByRole('menuitemradio', { name: 'app.types.all' }))
+ expect(await salesCard()).toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: /Filtered snippet/ })).not.toBeInTheDocument()
+})
- expect(screen.getByRole('status')).toBe(status)
- expect(status).toHaveTextContent(
- 'common.operation.searchCount:{"count":1,"content":"workflow.tabs.snippets"}',
- )
- expect(screen.getByRole('link', { name: /Support Snippet/ })).toBeInTheDocument()
- expect(grid).toHaveAttribute('aria-busy', 'false')
+it('searches and clears the filter through actual query state', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
+ vi.stubGlobal('jest', { advanceTimersByTime: vi.advanceTimersByTime })
+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
+ listSnippets.mockImplementation(
+ async ({ query }: NonNullable<Parameters<typeof listSnippets>[0]> = {}) =>
+ page([snippet({ name: query?.keyword ? 'Summary snippet' : 'Sales Snippet' })]),
+ )
+ const { onUrlUpdate } = renderList()
+ await salesCard()
+ const search = screen.getByRole('searchbox', { name: 'workflow.tabs.searchSnippets' })
+ await user.type(search, 'summary')
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500)
})
-
- it('mounts an empty live region before announcing initial results', () => {
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- data: { pages: [] },
- isFetching: true,
- isLoading: true,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
-
- const { container, rerenderList } = renderList()
- const status = screen.getByRole('status')
-
- expect(status).toBeEmptyDOMElement()
- expect(status.closest('[aria-busy]')).toBeNull()
- expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument()
-
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
- rerenderList()
-
- expect(screen.getByRole('status')).toBe(status)
- expect(status).toHaveTextContent(
- 'common.operation.searchCount:{"count":1,"content":"workflow.tabs.snippets"}',
- )
+ expect(await screen.findByRole('link', { name: /Summary snippet/ })).toBeInTheDocument()
+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('keywords')).toBe('summary')
+ expect(listSnippets).toHaveBeenLastCalledWith(searchParams({ keyword: 'summary' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500)
})
+ expect(await salesCard()).toBeInTheDocument()
+ expect(search).toHaveValue('')
+ await waitFor(() =>
+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.has('keywords')).toBe(false),
+ )
+})
- it('keeps current results available while the next page is loading', () => {
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- isFetchingNextPage: true,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
-
- renderList()
- const card = screen.getByRole('link', { name: /Sales Snippet/ })
- const list = card.closest('[aria-busy]')
+it('fetches snippets without create action for users with management permission', async () => {
+ workspacePermissionKeys = ['snippets.management']
+ renderList()
+ expect(await salesCard()).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'snippet.create' })).not.toBeInTheDocument()
+})
- expect(card).toBeInTheDocument()
- expect(list).toHaveAttribute('aria-busy', 'true')
- expect(screen.getByRole('status')).toHaveTextContent('common.loading')
- })
+it('does not fetch or register infinite scroll without list permissions', () => {
+ workspacePermissionKeys = []
+ renderList()
+ expect(listSnippets).not.toHaveBeenCalled()
+ expect(intersectionCallback).toBeUndefined()
+ expect(screen.queryByRole('link', { name: /Sales Snippet/ })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'snippet.create' })).not.toBeInTheDocument()
+ expect(screen.getByRole('status')).toHaveTextContent('workflow.tabs.noSnippetsFound')
+})
- it('fetches the next page when the scroll anchor intersects', () => {
- mockUseInfiniteSnippetList.mockReturnValue({
- ...mockSnippetListState,
- hasNextPage: true,
- refetch: mockRefetch,
- fetchNextPage: mockFetchNextPage,
- })
+it('announces an empty result after the request resolves', async () => {
+ listSnippets.mockResolvedValue(page([]))
+ renderList()
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent('workflow.tabs.noSnippetsFound'),
+ )
+ expect(screen.queryByRole('link', { name: /Sales Snippet/ })).not.toBeInTheDocument()
+})
- renderList()
+it('announces request and retry failures through the real query lifecycle', async () => {
+ const user = userEvent.setup()
+ const retry = createDeferred<SnippetListResponse>()
+ listSnippets.mockRejectedValueOnce(new Error('Request failed')).mockReturnValueOnce(retry.promise)
+ renderList()
+ const retryButton = await screen.findByRole('button', { name: 'common.operation.retry' })
+ const status = screen.getByRole('status')
+ expect(status).toHaveTextContent('common.errorBoundary.title')
+ await user.click(retryButton)
+ await waitFor(() => expect(listSnippets).toHaveBeenCalledTimes(2))
+ expect(screen.queryByRole('link', { name: /Sales Snippet/ })).not.toBeInTheDocument()
+ await act(async () => retry.reject(new Error('Retry failed')))
+ await waitFor(() => expect(status).toHaveTextContent('common.errorBoundary.title'))
+ expect(screen.getByRole('button', { name: 'common.operation.retry' })).toBeEnabled()
+})
- intersectionCallback?.(
+it('keeps the first page while loading the next and appends the new results on intersection', async () => {
+ const next = createDeferred<SnippetListResponse>()
+ listSnippets.mockResolvedValueOnce(fullPage()).mockReturnValueOnce(next.promise)
+ renderList()
+ await salesCard()
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'common.operation.searchCount:{"count":31,"content":"workflow.tabs.snippets"}',
+ )
+ expect(intersectionCallback).toBeDefined()
+ act(() =>
+ intersectionCallback!(
[{ isIntersecting: true } as IntersectionObserverEntry],
{} as IntersectionObserver,
- )
+ ),
+ )
+ await waitFor(() =>
+ expect(listSnippets).toHaveBeenLastCalledWith({ query: { page: 2, limit: 30 } }),
+ )
+ expect(screen.getByRole('link', { name: /Sales Snippet/ })).toBeInTheDocument()
+ await act(async () =>
+ next.resolve(
+ page([snippet({ id: 'snippet-31', name: 'Final snippet' })], { page: 2, total: 31 }),
+ ),
+ )
+ expect(await screen.findByRole('link', { name: /Final snippet/ })).toBeInTheDocument()
+ expect(screen.getByRole('link', { name: /Sales Snippet/ })).toBeInTheDocument()
+ expect(screen.getByRole('link', { name: /Snippet 30/ })).toBeInTheDocument()
+})
- expect(mockFetchNextPage).toHaveBeenCalledTimes(1)
+it('announces kept-data refreshes when the result count stays the same', async () => {
+ const refresh = createDeferred<SnippetListResponse>()
+ listSnippets.mockResolvedValueOnce(page()).mockReturnValueOnce(refresh.promise)
+ const { queryClient } = renderList()
+ await salesCard()
+ const status = screen.getByRole('status')
+ act(() => {
+ void queryClient.invalidateQueries({ queryKey: ['snippets', 'list'] })
})
+ await waitFor(() => expect(status).toHaveTextContent('common.loading'))
+ expect(screen.getByRole('link', { name: /Sales Snippet/ })).toBeInTheDocument()
+ await act(async () => refresh.resolve(page([snippet({ name: 'Support Snippet' })])))
+ expect(await screen.findByRole('link', { name: /Support Snippet/ })).toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: /Sales Snippet/ })).not.toBeInTheDocument()
+ expect(status).toHaveTextContent(
+ 'common.operation.searchCount:{"count":1,"content":"workflow.tabs.snippets"}',
+ )
+})
- it('does not register infinite scroll without snippet list permissions', () => {
- mockWorkspacePermissionKeys.mockReturnValue([])
-
- renderList()
-
- intersectionCallback?.(
- [{ isIntersecting: true } as IntersectionObserverEntry],
- {} as IntersectionObserver,
- )
- expect(mockFetchNextPage).not.toHaveBeenCalled()
- })
+it('mounts an empty live region before announcing initial results', async () => {
+ const initial = createDeferred<SnippetListResponse>()
+ listSnippets.mockReturnValue(initial.promise)
+ renderList()
+ const status = screen.getByRole('status')
+ expect(status).toBeEmptyDOMElement()
+ expect(screen.queryByRole('link', { name: /Sales Snippet/ })).not.toBeInTheDocument()
+ await act(async () => initial.resolve(page()))
+ expect(await salesCard()).toBeInTheDocument()
+ expect(status).toHaveTextContent(
+ 'common.operation.searchCount:{"count":1,"content":"workflow.tabs.snippets"}',
+ )
+})
- it('opens tag management from real filters and cards and refreshes after a binding change', async () => {
- const user = userEvent.setup()
- mockWorkspacePermissionKeys.mockReturnValue([
- 'snippets.create_and_modify',
- 'snippets.management',
- ])
- renderList()
- await user.click(screen.getByRole('combobox', { name: 'common.tag.placeholder' }))
- await user.click(await screen.findByRole('button', { name: 'common.tag.manageTags' }))
- expect(screen.getByTestId('tag-management-modal')).toHaveAttribute('data-show', 'true')
- await user.click(screen.getByRole('button', { name: 'close tag modal' }))
- expect(screen.getByTestId('tag-management-modal')).toHaveAttribute('data-show', 'false')
- await user.click(screen.getByRole('combobox', { name: 'common.tag.addTag: Sales Snippet' }))
- await user.click(await screen.findByRole('option', { name: 'Sales' }))
- await user.click(screen.getByRole('button', { name: 'common.tag.manageTags' }))
- expect(screen.getByTestId('tag-management-modal')).toHaveAttribute('data-show', 'true')
- await waitFor(() =>
- expect(mockBindTags).toHaveBeenCalledExactlyOnceWith(
- {
- body: { tag_ids: ['tag-1'], target_id: 'snippet-1', type: 'snippet' },
- },
- { context: { silent: true } },
- ),
- )
- await waitFor(() => expect(mockRefetch).toHaveBeenCalledOnce())
- await user.click(screen.getByRole('button', { name: 'refresh tags' }))
- expect(mockRefetch).toHaveBeenCalledTimes(2)
+it('opens real tag management from filters and cards and refreshes after a binding change', async () => {
+ const user = userEvent.setup()
+ workspacePermissionKeys = ['snippets.create_and_modify', 'snippets.management']
+ let tagged = false
+ mockBindTags.mockImplementation(async () => {
+ tagged = true
+ return { result: 'success' }
})
+ listSnippets.mockImplementation(async () =>
+ page([
+ snippet({
+ name: tagged ? 'Tagged snippet' : 'Sales Snippet',
+ tags: tagged ? [{ id: 'tag-1', name: 'Sales', type: 'snippet' }] : [],
+ }),
+ ]),
+ )
+ renderList()
+ await salesCard()
+ await user.click(screen.getByRole('combobox', { name: 'common.tag.placeholder' }))
+ await user.click(await screen.findByRole('button', { name: 'common.tag.manageTags' }))
+ const dialog = await screen.findByRole('dialog', { name: 'common.tag.manageTags' })
+ expect(within(dialog).getByRole('textbox', { name: 'common.tag.addNew' })).toBeInTheDocument()
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByRole('combobox', { name: 'common.tag.addTag: Sales Snippet' }))
+ await user.click(await screen.findByRole('option', { name: 'Sales' }))
+ await user.keyboard('{Escape}')
+ expect(await screen.findByRole('combobox', { name: 'Sales: Tagged snippet' })).toBeInTheDocument()
+ expect(mockBindTags).toHaveBeenCalledExactlyOnceWith(
+ {
+ body: { tag_ids: ['tag-1'], target_id: 'snippet-1', type: 'snippet' },
+ },
+ { context: { silent: true } },
+ )
+ await user.click(screen.getByRole('combobox', { name: 'Sales: Tagged snippet' }))
+ expect(await screen.findByRole('option', { name: 'Sales' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ )
+ await user.click(screen.getByRole('button', { name: 'common.tag.manageTags' }))
+ expect(await screen.findByRole('dialog', { name: 'common.tag.manageTags' })).toBeInTheDocument()
})
diff --git a/web/app/components/snippets/hooks/__tests__/use-create-snippet-from-selection.spec.tsx b/web/app/components/snippets/hooks/__tests__/use-create-snippet-from-selection.spec.tsx
index 9ab4e65b21c..0ed34372577 100644
--- a/web/app/components/snippets/hooks/__tests__/use-create-snippet-from-selection.spec.tsx
+++ b/web/app/components/snippets/hooks/__tests__/use-create-snippet-from-selection.spec.tsx
@@ -1,57 +1,76 @@
-import type { ReactNode } from 'react'
-import type { CreateSnippetDialogPayload } from '../../create-snippet-dialog'
import type { LLMNodeType } from '@/app/components/workflow/nodes/llm/types'
-import type { Edge, EnvironmentVariable, Node } from '@/app/components/workflow/types'
-import { act, render, renderHook, screen } from '@testing-library/react'
+import type { Edge, EnvironmentVariable } from '@/app/components/workflow/types'
+import type { SnippetCanvasData } from '@/models/snippet'
+import type { consoleClient } from '@/service/console'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createNode as createWorkflowNode } from '@/app/components/workflow/__tests__/fixtures'
import { BlockEnum } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { PipelineInputVarType } from '@/models/pipeline'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
import { useCreateSnippetFromSelection } from '../use-create-snippet-from-selection'
const SNIPPET_INPUT_FIELD_NODE_ID = 'start'
-const mockHandleOpenCreateSnippetDialog = vi.fn()
-const mockHandleCloseCreateSnippetDialog = vi.fn()
-const mockHandleCreateSnippet = vi.fn()
-
-vi.mock('../use-create-snippet', () => ({
- useCreateSnippet: () => ({
- createSnippetMutation: {
- isPending: false,
- },
- handleCloseCreateSnippetDialog: mockHandleCloseCreateSnippetDialog,
- handleCreateSnippet: mockHandleCreateSnippet,
- handleOpenCreateSnippetDialog: mockHandleOpenCreateSnippetDialog,
- isCreateSnippetDialogOpen: true,
- isCreatingSnippet: false,
- }),
+const api = vi.hoisted(() => ({
+ create: vi.fn<typeof consoleClient.workspaces.current.customizedSnippets.post>(),
+ save: vi.fn<typeof consoleClient.snippets.bySnippetId.workflows.draft.post>(),
+ push: vi.fn(),
}))
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: api.push }) }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.customizedSnippets.post': api.create,
+ 'snippets.bySnippetId.workflows.draft.post': api.save,
+ }),
+ }
+})
+
+function renderSelection(params: Parameters<typeof useCreateSnippetFromSelection>[0]) {
+ function Selection() {
+ const { handleOpenCreateSnippet, createSnippetDialog } = useCreateSnippetFromSelection(params)
+ return (
+ <>
+ <button type="button" onClick={handleOpenCreateSnippet}>
+ Create from selection
+ </button>
+ {createSnippetDialog}
+ </>
+ )
+ }
+ renderWithConsoleQuery(<Selection />, { workspacePermissionKeys: ['snippets.create_and_modify'] })
+ return userEvent.setup()
+}
vi.mock('@/app/notifications', () => ({
toast: { error: vi.fn() },
}))
-const submitDialog = async (dialog: ReactNode) => {
- const user = userEvent.setup()
- render(dialog)
+const submitDialog = async (user: ReturnType<typeof userEvent.setup>) => {
await user.type(
screen.getByRole('textbox', { name: 'workflow.snippet.nameLabel' }),
'Reusable selection',
)
await user.click(screen.getByRole('button', { name: 'workflow.snippet.confirm' }))
- expect(mockHandleCreateSnippet).toHaveBeenCalledOnce()
- return mockHandleCreateSnippet.mock.calls[0]![0] as CreateSnippetDialogPayload
+ await waitFor(() => expect(api.push).toHaveBeenCalledWith('/snippets/snippet-1/orchestrate'))
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(api.create).toHaveBeenCalledOnce()
+ const submitted = api.create.mock.calls[0]![0].body
+ expect(api.save).toHaveBeenCalledExactlyOnceWith({
+ params: { snippet_id: 'snippet-1' },
+ body: { graph: submitted.graph, input_fields: submitted.input_fields },
+ })
+ return { ...submitted, graph: submitted.graph as SnippetCanvasData }
}
-const createNode = (id: string, data: Record<string, unknown>): Node =>
- ({
- id,
- type: 'custom',
- position: { x: 0, y: 0 },
- width: 200,
- height: 100,
- data,
- }) as unknown as Node
+const createNode = (
+ id: string,
+ data: NonNullable<Parameters<typeof createWorkflowNode>[0]>['data'],
+) => createWorkflowNode({ id, width: 200, height: 100, data })
const llmEnvironmentVariable: EnvironmentVariable = {
id: 'model-env',
@@ -68,7 +87,24 @@ const llmEnvironmentVariable: EnvironmentVariable = {
describe('useCreateSnippetFromSelection', () => {
beforeEach(() => {
- vi.resetAllMocks()
+ api.create.mockImplementation(async ({ body }) => ({
+ id: 'snippet-1',
+ name: body.name,
+ type: body.type ?? 'group',
+ description: body.description ?? null,
+ graph: body.graph ?? {},
+ input_fields: body.input_fields ?? [],
+ created_at: 1,
+ created_by: null,
+ updated_at: 1,
+ updated_by: null,
+ is_published: false,
+ icon_info: null,
+ tags: [],
+ use_count: 0,
+ version: 1,
+ }))
+ api.save.mockResolvedValue({ result: 'success', hash: 'saved', updated_at: 1 })
})
it('should convert environment, conversation, and system variables into snippet input fields', async () => {
@@ -89,20 +125,16 @@ describe('useCreateSnippetFromSelection', () => {
const edges: Edge[] = []
const onClose = vi.fn()
- const { result } = renderHook(() =>
- useCreateSnippetFromSelection({
- edges,
- environmentVariables: [llmEnvironmentVariable],
- selectedNodes,
- onClose,
- }),
- )
-
- act(() => {
- result.current.handleOpenCreateSnippet()
+ const user = renderSelection({
+ edges,
+ environmentVariables: [llmEnvironmentVariable],
+ selectedNodes,
+ onClose,
})
- const submitted = await submitDialog(result.current.createSnippetDialog)
+ await user.click(screen.getByRole('button', { name: 'Create from selection' }))
+
+ const submitted = await submitDialog(user)
expect(submitted.input_fields).toEqual([
{
@@ -164,18 +196,16 @@ describe('useCreateSnippetFromSelection', () => {
model_selector: ['start', 'MODEL_NAME'],
}),
]
- const { result } = renderHook(() =>
- useCreateSnippetFromSelection({
- edges: [],
- environmentVariables: [],
- selectedNodes,
- onClose: vi.fn(),
- }),
- )
+ const user = renderSelection({
+ edges: [],
+ environmentVariables: [],
+ selectedNodes,
+ onClose: vi.fn(),
+ })
- act(() => result.current.handleOpenCreateSnippet())
+ await user.click(screen.getByRole('button', { name: 'Create from selection' }))
- const submitted = await submitDialog(result.current.createSnippetDialog)
+ const submitted = await submitDialog(user)
expect(submitted.input_fields).toEqual([])
expect((submitted.graph?.nodes[0]?.data as LLMNodeType).model_selector).toEqual([
'start',
@@ -197,22 +227,20 @@ describe('useCreateSnippetFromSelection', () => {
}),
]
const onClose = vi.fn()
- const { result } = renderHook(() =>
- useCreateSnippetFromSelection({
- edges: [],
- environmentVariables: [],
- selectedNodes,
- onClose,
- }),
- )
+ const user = renderSelection({
+ edges: [],
+ environmentVariables: [],
+ selectedNodes,
+ onClose,
+ })
- act(() => result.current.handleOpenCreateSnippet())
+ await user.click(screen.getByRole('button', { name: 'Create from selection' }))
expect(toast.error).toHaveBeenCalledWith(
'workflow.errorMsg.fieldRequired:{"field":"workflow.errorMsg.fields.model"}',
)
- expect(mockHandleCreateSnippet).not.toHaveBeenCalled()
- expect(mockHandleOpenCreateSnippetDialog).not.toHaveBeenCalled()
+ expect(api.create).not.toHaveBeenCalled()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(onClose).not.toHaveBeenCalled()
})
@@ -258,20 +286,16 @@ describe('useCreateSnippetFromSelection', () => {
]
const onClose = vi.fn()
- const { result } = renderHook(() =>
- useCreateSnippetFromSelection({
- edges: [],
- environmentVariables: [],
- selectedNodes,
- onClose,
- }),
- )
-
- act(() => {
- result.current.handleOpenCreateSnippet()
+ const user = renderSelection({
+ edges: [],
+ environmentVariables: [],
+ selectedNodes,
+ onClose,
})
- const submitted = await submitDialog(result.current.createSnippetDialog)
+ await user.click(screen.getByRole('button', { name: 'Create from selection' }))
+
+ const submitted = await submitDialog(user)
expect(submitted.input_fields).toEqual([
{
@@ -337,20 +361,16 @@ describe('useCreateSnippetFromSelection', () => {
]
const onClose = vi.fn()
- const { result } = renderHook(() =>
- useCreateSnippetFromSelection({
- edges: [],
- environmentVariables: [],
- selectedNodes,
- onClose,
- }),
- )
-
- act(() => {
- result.current.handleOpenCreateSnippet()
+ const user = renderSelection({
+ edges: [],
+ environmentVariables: [],
+ selectedNodes,
+ onClose,
})
- const submitted = await submitDialog(result.current.createSnippetDialog)
+ await user.click(screen.getByRole('button', { name: 'Create from selection' }))
+
+ const submitted = await submitDialog(user)
const nodeData = submitted.graph?.nodes[0]?.data as {
context?: {
enabled: boolean
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
index f077ce1eebc..d045c26349d 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
@@ -1,46 +1,62 @@
import type { AgentProviderResponse } from '@dify/contracts/api/console/workspaces/types.gen'
-import { screen, waitFor } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { createPlugin } from '@/app/components/workflow/block-selector/__tests__/factories'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { createInstalledPluginFixture } from '@/test/fixtures/plugin'
import { createProvider, createStrategy } from '../../../agent/__tests__/strategy-fixture'
import { AgentStrategySelector } from '../agent-strategy-selector'
-const { request, searchMarketplace, marketplaceResults, marketplace, install } = vi.hoisted(() => ({
+const { request, marketplace, install, manifest } = vi.hoisted(() => ({
request: vi.fn(),
- searchMarketplace: vi.fn(),
- marketplaceResults: vi.fn(),
marketplace: vi.fn(),
install: vi.fn(),
+ manifest: vi.fn(),
}))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
request,
+ postMarketplace: marketplace,
}))
-vi.mock('@/app/components/plugins/marketplace/hooks', () => ({
- useMarketplacePlugins: () => ({
- queryPluginsWithDebounced: searchMarketplace,
- plugins: marketplaceResults(),
- }),
-}))
-vi.mock('@/service/use-plugins', () => ({
- useFetchPluginsInMarketPlaceByIds: marketplace,
- useCheckInstalled: () => ({ data: { plugins: [] }, isLoading: false, refetch: vi.fn() }),
- useInstallPackageFromMarketPlace: () => ({ mutate: install, isPending: false }),
-}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.plugin.list.installations.ids.post': manifest,
+ }),
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.plugin.install.marketplace.post': install,
+ }),
+ }
+})
beforeEach(() => {
- vi.clearAllMocks()
request.mockReset()
- marketplaceResults.mockReturnValue([])
- marketplace.mockReturnValue({
- isLoading: false,
- data: { data: { plugins: [] } },
- refetch: vi.fn(),
- })
+ marketplace.mockReset().mockResolvedValue({ data: { plugins: [], total: 0 } })
+ manifest.mockReset().mockResolvedValue({ plugins: [] })
+ install.mockReset()
+})
+afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
})
+function searchUser() {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
+ vi.stubGlobal('jest', { advanceTimersByTime: vi.advanceTimersByTime })
+ return userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
+}
+async function finishSearch() {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500)
+ })
+}
+
function namedProvider(name: string, label: string, author: string): AgentProviderResponse {
const provider = createProvider()
return {
@@ -156,7 +172,7 @@ it('filters by provider identity without changing the saved selection or opening
expect(screen.queryByRole('button', { name: 'Display name' })).not.toBeInTheDocument()
expect(screen.getByText('tools.addToolModal.agent.title')).toBeInTheDocument()
expect(onChange).not.toHaveBeenCalled()
- expect(searchMarketplace).not.toHaveBeenCalled()
+ expect(marketplace).not.toHaveBeenCalled()
})
it('keeps letter navigation for long catalogs and removes it in tree view', async () => {
@@ -183,9 +199,14 @@ it('keeps letter navigation for long catalogs and removes it in tree view', asyn
it('keeps marketplace search and its category link alongside the installed catalog', async () => {
const user = userEvent.setup()
- marketplaceResults.mockReturnValue([
- createPlugin({ label: { en_US: 'Marketplace strategy', zh_Hans: 'Marketplace strategy' } }),
- ])
+ marketplace.mockResolvedValue({
+ data: {
+ total: 2,
+ plugins: [
+ createPlugin({ label: { en_US: 'Marketplace strategy', zh_Hans: 'Marketplace strategy' } }),
+ ],
+ },
+ })
request.mockImplementation(() => Promise.resolve(Response.json([createProvider()])))
render(<AgentStrategySelector onChange={vi.fn()} />, {
systemFeatures: { enable_marketplace: true },
@@ -195,24 +216,34 @@ it('keeps marketplace search and its category link alongside the installed catal
expect(new URL(link.getAttribute('href')!, window.location.href).pathname).toBe(
'/plugins/agent-strategy',
)
- await user.type(
+ await screen.findByRole('button', { name: 'Agent provider' })
+ const search = searchUser()
+ await search.type(
screen.getByPlaceholderText('workflowAgent.nodes.agent.strategy.searchPlaceholder'),
'react',
)
- expect(searchMarketplace).toHaveBeenLastCalledWith({
- query: 'react',
- category: PluginCategoryEnum.agent,
- })
- expect(screen.getByText('Marketplace strategy')).toBeInTheDocument()
+ await finishSearch()
+ expect(await screen.findByText('Marketplace strategy')).toBeInTheDocument()
+ expect(marketplace).toHaveBeenCalledWith(
+ '/plugins/search/advanced',
+ expect.objectContaining({
+ body: expect.objectContaining({ query: 'react', category: PluginCategoryEnum.agent }),
+ }),
+ )
})
it('shows installed strategies once and keeps other marketplace results available', async () => {
const user = userEvent.setup()
const provider = createProvider()
- marketplaceResults.mockReturnValue([
- createPlugin({ plugin_id: provider.plugin_id, label: { en_US: 'Installed Marketplace' } }),
- createPlugin({ plugin_id: 'org/available', label: { en_US: 'Available Marketplace' } }),
- ])
+ marketplace.mockResolvedValue({
+ data: {
+ total: 2,
+ plugins: [
+ createPlugin({ plugin_id: provider.plugin_id, label: { en_US: 'Installed Marketplace' } }),
+ createPlugin({ plugin_id: 'org/available', label: { en_US: 'Available Marketplace' } }),
+ ],
+ },
+ })
request.mockImplementation(() => Promise.resolve(Response.json([provider])))
render(<AgentStrategySelector onChange={vi.fn()} />, {
systemFeatures: { enable_marketplace: true },
@@ -220,10 +251,13 @@ it('shows installed strategies once and keeps other marketplace results availabl
await user.click(screen.getByText('workflowAgent.nodes.agent.strategy.selectTip'))
expect(await screen.findByRole('button', { name: 'Agent provider' })).toBeInTheDocument()
- await user.type(
+ const search = searchUser()
+ await search.type(
screen.getByPlaceholderText('workflowAgent.nodes.agent.strategy.searchPlaceholder'),
'agent',
)
+ await finishSearch()
+ await screen.findByText('Available Marketplace')
expect(screen.queryByText('Installed Marketplace')).not.toBeInTheDocument()
expect(await screen.findByText('Available Marketplace')).toBeInTheDocument()
})
@@ -261,18 +295,34 @@ it('preserves an older saved selection with no plugin identifier until the user
)
})
-it('keeps the install action for a saved marketplace strategy that is no longer installed', async () => {
+it('installs a missing saved strategy and refreshes its availability', async () => {
const user = userEvent.setup()
- marketplace.mockReturnValue({
- isLoading: false,
- data: { data: { plugins: [createPlugin()] } },
- refetch: vi.fn(),
+ const installation = createDeferred<{ all_installed: boolean; task_id: string }>()
+ marketplace.mockResolvedValue({ data: { plugins: [createPlugin()], total: 1 } })
+ let installed = false
+ const provider = createProvider()
+ request.mockImplementation((url: string) => {
+ if (url.endsWith('/agent-providers'))
+ return Promise.resolve(Response.json(installed ? [provider] : []))
+ if (installed) return Promise.resolve(Response.json(provider))
+ return Promise.reject(new Error('Provider not installed'))
})
- request.mockImplementation((url: string) =>
- url.endsWith('/agent-providers')
- ? Promise.resolve(Response.json([]))
- : Promise.reject(new Error('Provider not installed')),
- )
+ install.mockImplementation(async () => {
+ const response = await installation.promise
+ installed = true
+ return response
+ })
+ manifest.mockImplementation(async () => ({
+ plugins: installed
+ ? [
+ createInstalledPluginFixture({
+ id: 'langgenius/agent:1.0.0@hash',
+ plugin_id: 'langgenius/agent',
+ plugin_unique_identifier: 'langgenius/agent:1.0.0@hash',
+ }),
+ ]
+ : [],
+ }))
render(
<AgentStrategySelector
value={{
@@ -291,9 +341,22 @@ it('keeps the install action for a saved marketplace strategy that is no longer
name: 'workflowAgent.nodes.agent.pluginInstaller.install',
}),
)
- expect(install).toHaveBeenCalledWith('langgenius/agent:1.0.0@hash', expect.any(Object))
+ expect(
+ await screen.findByRole('button', {
+ name: 'workflowAgent.nodes.agent.pluginInstaller.installing',
+ }),
+ ).toBeDisabled()
+ expect(install).toHaveBeenCalledExactlyOnceWith({
+ body: { plugin_unique_identifiers: ['langgenius/agent:1.0.0@hash'] },
+ })
+ await act(async () => installation.resolve({ all_installed: true, task_id: 'task-1' }))
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', { name: /pluginInstaller.install/ }),
+ ).not.toBeInTheDocument(),
+ )
+ expect(screen.getByText('Saved label')).toBeInTheDocument()
expect(
screen.queryByPlaceholderText('workflowAgent.nodes.agent.strategy.searchPlaceholder'),
).not.toBeInTheDocument()
- expect(screen.getByText('Saved label')).toBeInTheDocument()
})
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/index.spec.tsx
index e7bf3c2a639..cad91686c72 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import type { DeliveryMethod } from '../../../types'
-import { screen, waitFor, within } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { useState } from 'react'
@@ -8,112 +8,51 @@ import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { DeliveryMethodType } from '../../../types'
import DeliveryMethodForm from '../index'
-const mockHandleSyncWorkflowDraft = vi.fn()
-
-vi.mock('../method-selector', () => ({
- __esModule: true,
- default: (props: { onAdd: (method: DeliveryMethod) => void; onShowUpgradeTip: () => void }) => (
- <div>
- <button
- type="button"
- onClick={() =>
- props.onAdd({ id: 'webapp-1', type: DeliveryMethodType.WebApp, enabled: true })
- }
- >
- add-method
- </button>
- <button type="button" onClick={props.onShowUpgradeTip}>
- show-upgrade
- </button>
- </div>
- ),
-}))
-
-vi.mock('../method-item', () => ({
- __esModule: true,
- default: (props: {
- method: DeliveryMethod
- onChange: (method: DeliveryMethod) => void
- onDelete: (type: DeliveryMethodType) => void
- }) => (
- <section aria-label={props.method.type}>
- <button
- type="button"
- onClick={() => props.onChange({ ...props.method, enabled: !props.method.enabled })}
- >
- change-method
- </button>
- <button type="button" onClick={() => props.onDelete(props.method.type)}>
- delete-method
- </button>
- </section>
- ),
-}))
-
-describe('DeliveryMethodForm', () => {
- const onChange = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
+const prefix = 'workflowHumanInput.nodes.humanInput.deliveryMethod.'
+function renderMethods(initial: DeliveryMethod[], emailDeliveryEnabled = true) {
+ function Form() {
+ const [methods, setMethods] = useState(initial)
+ return <DeliveryMethodForm nodeId="node-1" value={methods} onChange={setMethods} />
+ }
+ const { queryClient } = createConsoleQueryWrapper({
+ features: { human_input_email_delivery_enabled: emailDeliveryEnabled },
})
+ return renderWorkflowFlowComponent(
+ <NuqsTestingAdapter>
+ <Form />
+ </NuqsTestingAdapter>,
+ {
+ queryClient,
+ },
+ )
+}
- it('adds, changes, and removes the selected method while preserving other methods', async () => {
- const user = userEvent.setup()
- const email: DeliveryMethod = { id: 'email-1', type: DeliveryMethodType.Email, enabled: false }
- function Form() {
- const [methods, setMethods] = useState<DeliveryMethod[]>([email])
- return (
- <DeliveryMethodForm
- nodeId="node-1"
- value={methods}
- onChange={(next) => {
- setMethods(next)
- onChange(next)
- }}
- />
- )
- }
- render(<Form />)
- await user.click(screen.getByRole('button', { name: 'add-method' }))
- const webapp: DeliveryMethod = {
- id: 'webapp-1',
- type: DeliveryMethodType.WebApp,
- enabled: true,
- }
- expect(onChange).toHaveBeenLastCalledWith([email, webapp])
- expect(mockHandleSyncWorkflowDraft).not.toHaveBeenCalled()
- const method = screen.getByRole('region', { name: DeliveryMethodType.WebApp })
- await user.click(within(method).getByRole('button', { name: 'change-method' }))
- expect(onChange).toHaveBeenLastCalledWith([email, { ...webapp, enabled: false }])
- expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledExactlyOnceWith(true, undefined)
- await user.click(within(method).getByRole('button', { name: 'delete-method' }))
- expect(onChange).toHaveBeenLastCalledWith([email])
- expect(
- screen.queryByRole('region', { name: DeliveryMethodType.WebApp }),
- ).not.toBeInTheDocument()
- expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledTimes(1)
- })
-
- it('should open and close the upgrade modal', async () => {
- const user = userEvent.setup()
- render(<DeliveryMethodForm nodeId="node-1" value={[]} onChange={onChange} />)
-
- await user.click(screen.getByText('show-upgrade'))
- expect(screen.getByRole('dialog')).toBeInTheDocument()
-
- await user.click(
- screen.getByRole('button', {
- name: 'workflowHumanInput.nodes.humanInput.deliveryMethod.upgradeTipHide',
- }),
- )
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- })
+it('adds, changes, and removes the selected method while preserving other methods', async () => {
+ const user = userEvent.setup()
+ renderMethods([{ id: 'email-1', type: DeliveryMethodType.Email, enabled: false }])
+ await user.click(screen.getAllByRole('button', { name: `${prefix}title` })[1]!)
+ await user.click(screen.getByText(`${prefix}types.webapp.title`))
+ await user.keyboard('{Escape}')
+ const toggle = screen.getByRole('switch')
+ expect(toggle).toBeChecked()
+ expect(screen.getByText('email')).toBeInTheDocument()
+ await user.click(toggle)
+ expect(toggle).not.toBeChecked()
+ // The existing email entry precedes the newly added WebApp entry.
+ await user.click(screen.getAllByRole('button', { name: 'common.operation.remove' })[1]!)
+ expect(screen.queryByText('webapp')).not.toBeInTheDocument()
+ expect(screen.queryByRole('switch')).not.toBeInTheDocument()
+ expect(screen.getByText('email')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: `${prefix}notConfigured` })).toBeInTheDocument()
})
-function render(ui: React.ReactElement) {
- const { queryClient } = createConsoleQueryWrapper()
- return renderWorkflowFlowComponent(<NuqsTestingAdapter>{ui}</NuqsTestingAdapter>, {
- queryClient,
- hooksStoreProps: { doSyncWorkflowDraft: mockHandleSyncWorkflowDraft },
- })
-}
+it('opens the upgrade modal for unavailable email delivery and closes it', async () => {
+ const user = userEvent.setup()
+ renderMethods([], false)
+ await user.click(screen.getAllByRole('button', { name: `${prefix}title` })[1]!)
+ await user.click(screen.getByText(`${prefix}types.email.title`))
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: `${prefix}upgradeTipHide` }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(screen.queryByText('email')).not.toBeInTheDocument()
+})