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 fabricated form, sidebar and access controls (#45248)

Stephen Zhou262158cfdbe5
diff --git a/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx b/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
index b6c9f3efab7..a5709bb2410 100644
--- a/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
+++ b/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
@@ -1,9 +1,7 @@
-import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { LegacyHumanInputFormData } from '@/features/human-input/form/types'
import { ORPCError } from '@orpc/client'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { useFileUploadContext } from '@/app/components/base/file-uploader/upload-context'
import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
@@ -18,15 +16,12 @@ vi.mock('@/config', async (importOriginal) => ({
},
}))
-const { mockGetForm, mockSubmitForm, mockUploadLocal, mockUploadRemote, uploadState } = vi.hoisted(
- () => ({
- mockGetForm: vi.fn(),
- mockSubmitForm: vi.fn(),
- mockUploadLocal: vi.fn(),
- mockUploadRemote: vi.fn(),
- uploadState: { onChange: undefined as ((files: FileEntity[]) => void) | undefined },
- }),
-)
+const { mockGetForm, mockSubmitForm, mockUploadLocal, mockUploadRemote } = vi.hoisted(() => ({
+ mockGetForm: vi.fn(),
+ mockSubmitForm: vi.fn(),
+ mockUploadLocal: vi.fn<typeof import('@/service/share').uploadHumanInputFormLocalFile>(),
+ mockUploadRemote: vi.fn(),
+}))
vi.mock('@/next/navigation', () => ({ useParams: () => ({ token: 'token-123' }) }))
vi.mock('@/service/share', async (importOriginal) => ({
@@ -37,49 +32,29 @@ vi.mock('@/service/share', async (importOriginal) => ({
uploadHumanInputFormRemoteFileInfo: mockUploadRemote,
}))
-// Retain the callback captured when upload starts, as the asynchronous uploader does.
-// Form parsing, text fields, validation and submission all remain real.
-vi.mock('@/app/components/base/file-uploader', () => ({
- FileUploaderInAttachmentWrapper: ({ onChange }: { onChange: (files: FileEntity[]) => void }) => {
- const { uploadStrategy } = useFileUploadContext()
- if (!uploadState.onChange) uploadState.onChange = onChange
- return (
- <div aria-label="Attachment upload">
- <button
- type="button"
- onClick={() =>
- uploadStrategy?.uploadLocal({
- file: new File(['review'], 'review.pdf', { type: 'application/pdf' }),
- onProgressCallback: vi.fn(),
- onSuccessCallback: vi.fn(),
- onErrorCallback: vi.fn(),
- })
- }
- >
- Upload local attachment
- </button>
- <button
- type="button"
- onClick={() => uploadStrategy?.uploadRemote('https://example.com/review.pdf')}
- >
- Upload linked attachment
- </button>
- </div>
- )
- },
-}))
+const uploadLocalAttachment = async (user: ReturnType<typeof userEvent.setup>) => {
+ // The native file input currently has no accessible label.
+ const input = document.querySelector<HTMLInputElement>('input[type="file"]')!
+ await user.upload(input, new File(['review'], 'review.pdf', { type: 'application/pdf' }))
+ await waitFor(() => expect(mockUploadLocal).toHaveBeenCalledOnce())
+ return mockUploadLocal.mock.calls[0]![0]
+}
-const uploadedFile: FileEntity = {
- id: 'file-1',
- name: 'review.pdf',
- size: 128,
- type: 'document',
- progress: 100,
- transferMethod: TransferMethod.local_file,
- supportFileType: SupportUploadFileTypes.document,
- uploadedId: 'upload-file-1',
+const completeUpload = async () => {
+ await act(async () => {
+ mockUploadLocal.mock.calls[0]![0].onSuccessCallback({
+ id: 'upload-file-1',
+ name: 'review.pdf',
+ size: 6,
+ mime_type: 'application/pdf',
+ extension: 'pdf',
+ created_by: 'form-user',
+ created_at: 0,
+ preview_url: null,
+ source_url: '',
+ })
+ })
}
-const completeUpload = () => act(() => uploadState.onChange?.([uploadedFile]))
describe.each([false, true])('Human input share form with IM gate %s', (enabled) => {
const originalTitle = document.title
@@ -119,7 +94,7 @@ describe.each([false, true])('Human input share form with IM gate %s', (enabled)
output_variable_name: 'attachments',
allowed_file_extensions: ['.pdf'],
allowed_file_types: [SupportUploadFileTypes.document],
- allowed_file_upload_methods: [TransferMethod.local_file],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
number_limits: 3,
},
],
@@ -141,8 +116,13 @@ describe.each([false, true])('Human input share form with IM gate %s', (enabled)
mockGetForm.mockResolvedValue(formData)
mockSubmitForm.mockResolvedValue({})
mockUploadLocal.mockReset().mockResolvedValue(undefined)
- mockUploadRemote.mockReset().mockResolvedValue({ id: 'remote-file' })
- uploadState.onChange = undefined
+ mockUploadRemote.mockReset().mockResolvedValue({
+ id: 'remote-file',
+ name: 'review.pdf',
+ mime_type: 'application/pdf',
+ size: 6,
+ url: 'https://example.com/review.pdf',
+ })
})
it('moves from loading to the requested form and updates its document title', async () => {
@@ -170,8 +150,16 @@ describe.each([false, true])('Human input share form with IM gate %s', (enabled)
const user = userEvent.setup()
render(<FormContent />)
- await user.click(await screen.findByRole('button', { name: 'Upload local attachment' }))
- await user.click(screen.getByRole('button', { name: 'Upload linked attachment' }))
+ await screen.findByRole('textbox', { name: 'summary' })
+ await uploadLocalAttachment(user)
+ await completeUpload()
+ await user.click(screen.getByRole('button', { name: 'common.fileUploader.pasteFileLink' }))
+ await user.type(
+ screen.getByPlaceholderText('common.fileUploader.pasteFileLinkInputPlaceholder'),
+ 'https://example.com/review.pdf',
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.ok' }))
+ await screen.findByText('https://example.com/review.pdf')
expect(mockUploadLocal).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
@@ -233,9 +221,10 @@ describe.each([false, true])('Human input share form with IM gate %s', (enabled)
const user = userEvent.setup()
render(<FormContent />)
const summary = await screen.findByRole('textbox', { name: 'summary' })
+ await uploadLocalAttachment(user)
await user.clear(summary)
await user.type(summary, 'updated summary')
- completeUpload()
+ await completeUpload()
expect(summary).toHaveValue('updated summary')
await user.click(screen.getByRole('button', { name: 'Approve' }))
@@ -266,7 +255,8 @@ describe.each([false, true])('Human input share form with IM gate %s', (enabled)
const user = userEvent.setup()
render(<FormContent />)
await screen.findByRole('textbox', { name: 'summary' })
- completeUpload()
+ await uploadLocalAttachment(user)
+ await completeUpload()
await user.click(screen.getByRole('button', { name: 'Approve' }))
await waitFor(() =>
@@ -285,9 +275,10 @@ describe.each([false, true])('Human input share form with IM gate %s', (enabled)
const approve = await screen.findByRole('button', { name: 'Approve' })
expect(approve).toBeDisabled()
- act(() => uploadState.onChange?.([{ ...uploadedFile, progress: 50, uploadedId: undefined }]))
+ const upload = await uploadLocalAttachment(user)
+ act(() => upload.onProgressCallback(50))
expect(approve).toBeDisabled()
- completeUpload()
+ await completeUpload()
expect(approve).toBeEnabled()
await user.clear(screen.getByRole('textbox', { name: 'summary' }))
expect(approve).toBeDisabled()
diff --git a/web/app/components/share/text-generation/__tests__/text-generation-sidebar.spec.tsx b/web/app/components/share/text-generation/__tests__/text-generation-sidebar.spec.tsx
index 22810945029..92eb2040b15 100644
--- a/web/app/components/share/text-generation/__tests__/text-generation-sidebar.spec.tsx
+++ b/web/app/components/share/text-generation/__tests__/text-generation-sidebar.spec.tsx
@@ -4,48 +4,23 @@ import type { SiteInfo } from '@/models/share'
import type { VisionSettings } from '@/types/app'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useRef, useState } from 'react'
import { AccessMode } from '@/models/access-control'
import { createSystemFeaturesFixture } from '@/test/console/system-features'
import { Resolution, TransferMethod } from '@/types/app'
import TextGenerationSidebar from '../text-generation-sidebar'
-const runOncePropsSpy = vi.fn()
-const runBatchPropsSpy = vi.fn()
-const savedItemsPropsSpy = vi.fn()
-
-vi.mock('@/app/components/share/text-generation/run-once', () => ({
- default: (props: Record<string, unknown>) => {
- runOncePropsSpy(props)
- return <div data-testid="run-once-mock" />
- },
-}))
-
-vi.mock('@/app/components/share/text-generation/run-batch', () => ({
- default: (props: Record<string, unknown>) => {
- runBatchPropsSpy(props)
- return <div data-testid="run-batch-mock" />
- },
-}))
-
-vi.mock('@/app/components/app/text-generate/saved-items', () => ({
- default: (props: { onStartCreateContent: () => void; list: Array<{ id: string }> }) => {
- savedItemsPropsSpy(props)
- return (
- <div data-testid="saved-items-mock">
- <span>{props.list.length}</span>
- <button onClick={props.onStartCreateContent}>back-to-create</button>
- </div>
- )
- },
-}))
-
-vi.mock('@/app/components/share/text-generation/text-generation-menu', () => ({
- default: () => <div data-testid="menu-dropdown-mock" />,
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn() }),
+ usePathname: () => '/',
+ useParams: () => ({}),
}))
const promptConfig: PromptConfig = {
prompt_template: 'template',
- prompt_variables: [{ key: 'name', name: 'Name', type: 'string', required: true }],
+ prompt_variables: [
+ { key: 'name', name: 'Name', type: 'string', required: true, default: 'Alice' },
+ ],
}
const savedMessages: SavedMessage[] = [
@@ -99,68 +74,70 @@ const baseProps: ComponentProps<typeof TextGenerationSidebar> = {
}
const renderSidebar = (overrides: Partial<typeof baseProps> = {}) => {
- return render(<TextGenerationSidebar {...baseProps} {...overrides} />)
+ function Caller() {
+ const [currentTab, setCurrentTab] = useState(overrides.currentTab ?? baseProps.currentTab)
+ const [inputs, setInputs] = useState(baseProps.inputs)
+ const inputsRef = useRef(inputs)
+ const [savedMessages, setSavedMessages] = useState(baseProps.savedMessages)
+ return (
+ <TextGenerationSidebar
+ {...baseProps}
+ {...overrides}
+ currentTab={currentTab}
+ onTabChange={setCurrentTab}
+ inputs={inputs}
+ inputsRef={inputsRef}
+ onInputsChange={setInputs}
+ savedMessages={savedMessages}
+ onRemoveSavedMessage={async (id) =>
+ setSavedMessages((messages) => messages.filter((message) => message.id !== id))
+ }
+ />
+ )
+ }
+ return render(<Caller />)
}
describe('TextGenerationSidebar', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should render create tab content and pass orchestration props to RunOnce', () => {
+ it('renders the create form with its configured input', () => {
renderSidebar()
expect(screen.getByText('Text Generation')).toBeInTheDocument()
expect(screen.getByText('Share description')).toBeInTheDocument()
- expect(screen.getByTestId('run-once-mock')).toBeInTheDocument()
- expect(runOncePropsSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- inputs: { name: 'Alice' },
- promptConfig,
- runControl: null,
- visionConfig,
- }),
- )
- expect(screen.queryByTestId('saved-items-mock')).not.toBeInTheDocument()
+ expect(screen.getByRole('textbox', { name: 'Name' })).toHaveValue('Alice')
+ expect(screen.getByRole('button', { name: 'share.generation.run' })).toBeEnabled()
+ expect(screen.queryByText('Answer 1')).not.toBeInTheDocument()
})
- it('should render batch tab and hide saved tab for workflow apps', () => {
- renderSidebar({
- currentTab: 'batch',
- isWorkflow: true,
- })
+ it('renders the batch uploader and hides saved content for workflow apps', () => {
+ renderSidebar({ currentTab: 'batch', isWorkflow: true })
- expect(screen.getByTestId('run-batch-mock')).toBeInTheDocument()
- expect(runBatchPropsSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- vars: promptConfig.prompt_variables,
- isAllFinished: true,
- }),
- )
+ expect(screen.getByText('share.generation.csvUploadTitle')).toBeInTheDocument()
+ expect(screen.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'share.generation.run' })).toBeDisabled()
expect(
screen.queryByRole('tab', { name: /^share\.generation\.tabs\.saved/ }),
).not.toBeInTheDocument()
})
- it('should render saved items and allow switching back to create tab', async () => {
+ it('renders saved answers and switches back to the real create form', async () => {
const user = userEvent.setup()
- const onTabChange = vi.fn()
-
- renderSidebar({
- currentTab: 'saved',
- onTabChange,
- })
-
- expect(screen.getByTestId('saved-items-mock')).toBeInTheDocument()
- expect(savedItemsPropsSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- list: baseProps.savedMessages,
- isShowTextToSpeech: true,
- }),
+ renderSidebar({ currentTab: 'saved' })
+
+ expect(await screen.findByText('Answer 1')).toBeInTheDocument()
+ expect(screen.getByText('Answer 2')).toBeInTheDocument()
+ for (const button of screen.getAllByRole('button', { name: 'common.operation.delete' }))
+ await user.click(button)
+ expect(screen.getByText('share.generation.savedNoData.title')).toBeInTheDocument()
+ await user.click(
+ screen.getByRole('button', { name: 'share.generation.savedNoData.startCreateContent' }),
)
-
- await user.click(screen.getByRole('button', { name: 'back-to-create' }))
- expect(onTabChange).toHaveBeenCalledWith('create')
+ expect(screen.getByRole('tab', { name: 'share.generation.tabs.create' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ )
+ expect(screen.getByRole('textbox', { name: 'Name' })).toHaveValue('Alice')
+ expect(screen.queryByText('Answer 1')).not.toBeInTheDocument()
})
it('should prefer workspace branding and hide powered-by block when branding is removed', () => {
diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
index 6dc48cb9d13..eac0099662b 100644
--- a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
@@ -32,29 +32,10 @@ const mocks = vi.hoisted(() => ({
apiEnableMutation: vi.fn(),
createApiKeyMutation: vi.fn(),
deleteApiKeyMutation: vi.fn(),
- accessControlRender: vi.fn(),
+ updateAccessMutation: vi.fn(),
accessSubjectsQueryFn: vi.fn(),
}))
-vi.mock('@/app/components/app/app-access-control', () => ({
- default: ({
- app,
- onConfirm,
- }: {
- app: { id: string; access_mode: string }
- onConfirm: () => Promise<void>
- }) => {
- mocks.accessControlRender(app)
- return (
- <div role="dialog" aria-label="access-control">
- <button type="button" onClick={() => void onConfirm()}>
- Save access control
- </button>
- </div>
- )
- },
-}))
-
vi.mock('@/service/share', () => ({
getUserCanAccess: mocks.getUserCanAccess,
}))
@@ -113,6 +94,7 @@ vi.mock('@/service/console', async (importOriginal) => {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'enterprise.webAppAuth.getWebAppWhitelistSubjects': mocks.accessSubjectsQueryFn,
+ 'enterprise.webAppAuth.updateWebAppWhitelistSubjects': mocks.updateAccessMutation,
'apps.byAppId.siteEnable.post': mocks.siteEnableMutation,
'apps.byAppId.site.post': mocks.siteMutation,
'apps.byAppId.site.accessTokenReset.post': mocks.siteAccessTokenResetMutation,
@@ -197,16 +179,22 @@ function createAccessCardWrapper(queryClient: QueryClient) {
function renderWithQueryClient(
ui: React.ReactElement,
- { webAppAuthEnabled = true }: { webAppAuthEnabled?: boolean } = {},
+ {
+ webAppAuthEnabled = true,
+ agent,
+ }: { webAppAuthEnabled?: boolean; agent?: AgentAppDetailWithSite } = {},
) {
- const queryClient = createConsoleQueryClient(webAppAuthEnabled)
+ const queryClient = createConsoleQueryClient(webAppAuthEnabled, agent)
render(ui, { wrapper: createAccessCardWrapper(queryClient) })
return queryClient
}
-function createConsoleQueryClient(webAppAuthEnabled = true) {
+function createConsoleQueryClient(
+ webAppAuthEnabled = true,
+ agent: AgentAppDetailWithSite = createAgent(),
+) {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
@@ -227,7 +215,7 @@ function createConsoleQueryClient(webAppAuthEnabled = true) {
queryClient.setQueryData<AgentAppDetailWithSite>(
consoleQuery.agent.byAgentId.get.queryOptions({ input: { params: { agent_id: 'agent-1' } } })
.queryKey,
- createAgent(),
+ agent,
)
seedFeatures(queryClient)
return queryClient
@@ -262,6 +250,7 @@ describe('Agent access surface cards', () => {
mocks.agentDetailQueryFn.mockResolvedValue(createAgent())
mocks.getUserCanAccess.mockResolvedValue({ result: true })
mocks.accessSubjectsQueryFn.mockResolvedValue({ groups: [], members: [] })
+ mocks.updateAccessMutation.mockResolvedValue({ result: 'success' })
})
afterEach(() => vi.restoreAllMocks())
@@ -364,19 +353,29 @@ describe('Agent access surface cards', () => {
await user.click(
screen.getByRole('button', { name: /accessControlDialog\.accessItems\.specific/ }),
)
- const dialog = await screen.findByRole('dialog', { name: 'access-control' })
- expect(screen.getByRole('button', { name: /webApp\.actions\.open/ })).toHaveAttribute(
- 'aria-disabled',
- 'true',
- )
+ const dialog = await screen.findByRole('dialog', { name: 'app.accessControlDialog.title' })
+ expect(
+ screen.getByRole('button', { name: /webApp\.actions\.open/, hidden: true }),
+ ).toHaveAttribute('aria-disabled', 'true')
+ await user.click(
+ within(dialog).getByRole('radio', {
+ name: 'app.accessControlDialog.accessItems.organization',
+ }),
+ )
mocks.getUserCanAccess.mockResolvedValue({ result: true })
- await user.click(within(dialog).getByRole('button', { name: 'Save access control' }))
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.confirm' }))
+ await waitFor(() =>
+ expect(mocks.updateAccessMutation).toHaveBeenCalledExactlyOnceWith({
+ body: { appId: 'app-1', accessMode: AccessMode.ORGANIZATION },
+ }),
+ )
expect(await screen.findByRole('link', { name: /webApp\.actions\.open/ })).toHaveAttribute(
'href',
'https://chat.example.test/agent/site-token',
)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('should serialize Web App toggles and cache each confirmed response', async () => {
@@ -390,10 +389,7 @@ describe('Agent access surface cards', () => {
const agent = createAgent()
const queryClient = renderWithQueryClient(
<WebAppAccessCard agent={agent} agentId="agent-1" isLoading={false} />,
- )
- queryClient.setQueryData(
- consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
- agent,
+ { agent },
)
expect(screen.getByText('https://chat.example.test/agent/site-token')).toBeInTheDocument()
@@ -533,10 +529,7 @@ describe('Agent access surface cards', () => {
const agent = createAgent()
const queryClient = renderWithQueryClient(
<WebAppAccessCard agent={agent} agentId="agent-1" isLoading={false} />,
- )
- queryClient.setQueryData(
- consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
- agent,
+ { agent },
)
mocks.siteAccessTokenResetMutation.mockResolvedValueOnce(
createAppSiteFixture({ code: 'new-site-token' }),
@@ -652,10 +645,7 @@ describe('Agent access surface cards', () => {
const queryClient = renderWithQueryClient(
<WebAppAccessCard agent={agent} agentId="agent-1" isLoading={false} />,
- )
- queryClient.setQueryData(
- consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
- agent,
+ { agent },
)
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries')
@@ -1020,11 +1010,9 @@ describe('Agent access surface cards', () => {
mocks.apiEnableMutation.mockResolvedValueOnce(updatedApiAccess)
const agent = createAgent({ enable_api: false })
- const queryClient = renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)
- queryClient.setQueryData(
- consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
+ const queryClient = renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />, {
agent,
- )
+ })
await screen.findByText(initialApiAccess.service_api_base_url)
await user.click(
@@ -1277,11 +1265,18 @@ describe('Agent access surface cards', () => {
await user.click(screen.getByRole('button', { name: organizationAccessLabel }))
- expect(await screen.findByRole('dialog', { name: 'access-control' })).toBeInTheDocument()
- expect(mocks.accessControlRender).toHaveBeenCalledWith({
- id: 'backing-app-1',
- access_mode: 'private_all',
- })
+ const dialog = await screen.findByRole('dialog', { name: 'app.accessControlDialog.title' })
+ expect(within(dialog).getByRole('radio', { name: organizationAccessLabel })).toBeChecked()
+ await user.click(
+ within(dialog).getByRole('radio', { name: 'app.accessControlDialog.accessItems.external' }),
+ )
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.confirm' }))
+ await waitFor(() =>
+ expect(mocks.updateAccessMutation).toHaveBeenCalledExactlyOnceWith({
+ body: { appId: 'backing-app-1', accessMode: AccessMode.EXTERNAL_MEMBERS },
+ }),
+ )
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
})
it('allows viewers to copy and open WebApp addresses while disabling management actions', async () => {
diff --git a/web/features/human-input/public/__tests__/form.spec.tsx b/web/features/human-input/public/__tests__/form.spec.tsx
index 1b4307fd3ac..a7ca365ab62 100644
--- a/web/features/human-input/public/__tests__/form.spec.tsx
+++ b/web/features/human-input/public/__tests__/form.spec.tsx
@@ -1,106 +1,46 @@
import type { HumanInputV2FormTransport } from '../types'
-import { act, render, screen, waitFor } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { useFileUploadContext } from '@/app/components/base/file-uploader/upload-context'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import HumanInputV2Form from '../form'
-import { createMockHumanInputV2FormTransport, HUMAN_INPUT_V2_MOCK_OTP } from '../mock-transport'
-
-const mockPresentation = vi.hoisted(() => ({
- lastDefinition: undefined as unknown,
-}))
-
-vi.mock('@/features/human-input/form/loaded-form-content', () => ({
- default: function MockLoadedFormContent({
- definition,
- isSubmitting,
- actionsDisabled,
- verificationContent,
- onSubmit,
- }: {
- definition: unknown
- isSubmitting: boolean
- actionsDisabled: boolean
- verificationContent: React.ReactNode
- onSubmit: (inputs: Record<string, unknown>, action: string) => void
- }) {
- const { uploadStrategy } = useFileUploadContext()
- mockPresentation.lastDefinition = definition
- return (
- <div>
- {verificationContent}
- <button
- type="button"
- onClick={() =>
- uploadStrategy?.uploadLocal({
- file: new File(['review'], 'review.txt', { type: 'text/plain' }),
- onProgressCallback: vi.fn(),
- onSuccessCallback: vi.fn(),
- onErrorCallback: vi.fn(),
- })
- }
- >
- Upload local attachment
- </button>
- <button
- type="button"
- onClick={() => uploadStrategy?.uploadRemote('https://example.com/review.txt')}
- >
- Upload linked attachment
- </button>
- <button
- type="button"
- disabled={isSubmitting || actionsDisabled}
- onClick={() => onSubmit({ response: 'approved' }, 'approve')}
- >
- Approve
- </button>
- <button
- type="button"
- disabled={isSubmitting || actionsDisabled}
- onClick={() => onSubmit({ response: 'rejected' }, 'reject')}
- >
- Reject
- </button>
- </div>
- )
- },
-}))
-
-vi.mock('@/features/human-input/form/form-status-card', () => ({
- default: ({
- title,
- subtitle,
- submissionID,
- }: {
- title: React.ReactNode
- subtitle?: React.ReactNode
- submissionID?: string
- }) => (
- <div>
- <div>{title}</div>
- <div>{subtitle}</div>
- {submissionID && <div>{submissionID}</div>}
- </div>
- ),
-}))
-
-describe('HumanInputV2Form', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockPresentation.lastDefinition = undefined
+import {
+ createHumanInputV2MockScenario,
+ createMockHumanInputV2FormTransport,
+ HUMAN_INPUT_V2_MOCK_OTP,
+} from '../mock-transport'
+
+vi.mock('@/next/navigation', () => ({ useParams: () => ({}) }))
+
+// OTP scenarios use a supported text-only definition; the upload/navigation
+// scenario below retains the attachment definition.
+const createTextFormTransport = () => {
+ const { definition } = createHumanInputV2MockScenario()
+ return createMockHumanInputV2FormTransport({
+ scenario: {
+ definition: {
+ ...definition,
+ formContent: '{{#$output.response#}}',
+ inputs: definition.inputs.filter((input) => input.output_variable_name === 'response'),
+ },
+ },
})
+}
+describe('HumanInputV2Form', () => {
it('loads the definition, requests one OTP, validates its shape, and submits one atomic payload', async () => {
const user = userEvent.setup()
- const transport = createMockHumanInputV2FormTransport()
+ const transport = createTextFormTransport()
const getForm = vi.spyOn(transport, 'getForm')
const requestAccess = vi.spyOn(transport, 'requestAccess')
const submit = vi.spyOn(transport, 'submit')
render(<HumanInputV2Form token="form-token" transport={transport} />)
- expect(screen.getByRole('progressbar', { name: 'common.loading' })).toBeInTheDocument()
+ expect(screen.getByLabelText('common.loading')).toBeInTheDocument()
const otpInput = await screen.findByLabelText('share.humanInputV2.otpLabel')
+ const response = screen.getByRole('textbox', { name: 'response' })
+ await user.clear(response)
+ await user.type(response, 'approved')
const approve = screen.getByRole('button', { name: 'Approve' })
expect(getForm).toHaveBeenCalledWith('form-token')
expect(requestAccess).toHaveBeenCalledTimes(1)
@@ -122,13 +62,15 @@ describe('HumanInputV2Form', () => {
}),
)
expect(await screen.findByText('share.humanInput.thanks')).toBeInTheDocument()
- expect(screen.getByText('form-token')).toBeInTheDocument()
+ expect(
+ screen.getByText('share.humanInput.submissionID:{"id":"form-token"}'),
+ ).toBeInTheDocument()
expect(screen.queryByLabelText('share.humanInputV2.otpLabel')).not.toBeInTheDocument()
})
it('allows invalid OTP correction while preserving the current challenge', async () => {
const user = userEvent.setup()
- const transport = createMockHumanInputV2FormTransport()
+ const transport = createTextFormTransport()
const requestAccess = vi.spyOn(transport, 'requestAccess')
render(<HumanInputV2Form token="form-token" transport={transport} />)
@@ -152,7 +94,7 @@ describe('HumanInputV2Form', () => {
const submitPromise = new Promise<void>((resolve) => {
resolveSubmit = resolve
})
- const baseTransport = createMockHumanInputV2FormTransport()
+ const baseTransport = createTextFormTransport()
const submit = vi.fn<HumanInputV2FormTransport['submit']>().mockReturnValue(submitPromise)
const transport = { ...baseTransport, submit }
@@ -187,7 +129,9 @@ describe('HumanInputV2Form', () => {
expect(await screen.findByText(copy)).toBeInTheDocument()
if (formState === 'expired' || formState === 'submitted') {
expect(screen.getByText('share.humanInput.sorry')).toBeInTheDocument()
- expect(screen.getByText('form-token')).toBeInTheDocument()
+ expect(
+ screen.getByText('share.humanInput.submissionID:{"id":"form-token"}'),
+ ).toBeInTheDocument()
}
expect(requestAccess).not.toHaveBeenCalled()
expect(screen.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument()
@@ -217,21 +161,46 @@ describe('HumanInputV2Form', () => {
render(<HumanInputV2Form token="form-token" transport={transport} />)
await screen.findByLabelText('share.humanInputV2.otpLabel')
- expect(mockPresentation.lastDefinition).not.toHaveProperty('branding')
+ expect(screen.getByRole('textbox', { name: 'response' })).toHaveValue('Looks good')
+ expect(screen.getByText('share.chat.poweredBy')).toBeInTheDocument()
+ expect(screen.getByRole('img', { name: 'Dify' })).toBeInTheDocument()
})
it('scopes attachment uploads to the displayed token and injected transport after navigation', async () => {
const user = userEvent.setup()
const transport = createMockHumanInputV2FormTransport()
const uploadLocalFile = vi.spyOn(transport, 'uploadLocalFile')
- const uploadRemoteFile = vi.spyOn(transport, 'uploadRemoteFile')
+ const uploadRemoteFile = vi.spyOn(transport, 'uploadRemoteFile').mockResolvedValue({
+ id: 'remote-2',
+ name: 'review.txt',
+ mimeType: 'text/plain',
+ size: 6,
+ url: 'https://example.com/review.txt',
+ })
const { rerender } = render(<HumanInputV2Form token="first-form" transport={transport} />)
- await user.click(await screen.findByRole('button', { name: 'Upload local attachment' }))
+ await screen.findByRole('textbox', { name: 'response' })
+ // The native chooser has no accessible label in the current uploader.
+ await user.upload(
+ document.querySelector<HTMLInputElement>('input[type="file"]')!,
+ new File(['review'], 'review.txt', { type: 'text/plain' }),
+ )
+ await screen.findByText('review.txt')
+ await waitFor(() => expect(uploadLocalFile).toHaveBeenCalledOnce())
expect(uploadLocalFile).toHaveBeenCalledWith('first-form', expect.any(File))
rerender(<HumanInputV2Form token="second-form" transport={transport} />)
- await user.click(await screen.findByRole('button', { name: 'Upload linked attachment' }))
+ await waitFor(() => expect(screen.queryByText('review.txt')).not.toBeInTheDocument())
+ await user.click(
+ await screen.findByRole('button', { name: 'common.fileUploader.pasteFileLink' }),
+ )
+ await user.type(
+ screen.getByPlaceholderText('common.fileUploader.pasteFileLinkInputPlaceholder'),
+ 'https://example.com/review.txt',
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.ok' }))
+ await screen.findByText('https://example.com/review.txt')
+ await waitFor(() => expect(uploadRemoteFile).toHaveBeenCalledOnce())
expect(uploadRemoteFile).toHaveBeenCalledWith('second-form', 'https://example.com/review.txt')
})
})