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 HITL and installed app test doubles (#45167)

Stephen Zhou6395e8b8bea0
diff --git a/web/app/components/app/text-generate/item/__tests__/index.hitl-v2.spec.tsx b/web/app/components/app/text-generate/item/__tests__/index.hitl-v2.spec.tsx
index dd6ac035ec3..df080117adf 100644
--- a/web/app/components/app/text-generate/item/__tests__/index.hitl-v2.spec.tsx
+++ b/web/app/components/app/text-generate/item/__tests__/index.hitl-v2.spec.tsx
@@ -1,6 +1,9 @@
+import type { ReactElement } from 'react'
import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { ChatContextProvider } from '@/app/components/base/chat/chat/context-provider'
+import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
+import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { AppSourceType } from '@/service/share'
import {
createHumanInputFormFixture,
@@ -8,160 +11,93 @@ import {
} from '@/test/fixtures/workflow-process'
import GenerationItem from '../index'
-const mockFetchMoreLikeThis = vi.fn()
-const mockFetchTextGenerationMessage = vi.fn()
-const mockUpdateFeedback = vi.fn()
-const mockSubmitHumanInputForm = vi.fn()
-const mockSubmitWebAppHumanInputForm = vi.fn()
-const mockSubmitHumanInputFormWorkflow = vi.fn()
-const mockToastWarning = vi.fn()
-vi.mock('@/next/navigation', () => ({
- useParams: () => ({
- appId: 'app-1',
- }),
+const mocks = vi.hoisted(() => ({
+ submitShare: vi.fn(),
+ submitWebApp: vi.fn(),
+ submitWorkflow: vi.fn(),
}))
-vi.mock('@/service/share', async () => {
- const actual = await vi.importActual<typeof import('@/service/share')>('@/service/share')
- return {
- ...actual,
- fetchMoreLikeThis: (...args: unknown[]) => mockFetchMoreLikeThis(...args),
- submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
- updateFeedback: (...args: unknown[]) => mockUpdateFeedback(...args),
- }
-})
-
-vi.mock('@/service/workflow', () => ({
- submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputFormWorkflow(...args),
+vi.mock('@/config', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/config')>()),
+ ENABLE_HITL_IM: true,
}))
-
-vi.mock('@/service/webapp-human-input', () => ({
- submitWebAppHumanInputForm: (...args: unknown[]) => mockSubmitWebAppHumanInputForm(...args),
+vi.mock('@/next/navigation', () => ({ useParams: () => ({ appId: 'app-1' }) }))
+vi.mock('@/service/share', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/share')>()),
+ fetchMoreLikeThis: vi.fn(),
+ submitHumanInputForm: mocks.submitShare,
+ updateFeedback: vi.fn(),
}))
-
-vi.mock('@/service/debug', () => ({
- fetchTextGenerationMessage: (...args: unknown[]) => mockFetchTextGenerationMessage(...args),
-}))
-
-vi.mock('@/app/components/base/chat/chat/context', () => ({
- useChatContext: () => ({
- config: {
- text_to_speech: {
- voice: 'alloy',
- },
- },
- }),
-}))
-
-vi.mock('@/app/components/base/markdown', () => ({
- Markdown: ({ content }: { content: string }) => <div>{`markdown:${content}`}</div>,
-}))
-
-vi.mock('@/app/notifications', () => ({
- toast: {
- warning: (...args: unknown[]) => mockToastWarning(...args),
- success: vi.fn(),
- },
+vi.mock('@/service/workflow', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/workflow')>()),
+ submitHumanInputForm: mocks.submitWorkflow,
}))
-
-vi.mock('../workflow-body', () => ({
- default: ({
- currentTab,
- onSubmitHumanInputForm,
- onSwitchTab,
- }: {
- currentTab: string
- onSubmitHumanInputForm: (
- token: string,
- data: { inputs: Record<string, string>; action: string },
- ) => Promise<void>
- onSwitchTab: (tab: string) => Promise<void>
- }) => (
- <div>
- <div>{`workflow-body:${currentTab}`}</div>
- <button
- onClick={() =>
- void onSubmitHumanInputForm('token-1', { action: 'submit', inputs: { name: 'dify' } })
- }
- >
- submit-human-input
- </button>
- <button onClick={() => void onSwitchTab('LOG')}>switch-workflow-tab</button>
- </div>
- ),
+vi.mock('@/service/webapp-human-input', () => ({
+ submitWebAppHumanInputForm: mocks.submitWebApp,
}))
+const renderItem = (ui: ReactElement) =>
+ render(<ChatContextProvider chatList={[]}>{ui}</ChatContextProvider>)
-describe('GenerationItem', () => {
- beforeEach(() => {
- vi.clearAllMocks()
+const reachableForm = (formVersion?: '1' | '2') =>
+ createHumanInputFormFixture({
+ form_content: 'Name {{#$output.name#}}',
+ form_version: formVersion,
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'name',
+ default: { type: 'constant', value: '', selector: [] },
+ },
+ ],
+ actions: [{ id: 'submit', title: 'Submit', button_style: UserActionButtonType.Primary }],
})
+describe('GenerationItem HITL routing', () => {
it.each([
- {
- appSourceType: AppSourceType.webApp,
- formVersion: '1' as const,
- submit: mockSubmitWebAppHumanInputForm,
- unusedSubmit: mockSubmitHumanInputForm,
- },
- {
- appSourceType: AppSourceType.webApp,
- formVersion: '2' as const,
- submit: mockSubmitWebAppHumanInputForm,
- unusedSubmit: mockSubmitHumanInputForm,
- },
- {
- appSourceType: AppSourceType.webApp,
- formVersion: undefined,
- submit: mockSubmitWebAppHumanInputForm,
- unusedSubmit: mockSubmitHumanInputForm,
- },
- {
- appSourceType: AppSourceType.tryApp,
- formVersion: undefined,
- submit: mockSubmitHumanInputForm,
- unusedSubmit: mockSubmitWebAppHumanInputForm,
- },
+ { appSourceType: AppSourceType.webApp, formVersion: '1' as const },
+ { appSourceType: AppSourceType.webApp, formVersion: '2' as const },
+ { appSourceType: AppSourceType.webApp, formVersion: undefined },
+ { appSourceType: AppSourceType.tryApp, formVersion: undefined },
])(
- 'preserves $appSourceType version $formVersion submission and workflow tab switching',
- async ({ appSourceType, formVersion, submit, unusedSubmit }) => {
+ 'submits a real $appSourceType form with version $formVersion and switches tabs',
+ async ({ appSourceType, formVersion }) => {
const user = userEvent.setup()
- render(
+ renderItem(
<GenerationItem
appSourceType={appSourceType}
- content="workflow result"
+ content={{ detail: 'workflow detail' }}
isError={false}
isWorkflow
messageId="msg-1"
onRetry={vi.fn()}
siteInfo={null}
workflowProcessData={createWorkflowProcessFixture({
+ status: WorkflowRunningStatus.Paused,
resultText: 'workflow result',
- humanInputFormDataList: [createHumanInputFormFixture({ form_version: formVersion })],
+ humanInputFormDataList: [reachableForm(formVersion)],
})}
/>,
)
- expect(screen.getByText('workflow-body:RESULT')).toBeInTheDocument()
+ expect(screen.getByText('runLog.result')).toBeInTheDocument()
+ await user.type(screen.getByRole('textbox', { name: 'name' }), 'Dify')
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
+ await user.click(screen.getByText('runLog.detail'))
- await user.click(screen.getByRole('button', { name: 'submit-human-input' }))
- await user.click(screen.getByRole('button', { name: 'switch-workflow-tab' }))
-
- expect(submit).toHaveBeenCalledWith(
+ const expectedSubmit =
+ appSourceType === AppSourceType.webApp ? mocks.submitWebApp : mocks.submitShare
+ expect(expectedSubmit).toHaveBeenCalledWith(
'token-1',
- {
- action: 'submit',
- inputs: { name: 'dify' },
- },
+ { action: 'submit', inputs: { name: 'Dify' } },
...(appSourceType === AppSourceType.webApp ? [formVersion] : []),
)
- expect(unusedSubmit).not.toHaveBeenCalled()
- expect(mockSubmitHumanInputFormWorkflow).not.toHaveBeenCalled()
- expect(screen.getByText('workflow-body:LOG')).toBeInTheDocument()
+ expect(mocks.submitWorkflow).not.toHaveBeenCalled()
+ expect(screen.getByText('JSON OUTPUT')).toBeInTheDocument()
},
)
it.each([true, false])(
- 'waits for approval events and submits only when ready is %s',
+ 'waits for preparation before submitting when ready is %s',
async (ready) => {
const user = userEvent.setup()
let resolvePreparation: ((ready: boolean) => void) | undefined
@@ -171,7 +107,7 @@ describe('GenerationItem', () => {
resolvePreparation = resolve
}),
)
- render(
+ renderItem(
<GenerationItem
appSourceType={AppSourceType.webApp}
content=""
@@ -180,27 +116,29 @@ describe('GenerationItem', () => {
onRetry={vi.fn()}
prepareHumanInputSubmission={prepareHumanInputSubmission}
siteInfo={null}
- workflowProcessData={{ status: WorkflowRunningStatus.Paused, tracing: [], expand: false }}
+ workflowProcessData={createWorkflowProcessFixture({
+ status: WorkflowRunningStatus.Paused,
+ humanInputFormDataList: [reachableForm()],
+ })}
/>,
)
- await user.click(screen.getByRole('button', { name: 'submit-human-input' }))
+
+ await user.type(screen.getByRole('textbox', { name: 'name' }), 'Dify')
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
expect(prepareHumanInputSubmission).toHaveBeenCalledOnce()
- expect(mockSubmitWebAppHumanInputForm).not.toHaveBeenCalled()
+ expect(mocks.submitWebApp).not.toHaveBeenCalled()
+
await act(async () => resolvePreparation?.(ready))
+
if (ready) {
- expect(mockSubmitWebAppHumanInputForm).toHaveBeenCalledExactlyOnceWith(
+ expect(mocks.submitWebApp).toHaveBeenCalledExactlyOnceWith(
'token-1',
- {
- inputs: { name: 'dify' },
- action: 'submit',
- },
+ { inputs: { name: 'Dify' }, action: 'submit' },
undefined,
)
} else {
- expect(mockSubmitWebAppHumanInputForm).not.toHaveBeenCalled()
+ expect(mocks.submitWebApp).not.toHaveBeenCalled()
}
- expect(mockSubmitHumanInputForm).not.toHaveBeenCalled()
- expect(mockSubmitHumanInputFormWorkflow).not.toHaveBeenCalled()
},
)
})
diff --git a/web/app/components/app/text-generate/item/__tests__/index.spec.tsx b/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
index 9cee0e0b51e..5583dba18fa 100644
--- a/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
+++ b/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
@@ -1,7 +1,10 @@
+import type { ReactNode } from 'react'
import type { HumanInputFormData } from '@/types/workflow'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { ChatContextProvider } from '@/app/components/base/chat/chat/context-provider'
+import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
+import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { AppSourceType } from '@/service/share'
import {
createHumanInputFormFixture,
@@ -13,9 +16,12 @@ const mockFetchMoreLikeThis = vi.fn()
const mockFetchTextGenerationMessage = vi.fn()
const mockUpdateFeedback = vi.fn()
const mockOnOpenLog = vi.fn()
-const mockSubmitHumanInputForm = vi.fn()
const mockSubmitHumanInputFormWorkflow = vi.fn()
const mockToastWarning = vi.fn()
+vi.mock('@/config', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/config')>()),
+ ENABLE_HITL_IM: true,
+}))
vi.mock('@/next/navigation', () => ({
useParams: () => ({
appId: 'app-1',
@@ -27,7 +33,6 @@ vi.mock('@/service/share', async () => {
return {
...actual,
fetchMoreLikeThis: (...args: unknown[]) => mockFetchMoreLikeThis(...args),
- submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
updateFeedback: (...args: unknown[]) => mockUpdateFeedback(...args),
}
})
@@ -40,20 +45,6 @@ vi.mock('@/service/debug', () => ({
fetchTextGenerationMessage: (...args: unknown[]) => mockFetchTextGenerationMessage(...args),
}))
-vi.mock('@/app/components/base/chat/chat/context', () => ({
- useChatContext: () => ({
- config: {
- text_to_speech: {
- voice: 'alloy',
- },
- },
- }),
-}))
-
-vi.mock('@/app/components/base/markdown', () => ({
- Markdown: ({ content }: { content: string }) => <div>{`markdown:${content}`}</div>,
-}))
-
vi.mock('@/app/notifications', () => ({
toast: {
warning: (...args: unknown[]) => mockToastWarning(...args),
@@ -61,38 +52,26 @@ vi.mock('@/app/notifications', () => ({
},
}))
-vi.mock('../workflow-body', () => ({
- default: ({
- currentTab,
- onSubmitHumanInputForm,
- onSwitchTab,
- }: {
- currentTab: string
- onSubmitHumanInputForm: (
- token: string,
- data: { inputs: Record<string, string>; action: string },
- ) => Promise<void>
- onSwitchTab: (tab: string) => Promise<void>
- }) => (
- <div>
- <div>{`workflow-body:${currentTab}`}</div>
- <button
- onClick={() =>
- void onSubmitHumanInputForm('token-1', { action: 'submit', inputs: { name: 'dify' } })
- }
- >
- submit-human-input
- </button>
- <button onClick={() => void onSwitchTab('LOG')}>switch-workflow-tab</button>
- </div>
- ),
-}))
+const renderItem = (ui: ReactNode) =>
+ render(ui, {
+ wrapper: ({ children }) => <ChatContextProvider chatList={[]}>{children}</ChatContextProvider>,
+ })
-describe('GenerationItem', () => {
- beforeEach(() => {
- vi.resetAllMocks()
+const reachableForm = (overrides: Partial<HumanInputFormData> = {}) =>
+ createHumanInputFormFixture({
+ form_content: 'Name {{#$output.name#}}',
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'name',
+ default: { type: 'constant', value: '', selector: [] },
+ },
+ ],
+ actions: [{ id: 'submit', title: 'Submit', button_style: UserActionButtonType.Primary }],
+ ...overrides,
})
+describe('GenerationItem', () => {
it('should render markdown content and allow more-like-this recursion', async () => {
const user = userEvent.setup()
mockFetchMoreLikeThis.mockResolvedValue({
@@ -101,7 +80,7 @@ describe('GenerationItem', () => {
})
mockUpdateFeedback.mockResolvedValue(undefined)
- render(
+ renderItem(
<GenerationItem
appSourceType={AppSourceType.webApp}
content="hello world"
@@ -116,14 +95,14 @@ describe('GenerationItem', () => {
/>,
)
- expect(screen.getByText('markdown:hello world')).toBeInTheDocument()
+ expect(await screen.findByText('hello world')).toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: /(?:^|\.)feature\.moreLikeThis\.title(?=$|:)/ }),
)
await waitFor(() => {
- expect(screen.getByText('markdown:follow up answer')).toBeInTheDocument()
+ expect(screen.getByText('follow up answer')).toBeInTheDocument()
})
expect(mockFetchMoreLikeThis).toHaveBeenCalledWith('msg-1', AppSourceType.webApp, undefined)
@@ -149,7 +128,7 @@ describe('GenerationItem', () => {
message_files: [{ belongs_to: 'assistant', id: 'file-1' }],
})
- render(
+ renderItem(
<GenerationItem
appSourceType={AppSourceType.webApp}
content="hello world"
@@ -182,7 +161,7 @@ describe('GenerationItem', () => {
})
it('keeps the log action absent without an owning surface', () => {
- render(
+ renderItem(
<GenerationItem
appSourceType={AppSourceType.webApp}
content="Answer"
@@ -205,7 +184,7 @@ describe('GenerationItem', () => {
answer: 'Child answer',
message: [{ role: 'user', text: 'Child prompt' }],
})
- render(
+ renderItem(
<GenerationItem
appSourceType={AppSourceType.webApp}
content="Parent answer"
@@ -219,7 +198,7 @@ describe('GenerationItem', () => {
)
await user.click(screen.getByRole('button', { name: /feature\.moreLikeThis\.title/ }))
- expect(await screen.findByText('markdown:Child answer')).toBeInTheDocument()
+ expect(await screen.findByText('Child answer')).toBeInTheDocument()
await user.click(screen.getAllByRole('button', { name: /operation\.log/ })[1]!)
await waitFor(() =>
@@ -243,7 +222,7 @@ describe('GenerationItem', () => {
'submits the installed workflow form with its matching version %s',
async (version) => {
const user = userEvent.setup()
- render(
+ renderItem(
<GenerationItem
appSourceType={AppSourceType.installedApp}
content="workflow result"
@@ -256,34 +235,34 @@ describe('GenerationItem', () => {
status: WorkflowRunningStatus.Paused,
resultText: 'workflow result',
humanInputFormDataList: [
- createHumanInputFormFixture({
+ reachableForm({
form_id: 'another-form',
node_id: 'another-node',
form_token: 'another-token',
form_version: version === '2' ? '1' : '2',
+ display_in_ui: false,
}),
- createHumanInputFormFixture({ form_version: version }),
+ reachableForm({ form_version: version }),
],
})}
/>,
)
- expect(screen.getByText('workflow-body:RESULT')).toBeInTheDocument()
-
- await user.click(screen.getByRole('button', { name: 'submit-human-input' }))
+ expect(await screen.findByText('workflow result')).toBeInTheDocument()
+ await user.type(screen.getByRole('textbox', { name: 'name' }), 'Dify')
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
expect(mockSubmitHumanInputFormWorkflow).toHaveBeenCalledWith(
'token-1',
- { action: 'submit', inputs: { name: 'dify' } },
+ { action: 'submit', inputs: { name: 'Dify' } },
version,
)
- expect(mockSubmitHumanInputForm).not.toHaveBeenCalled()
},
)
it('uses the current form version after workflow state updates', async () => {
const user = userEvent.setup()
- const renderItem = (version: HumanInputFormData['form_version']) => (
+ const view = (version: HumanInputFormData['form_version']) => (
<GenerationItem
appSourceType={AppSourceType.installedApp}
content=""
@@ -293,61 +272,31 @@ describe('GenerationItem', () => {
siteInfo={null}
workflowProcessData={createWorkflowProcessFixture({
status: WorkflowRunningStatus.Paused,
- humanInputFormDataList: [createHumanInputFormFixture({ form_version: version })],
+ humanInputFormDataList: [reachableForm({ form_version: version })],
})}
/>
)
- const { rerender } = render(renderItem('1'))
- await user.click(screen.getByRole('button', { name: 'submit-human-input' }))
- rerender(renderItem('2'))
- await user.click(screen.getByRole('button', { name: 'submit-human-input' }))
+ const { rerender } = renderItem(view('1'))
+ await user.type(screen.getByRole('textbox', { name: 'name' }), 'First')
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
+ rerender(view('2'))
+ const name = screen.getByRole('textbox', { name: 'name' })
+ await user.clear(name)
+ await user.type(name, 'Second')
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
expect(mockSubmitHumanInputFormWorkflow).toHaveBeenNthCalledWith(
1,
'token-1',
- { action: 'submit', inputs: { name: 'dify' } },
+ { action: 'submit', inputs: { name: 'First' } },
'1',
)
expect(mockSubmitHumanInputFormWorkflow).toHaveBeenNthCalledWith(
2,
'token-1',
- { action: 'submit', inputs: { name: 'dify' } },
+ { action: 'submit', inputs: { name: 'Second' } },
'2',
)
- expect(mockSubmitHumanInputForm).not.toHaveBeenCalled()
- })
-
- it('should route human input submissions to the share service and allow workflow tab switching', async () => {
- const user = userEvent.setup()
- render(
- <GenerationItem
- appSourceType={AppSourceType.webApp}
- content="workflow result"
- isError={false}
- isWorkflow
- messageId="msg-1"
- onRetry={vi.fn()}
- siteInfo={null}
- workflowProcessData={createWorkflowProcessFixture({
- resultText: 'workflow result',
- })}
- />,
- )
-
- expect(screen.getByText('workflow-body:RESULT')).toBeInTheDocument()
-
- await user.click(screen.getByText('submit-human-input'))
- await user.click(screen.getByText('switch-workflow-tab'))
-
- expect(mockSubmitHumanInputForm).toHaveBeenCalledWith(
- 'token-1',
- {
- action: 'submit',
- inputs: { name: 'dify' },
- },
- undefined,
- )
- expect(screen.getByText('workflow-body:LOG')).toBeInTheDocument()
})
it('should clear recursive results when requested or when the parent reloads', async () => {
@@ -357,7 +306,7 @@ describe('GenerationItem', () => {
id: 'msg-2',
})
- const { rerender } = render(
+ const { rerender } = renderItem(
<GenerationItem
appSourceType={AppSourceType.webApp}
content="hello world"
@@ -377,7 +326,7 @@ describe('GenerationItem', () => {
)
await waitFor(() => {
- expect(screen.getByText('markdown:follow up answer')).toBeInTheDocument()
+ expect(screen.getByText('follow up answer')).toBeInTheDocument()
})
rerender(
@@ -396,10 +345,10 @@ describe('GenerationItem', () => {
/>,
)
- expect(screen.queryByText('markdown:follow up answer')).not.toBeInTheDocument()
+ expect(screen.queryByText('follow up answer')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /feature\.moreLikeThis\.title/ }))
- expect(await screen.findByText('markdown:follow up answer')).toBeInTheDocument()
+ expect(await screen.findByText('follow up answer')).toBeInTheDocument()
rerender(
<GenerationItem
@@ -417,12 +366,12 @@ describe('GenerationItem', () => {
/>,
)
- expect(screen.queryByText('markdown:follow up answer')).not.toBeInTheDocument()
+ expect(screen.queryByText('follow up answer')).not.toBeInTheDocument()
})
it('should warn instead of requesting more-like-this without a message id', async () => {
const user = userEvent.setup()
- render(
+ renderItem(
<GenerationItem
appSourceType={AppSourceType.webApp}
content="hello world"
@@ -444,7 +393,3 @@ describe('GenerationItem', () => {
expect(mockFetchMoreLikeThis).not.toHaveBeenCalled()
})
})
-
-vi.mock('@/service/webapp-human-input', () => ({
- submitWebAppHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
-}))
diff --git a/web/app/components/explore/installed-app/__tests__/index.spec.tsx b/web/app/components/explore/installed-app/__tests__/index.spec.tsx
index 0c8018eb482..b64b6555245 100644
--- a/web/app/components/explore/installed-app/__tests__/index.spec.tsx
+++ b/web/app/components/explore/installed-app/__tests__/index.spec.tsx
@@ -2,12 +2,10 @@ import type {
AppMode,
InstalledAppResponse,
} from '@dify/contracts/api/console/installed-apps/types.gen'
-import type { Mock } from 'vite-plus/test'
import { QueryClient } from '@tanstack/react-query'
import { screen, waitFor } from '@testing-library/react'
-import { useWebAppStore } from '@/context/web-app-context'
+import WebAppStoreProvider, { useWebAppStore } from '@/context/web-app-context'
import { AccessMode } from '@/models/access-control'
-import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'
import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import InstalledApp from '../index'
@@ -17,15 +15,26 @@ const mocks = vi.hoisted(() => ({
getInstalledApp: vi.fn(),
getInstalledAppMeta: vi.fn(),
getInstalledAppParameters: vi.fn(),
+ getUserAccess: vi.fn(),
+}))
+
+vi.mock('@/next/navigation', () => ({
+ usePathname: () => '/',
+ useSearchParams: () => new URLSearchParams(),
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
- const { withConsoleResponses } = await import('@/test/console/service-responses')
+ const { withConsoleClientResponses, withConsoleResponses } =
+ await import('@/test/console/service-responses')
const installedId = (input: { params: { installed_app_id: string } }) =>
input.params.installed_app_id
return {
...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'enterprise.webAppAuth.isUserAllowedToAccessWebApp': (input: { query: { appId: string } }) =>
+ mocks.getUserAccess(input.query.appId),
+ }),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'enterprise.webAppAuth.getWebAppAccessMode': (input: { query: { appId: string } }) =>
mocks.getAccessMode(input.query.appId),
@@ -38,20 +47,12 @@ vi.mock('@/service/console', async (importOriginal) => {
}
})
-vi.mock('@/context/web-app-context', () => ({
- useWebAppStore: vi.fn(),
-}))
-
-vi.mock('@/service/access-control/use-app-access-control', () => ({
- useGetUserCanAccessApp: vi.fn(),
-}))
-
+// These independently tested surfaces are intentionally outside the route/store contract here.
vi.mock('@/app/components/share/text-generation', () => ({
default: ({ isWorkflow }: { isWorkflow?: boolean }) => (
<div>{isWorkflow ? 'Workflow App' : 'Completion App'}</div>
),
}))
-
vi.mock('@/app/components/base/chat/chat-with-history', () => ({
default: () => <div>Chat App</div>,
}))
@@ -75,88 +76,63 @@ const createInstalledApp = (mode: AppMode = 'chat'): InstalledAppResponse => ({
},
})
-describe('InstalledApp', () => {
- const updateAppInfo = vi.fn()
- const updateWebAppAccessMode = vi.fn()
- const updateAppParams = vi.fn()
- const updateWebAppMeta = vi.fn()
- const updateUserCanAccessApp = vi.fn()
- const appParams = {
- user_input_form: [],
- file_upload: { image: { enabled: false, number_limits: 0, transfer_methods: [] } },
- system_parameters: {},
- }
- const appMeta = { tool_icons: {} }
+const appParamsResponse = {
+ annotation_reply: {},
+ file_upload: { image: { enabled: false, number_limits: 0, transfer_methods: [] } },
+ more_like_this: {},
+ opening_statement: null,
+ retriever_resource: {},
+ sensitive_word_avoidance: {},
+ speech_to_text: {},
+ suggested_questions: [],
+ suggested_questions_after_answer: {},
+ system_parameters: {
+ audio_file_size_limit: 10,
+ file_size_limit: 15,
+ image_file_size_limit: 10,
+ video_file_size_limit: 100,
+ workflow_file_upload_limit: 10,
+ },
+ text_to_speech: {},
+ user_input_form: [],
+}
+
+const installedAppView = (id: string) => (
+ <WebAppStoreProvider>
+ <InstalledApp id={id} />
+ </WebAppStoreProvider>
+)
+
+const renderInstalledApp = (
+ id = 'installed-app-123',
+ options: Parameters<typeof renderWithConsoleQuery>[1] = {},
+) => renderWithConsoleQuery(installedAppView(id), options)
+describe('InstalledApp', () => {
beforeEach(() => {
- vi.clearAllMocks()
mocks.getAccessMode.mockResolvedValue({ accessMode: AccessMode.PUBLIC })
mocks.getInstalledApp.mockResolvedValue(createInstalledApp())
- mocks.getInstalledAppMeta.mockResolvedValue(appMeta)
- mocks.getInstalledAppParameters.mockResolvedValue({
- annotation_reply: {},
- file_upload: appParams.file_upload,
- more_like_this: {},
- opening_statement: null,
- retriever_resource: {},
- sensitive_word_avoidance: {},
- speech_to_text: {},
- suggested_questions: [],
- suggested_questions_after_answer: {},
- system_parameters: {
- audio_file_size_limit: 10,
- file_size_limit: 15,
- image_file_size_limit: 10,
- video_file_size_limit: 100,
- workflow_file_upload_limit: 10,
- },
- text_to_speech: {},
- user_input_form: [],
- })
-
- ;(useWebAppStore as unknown as Mock).mockImplementation(
- (
- selector: (state: {
- updateAppInfo: Mock
- updateWebAppAccessMode: Mock
- updateAppParams: Mock
- updateWebAppMeta: Mock
- updateUserCanAccessApp: Mock
- }) => unknown,
- ) =>
- selector({
- updateAppInfo,
- updateWebAppAccessMode,
- updateAppParams,
- updateWebAppMeta,
- updateUserCanAccessApp,
- }),
- )
- ;(useGetUserCanAccessApp as Mock).mockReturnValue({
- data: { result: true },
- error: null,
- isPending: false,
- })
+ mocks.getInstalledAppMeta.mockResolvedValue({ tool_icons: {} })
+ mocks.getInstalledAppParameters.mockResolvedValue(appParamsResponse)
+ mocks.getUserAccess.mockResolvedValue({ result: true })
})
it.each<AppMode>(['chat', 'advanced-chat', 'agent-chat'] as const)(
'renders chat for the supported %s mode',
async (mode) => {
mocks.getInstalledApp.mockResolvedValue(createInstalledApp(mode))
-
- renderWithConsoleQuery(<InstalledApp id="installed-app-123" />)
-
+ renderInstalledApp()
expect(await screen.findByText('Chat App')).toBeInTheDocument()
},
)
it('renders completion and workflow surfaces explicitly', async () => {
mocks.getInstalledApp.mockResolvedValue(createInstalledApp('completion'))
- const { rerender } = renderWithConsoleQuery(<InstalledApp id="installed-app-123" />)
+ const { rerender } = renderInstalledApp()
expect(await screen.findByText('Completion App')).toBeInTheDocument()
mocks.getInstalledApp.mockResolvedValue(createInstalledApp('workflow'))
- rerender(<InstalledApp id="installed-app-456" />)
+ rerender(installedAppView('installed-app-456'))
expect(await screen.findByText('Workflow App')).toBeInTheDocument()
})
@@ -164,9 +140,7 @@ describe('InstalledApp', () => {
'fails closed for unsupported %s mode',
async (mode) => {
mocks.getInstalledApp.mockResolvedValue(createInstalledApp(mode))
-
- renderWithConsoleQuery(<InstalledApp id="installed-app-123" />)
-
+ renderInstalledApp()
expect(await screen.findByText('Unsupported installed app mode.')).toBeInTheDocument()
expect(screen.queryByText('Chat App')).not.toBeInTheDocument()
},
@@ -174,8 +148,7 @@ describe('InstalledApp', () => {
it('starts route-owned parameter, metadata, and access queries without waiting for detail', async () => {
mocks.getInstalledApp.mockReturnValue(new Promise(() => {}))
-
- renderWithConsoleQuery(<InstalledApp id="installed-app-123" />, {
+ renderInstalledApp('installed-app-123', {
systemFeatures: { webapp_auth: { enabled: true } },
})
@@ -187,10 +160,10 @@ describe('InstalledApp', () => {
})
it('writes one contract-derived app snapshot into the installed-app runtime store', async () => {
- renderWithConsoleQuery(<InstalledApp id="installed-app-123" />)
+ renderInstalledApp()
await waitFor(() =>
- expect(updateAppInfo).toHaveBeenCalledWith({
+ expect(useWebAppStore.getState().appInfo).toEqual({
app_id: 'installed-app-123',
custom_config: null,
site: {
@@ -209,27 +182,24 @@ describe('InstalledApp', () => {
)
})
- it('does not mount the app surface before the access query settles', async () => {
- ;(useGetUserCanAccessApp as Mock).mockReturnValue({
- data: undefined,
- error: null,
- isPending: true,
+ it('does not mount the app surface before the real access query settles', async () => {
+ mocks.getUserAccess.mockReturnValue(new Promise(() => {}))
+ renderInstalledApp('installed-app-123', {
+ systemFeatures: { webapp_auth: { enabled: true } },
})
- renderWithConsoleQuery(<InstalledApp id="installed-app-123" />)
-
- await waitFor(() => expect(mocks.getInstalledApp).toHaveBeenCalled())
+ await waitFor(() => expect(mocks.getUserAccess).toHaveBeenCalledWith('app-123'))
expect(screen.queryByText('Chat App')).not.toBeInTheDocument()
})
it('distinguishes a missing installed app from a recoverable detail failure', async () => {
mocks.getInstalledApp.mockRejectedValue(createHttpError(new Response(null, { status: 404 })))
- const { unmount } = renderWithConsoleQuery(<InstalledApp id="missing-app" />)
+ const { unmount } = renderInstalledApp('missing-app')
expect(await screen.findByText(/404/)).toBeInTheDocument()
unmount()
mocks.getInstalledApp.mockRejectedValue(new Error('Network unavailable'))
- renderWithConsoleQuery(<InstalledApp id="offline-app" />, {
+ renderInstalledApp('offline-app', {
queryClient: new QueryClient({ defaultOptions: { queries: { retryDelay: 0 } } }),
})
expect(await screen.findByText('Network unavailable')).toBeInTheDocument()
diff --git a/web/app/components/workflow/nodes/human-input/__tests__/panel.hitl-v2.spec.tsx b/web/app/components/workflow/nodes/human-input/__tests__/panel.hitl-v2.spec.tsx
index 16773fb99ea..28051c74ddb 100644
--- a/web/app/components/workflow/nodes/human-input/__tests__/panel.hitl-v2.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/__tests__/panel.hitl-v2.spec.tsx
@@ -1,367 +1,66 @@
-import type { ReactNode } from 'react'
-import type useConfig from '../hooks/use-config'
import type { HumanInputNodeType } from '../types'
-import type { NodePanelProps } from '@/app/components/workflow/types'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
+import { renderNodePanel } from '../../__tests__/render-node-panel'
import Panel from '../panel'
import { DeliveryMethodType, UserActionButtonType } from '../types'
-const mockHitlIm = vi.hoisted(() => ({ enabled: true }))
+const hitlIm = vi.hoisted(() => ({ enabled: true }))
vi.mock('@/config', async (importOriginal) => ({
...(await importOriginal<typeof import('@/config')>()),
get ENABLE_HITL_IM() {
- return mockHitlIm.enabled
+ return hitlIm.enabled
},
}))
-const mockUseConfig = vi.hoisted(() => vi.fn())
-const mockUseStore = vi.hoisted(() => vi.fn())
-const mockUseAvailableVarList = vi.hoisted(() => vi.fn())
-const mockDeliveryMethod = vi.hoisted(() => vi.fn())
-const mockFormContent = vi.hoisted(() => vi.fn())
-const mockFormContentPreview = vi.hoisted(() => vi.fn())
-const mockTimeoutInput = vi.hoisted(() => vi.fn())
-const mockUserActionItem = vi.hoisted(() => vi.fn())
-
-vi.mock('copy-to-clipboard', () => ({
- __esModule: true,
- default: vi.fn(),
-}))
-
-vi.mock('@/app/notifications', () => ({
- toast: {
- success: vi.fn(),
- },
-}))
-
-vi.mock('@/app/components/workflow/store', () => ({
- useStore: (selector: (state: { nodePanelWidth: number }) => unknown) => mockUseStore(selector),
-}))
-
-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
- __esModule: true,
- default: (...args: unknown[]) => mockUseAvailableVarList(...args),
-}))
-
-vi.mock('../hooks/use-config', () => ({
- __esModule: true,
- default: (...args: unknown[]) => mockUseConfig(...args),
-}))
-
-vi.mock('../components/delivery-method', () => ({
- __esModule: true,
- default: (props: {
- readonly: boolean
- onChange: (methods: HumanInputNodeType['delivery_methods']) => void
- }) => {
- mockDeliveryMethod(props)
- return (
- <button
- type="button"
- onClick={() =>
- props.onChange([
- {
- id: 'dm-email',
- type: DeliveryMethodType.Email,
- enabled: true,
- },
- ])
- }
- >
- {props.readonly ? 'delivery-method:readonly' : 'delivery-method:editable'}
- </button>
- )
- },
-}))
-
-vi.mock('../components/form-content', () => ({
- __esModule: true,
- default: (props: {
- readonly: boolean
- isExpand: boolean
- onChange: (value: string) => void
- onFormInputsChange: (value: HumanInputNodeType['inputs']) => void
- onFormInputItemRename: (oldName: string, newName: string) => void
- onFormInputItemRemove: (name: string) => void
- }) => {
- mockFormContent(props)
- return (
- <div>
- <div>
- {props.readonly
- ? 'form-content:readonly'
- : `form-content:${props.isExpand ? 'expanded' : 'collapsed'}`}
- </div>
- <button type="button" onClick={() => props.onChange('Updated content')}>
- change-form-content
- </button>
- <button
- type="button"
- onClick={() =>
- props.onFormInputsChange([
- {
- type: InputVarType.paragraph,
- output_variable_name: 'email',
- default: {
- selector: [],
- type: 'constant',
- value: '',
- },
- },
- ])
- }
- >
- change-form-inputs
- </button>
- <button type="button" onClick={() => props.onFormInputItemRename('name', 'email')}>
- rename-form-input
- </button>
- <button type="button" onClick={() => props.onFormInputItemRemove('name')}>
- remove-form-input
- </button>
- </div>
- )
- },
-}))
-
-vi.mock('../components/form-content-preview', () => ({
- __esModule: true,
- default: (props: { onClose: () => void }) => {
- mockFormContentPreview(props)
- return (
- <div>
- <div>form-preview</div>
- <button type="button" onClick={props.onClose}>
- close-preview
- </button>
- </div>
- )
- },
-}))
-
-vi.mock('../components/timeout', () => ({
- __esModule: true,
- default: (props: {
- readonly: boolean
- onChange: (value: { timeout: number; unit: 'hour' | 'day' }) => void
- }) => {
- mockTimeoutInput(props)
- return (
- <button type="button" onClick={() => props.onChange({ timeout: 8, unit: 'hour' })}>
- {props.readonly ? 'timeout:readonly' : 'timeout:editable'}
- </button>
- )
- },
-}))
-
-vi.mock('../components/user-action', () => ({
- __esModule: true,
- default: (props: {
- readonly: boolean
- data: HumanInputNodeType['user_actions'][number]
- onChange: (value: HumanInputNodeType['user_actions'][number]) => void
- onDelete: (id: string) => void
- }) => {
- mockUserActionItem(props)
- return (
- <div>
- <div>{`${props.data.id}:${props.readonly ? 'readonly' : 'editable'}`}</div>
- <button
- type="button"
- onClick={() =>
- props.onChange({
- ...props.data,
- title: `${props.data.title} updated`,
- })
- }
- >
- {`change-action-${props.data.id}`}
- </button>
- <button type="button" onClick={() => props.onDelete(props.data.id)}>
- {`delete-action-${props.data.id}`}
- </button>
- </div>
- )
- },
-}))
-
-vi.mock('@/app/components/workflow/nodes/_base/components/output-vars', () => ({
- __esModule: true,
- default: (props: {
- children: ReactNode
- collapsed?: boolean
- onCollapse?: (collapsed: boolean) => void
- }) => (
- <div>
- <button type="button" onClick={() => props.onCollapse?.(!props.collapsed)}>
- toggle-output-vars
- </button>
- {props.children}
- </div>
- ),
- VarItem: ({ name, type, description }: { name: string; type: string; description: string }) => (
- <div>{`${name}:${type}:${description}`}</div>
- ),
-}))
-
-vi.mock('@remixicon/react', () => ({
- RiAddLine: () => <span>add-icon</span>,
- RiClipboardLine: () => <span>clipboard-icon</span>,
- RiCollapseDiagonalLine: () => <span>collapse-icon</span>,
- RiExpandDiagonalLine: () => <span>expand-icon</span>,
- RiEyeLine: () => <span>preview-icon</span>,
-}))
-
const createData = (overrides: Partial<HumanInputNodeType> = {}): HumanInputNodeType => ({
title: 'Human Input',
desc: '',
type: BlockEnum.HumanInput,
- delivery_methods: [
- {
- id: 'dm-webapp',
- type: DeliveryMethodType.WebApp,
- enabled: true,
- },
- ],
+ delivery_methods: [{ id: 'dm-webapp', type: DeliveryMethodType.WebApp, enabled: true }],
form_content: 'Please review this request',
inputs: [
{
type: InputVarType.paragraph,
output_variable_name: 'review_result',
- default: {
- selector: [],
- type: 'constant',
- value: '',
- },
- },
- ],
- user_actions: [
- {
- id: 'approve',
- title: 'Approve',
- button_style: UserActionButtonType.Primary,
+ default: { selector: [], type: 'constant', value: '' },
},
],
+ user_actions: [{ id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary }],
timeout: 3,
timeout_unit: 'day',
...overrides,
})
-const createConfigResult = (
- overrides: Partial<ReturnType<typeof useConfig>> = {},
-): ReturnType<typeof useConfig> => ({
- readOnly: false,
- inputs: createData(),
- handleDeliveryMethodChange: vi.fn(),
- handleUserActionAdd: vi.fn(),
- handleUserActionChange: vi.fn(),
- handleUserActionDelete: vi.fn(),
- handleTimeoutChange: vi.fn(),
- handleFormContentChange: vi.fn(),
- handleFormInputsChange: vi.fn(),
- handleFormInputItemRename: vi.fn(),
- handleFormInputItemRemove: vi.fn(),
- editorKey: 1,
- structuredOutputCollapsed: true,
- setStructuredOutputCollapsed: vi.fn(),
- ...overrides,
-})
-
-const renderPanel = (data: HumanInputNodeType = createData()) => {
- const props: NodePanelProps<HumanInputNodeType> = {
- id: 'human-input-node',
+const renderPanel = (data = createData()) =>
+ renderNodePanel(
+ (props) => (
+ <NuqsTestingAdapter>
+ <Panel {...props} />
+ </NuqsTestingAdapter>
+ ),
data,
- panelProps: {
- getInputVars: vi.fn(() => []),
- toVarInputs: vi.fn(() => []),
- runInputData: {},
- runInputDataRef: { current: {} },
- setRunInputData: vi.fn(),
- runResult: null,
+ {
+ hooksStoreProps: { doSyncWorkflowDraft: async () => null },
},
- }
-
- return render(<Panel {...props} />)
-}
-
-describe('human-input/panel', () => {
- beforeEach(() => {
- mockHitlIm.enabled = true
- vi.clearAllMocks()
- mockUseStore.mockImplementation((selector) => selector({ nodePanelWidth: 480 }))
- mockUseAvailableVarList.mockImplementation(
- (_id, options?: { filterVar?: (payload: { type: VarType }) => boolean }) => ({
- availableVars: [
- {
- variable: ['start', 'email'],
- type: VarType.string,
- },
- {
- variable: ['code', 'result'],
- type: VarType.arrayString,
- },
- {
- variable: ['start', 'files'],
- type: VarType.file,
- },
- ].filter((variable) =>
- options?.filterVar ? options.filterVar({ type: variable.type } as never) : true,
- ),
- availableNodesWithParent: [
- {
- id: 'start-node',
- data: {
- title: 'Start',
- type: BlockEnum.Start,
- },
- },
- ],
- }),
- )
- mockUseConfig.mockReturnValue(createConfigResult())
- })
-
- it('shows the old-version badge only for legacy panel data', () => {
- const { rerender } = renderPanel()
- expect(screen.getByText('workflow.nodes.humanInputMigration.oldVersion')).toBeInTheDocument()
+ )
- const v2Data = createData() as HumanInputNodeType & { version: '2' }
- v2Data.version = '2'
- rerender(
- <Panel
- id="human-input-node"
- data={v2Data}
- panelProps={{
- getInputVars: vi.fn(() => []),
- toVarInputs: vi.fn(() => []),
- runInputData: {},
- runInputDataRef: { current: {} },
- setRunInputData: vi.fn(),
- runResult: null,
- }}
- />,
- )
- expect(
- screen.queryByText('workflow.nodes.humanInputMigration.oldVersion'),
- ).not.toBeInTheDocument()
- })
-
- it('keeps legacy delivery editing available without migration UI while disabled', async () => {
- mockHitlIm.enabled = false
+describe('human-input/panel HITL gate', () => {
+ it('keeps legacy delivery editing live while the HITL migration gate is off', async () => {
+ hitlIm.enabled = false
const user = userEvent.setup()
- const config = createConfigResult()
- mockUseConfig.mockReturnValue(config)
- renderPanel()
+ const { data } = renderPanel()
expect(
screen.queryByText('workflow.nodes.humanInputMigration.oldVersion'),
).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'delivery-method:editable' }))
- expect(config.handleDeliveryMethodChange).toHaveBeenCalledWith([
- { id: 'dm-email', type: DeliveryMethodType.Email, enabled: true },
+ await user.click(screen.getByRole('switch'))
+
+ expect(data().delivery_methods).toEqual([
+ { id: 'dm-webapp', type: DeliveryMethodType.WebApp, enabled: false },
])
})
})
diff --git a/web/app/components/workflow/panel/__tests__/workflow-preview.hitl-v2.spec.tsx b/web/app/components/workflow/panel/__tests__/workflow-preview.hitl-v2.spec.tsx
index a366890f5a7..5fdde67cdca 100644
--- a/web/app/components/workflow/panel/__tests__/workflow-preview.hitl-v2.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/workflow-preview.hitl-v2.spec.tsx
@@ -1,211 +1,122 @@
-import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
-import type { HumanInputFilledFormData, HumanInputFormData } from '@/types/workflow'
-import { screen } from '@testing-library/react'
+import type { HumanInputFormData } from '@/types/workflow'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createNode, createWorkflowRunningData } from '@/app/components/workflow/__tests__/fixtures'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
-import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import {
+ DeliveryMethodType,
+ UserActionButtonType,
+} from '@/app/components/workflow/nodes/human-input/types'
+import { BlockEnum, InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { submitHumanInputForm } from '@/service/workflow'
import WorkflowPreview from '../workflow-preview'
-const mockHandleCancelDebugAndPreviewPanel = vi.fn()
-
-vi.mock('copy-to-clipboard', () => ({
- default: vi.fn(),
-}))
-
-vi.mock('@/app/notifications', () => ({
- toast: {
- success: vi.fn(),
- },
+vi.mock('@/config', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/config')>()),
+ ENABLE_HITL_IM: true,
}))
-
-vi.mock('@/service/workflow', () => ({
+vi.mock('@/service/workflow', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/workflow')>()),
submitHumanInputForm: vi.fn(),
}))
-vi.mock('../../hooks/use-workflow-panel-interactions', async (importOriginal) => {
- const actual =
- await importOriginal<typeof import('../../hooks/use-workflow-panel-interactions')>()
-
- return {
- ...actual,
- useWorkflowInteractions: () => ({
- handleCancelDebugAndPreviewPanel: mockHandleCancelDebugAndPreviewPanel,
- }),
- }
-})
-
-vi.mock('@/app/components/workflow/run/result-panel', () => ({
- default: ({ status, onOpenTracingTab }: { status?: string; onOpenTracingTab?: () => void }) => (
- <div data-testid="result-panel">
- <div>{status}</div>
- <button type="button" onClick={onOpenTracingTab}>
- open-tracing
- </button>
- </div>
- ),
-}))
-
-vi.mock('@/app/components/workflow/run/result-text', () => ({
- default: ({
- outputs,
- isPaused,
- isRunning,
- onClick,
- }: {
- outputs?: string
- isPaused?: boolean
- isRunning?: boolean
- onClick?: () => void
- }) => (
- <div>
- <div data-testid="result-text">{JSON.stringify({ outputs, isPaused, isRunning })}</div>
- <button type="button" onClick={onClick}>
- open-detail
- </button>
- </div>
- ),
-}))
-
-vi.mock('@/app/components/workflow/run/tracing-panel', () => ({
- default: ({ list }: { list: unknown[] }) => <div data-testid="tracing-panel">{list.length}</div>,
-}))
-
-vi.mock('@/app/components/base/chat/chat/answer/reasoning-panel', () => ({
- default: ({ content, done }: { content: Record<string, string>; done: boolean }) => (
- <div data-testid="reasoning-panel" data-done={String(done)}>
- {Object.keys(content).join(',')}
- </div>
- ),
-}))
-
-vi.mock('@/app/components/workflow/panel/inputs-panel', () => ({
- default: ({ onRun }: { onRun: () => void }) => (
- <button type="button" onClick={onRun}>
- run-inputs
- </button>
- ),
-}))
-
-vi.mock('@/app/components/workflow/panel/human-input-form-list', () => ({
- default: ({
- humanInputFormDataList,
- onHumanInputFormSubmit,
- }: {
- humanInputFormDataList: unknown[]
- onHumanInputFormSubmit?: (
- token: string,
- formData: { inputs: Record<string, HumanInputFieldValue>; action: string },
- ) => Promise<void>
- }) => (
- <div>
- <div data-testid="human-form-list">{humanInputFormDataList.length}</div>
- <button
- type="button"
- onClick={() =>
- onHumanInputFormSubmit?.('form-token', { inputs: { answer: 'ok' }, action: 'approve' })
- }
- >
- submit-human-form
- </button>
- </div>
- ),
-}))
-
-vi.mock('@/app/components/workflow/panel/human-input-filled-form-list', () => ({
- default: ({ humanInputFilledFormDataList }: { humanInputFilledFormDataList: unknown[] }) => (
- <div data-testid="filled-form-list">{humanInputFilledFormDataList.length}</div>
- ),
-}))
const mockSubmitHumanInputForm = vi.mocked(submitHumanInputForm)
-
type WorkflowResult = NonNullable<ReturnType<typeof createWorkflowRunningData>['result']>
const createWorkflowResult = (overrides: Partial<WorkflowResult> = {}): WorkflowResult => ({
- status: WorkflowRunningStatus.Running,
+ status: WorkflowRunningStatus.Paused,
inputs_truncated: false,
process_data_truncated: false,
outputs_truncated: false,
+ files: [],
...overrides,
})
const createHumanInputFormData = (
- overrides: Partial<HumanInputFormData> = {},
+ version: HumanInputFormData['form_version'],
): HumanInputFormData => ({
form_id: 'form-1',
node_id: 'human-node-1',
node_title: 'Need Approval',
- form_content: 'Before {{#$output.reason#}} after',
- inputs: [],
- actions: [],
- form_token: 'token-1',
+ form_content: 'Name {{#$output.name#}} Reason {{#$output.reason#}}',
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'name',
+ default: { type: 'constant', value: '', selector: [] },
+ },
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'reason',
+ default: { type: 'constant', value: '', selector: [] },
+ },
+ ],
+ actions: [{ id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary }],
+ form_token: 'form-token',
+ form_version: version,
resolved_default_values: {},
display_in_ui: true,
- expiration_time: 2_000_000_000,
- ...overrides,
+ expiration_time: null,
})
-const createHumanInputFilledFormData = (
- overrides: Partial<HumanInputFilledFormData> = {},
-): HumanInputFilledFormData => ({
- form_id: 'form-1',
- node_id: 'node-1',
- node_title: 'Need Approval',
- rendered_content: 'rendered',
- action_id: 'approve',
- action_text: 'Approve',
- ...overrides,
+const createHumanInputNodeData = (version: '1' | '2') => ({
+ title: 'Need Approval',
+ desc: '',
+ type: BlockEnum.HumanInput,
+ version,
+ form_content: 'Name {{#$output.name#}} Reason {{#$output.reason#}}',
+ inputs: [],
+ user_actions: [{ id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary }],
+ timeout: 3,
+ timeout_unit: 'day',
+ ...(version === '2'
+ ? {
+ recipients_spec: [],
+ message_template: { subject: '', body: '' },
+ debug_mode: { enabled: false, channels: [] },
+ }
+ : {
+ delivery_methods: [{ id: 'webapp', type: DeliveryMethodType.WebApp, enabled: true }],
+ }),
})
-describe('WorkflowPreview', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- Object.defineProperty(window, 'innerWidth', {
- configurable: true,
- value: 1200,
- })
- })
-
+describe('WorkflowPreview HITL submission versions', () => {
it.each([undefined, '1', '2'] as const)(
- 'submits paused forms with event version %s',
+ 'submits the actual paused form with event version %s',
async (version) => {
+ mockSubmitHumanInputForm.mockResolvedValue({ result: 'success' })
const user = userEvent.setup()
- const pausedData = createWorkflowRunningData({
- result: createWorkflowResult({
- status: WorkflowRunningStatus.Paused,
- files: [],
- }),
- humanInputFormDataList: [
- createHumanInputFormData({ form_token: 'form-token', form_version: version }),
- ],
- humanInputFilledFormDataList: [createHumanInputFilledFormData()],
- })
-
+ const nodeVersion = version === '2' ? '1' : '2'
renderWorkflowFlowComponent(<WorkflowPreview />, {
nodes: [
createNode({
id: 'human-node-1',
type: 'default',
- data: { version: version === '2' ? '1' : '2' },
+ data: createHumanInputNodeData(nodeVersion),
}),
],
initialStoreState: {
- workflowRunningData: pausedData,
+ workflowRunningData: createWorkflowRunningData({
+ result: createWorkflowResult(),
+ humanInputFormDataList: [createHumanInputFormData(version)],
+ humanInputFilledFormDataList: [],
+ }),
},
})
- expect(screen.getByTestId('human-form-list')).toHaveTextContent('1')
- expect(screen.getByTestId('filled-form-list')).toHaveTextContent('1')
-
- await user.click(screen.getByRole('button', { name: 'submit-human-form' }))
- expect(mockSubmitHumanInputForm).toHaveBeenCalledWith(
- 'form-token',
- {
- inputs: { answer: 'ok' },
- action: 'approve',
- },
- version,
+ await user.type(screen.getByRole('textbox', { name: 'name' }), 'Ada')
+ await user.type(screen.getByRole('textbox', { name: 'reason' }), 'Ready to ship')
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+
+ await waitFor(() =>
+ expect(mockSubmitHumanInputForm).toHaveBeenCalledWith(
+ 'form-token',
+ {
+ inputs: { name: 'Ada', reason: 'Ready to ship' },
+ action: 'approve',
+ },
+ version,
+ ),
)
},
)