chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,26 @@
# Console Human Input Form
The authenticated session owner within the [Human Input feature].
`/human-input/[formToken]` is the signed-in Console approval page.
It reuses the Console authentication boundary and the existing form
presentation in [form]. Login redirects preserve the form URL. The backend remains the
authority for workspace access and recipient eligibility.
- `form.tsx` owns fetching, submission, expiry, and completion/error states.
- `definition.ts` validates the generated Console response, then maps ordered
`resolved_form.parts`, field defaults, actions and expiration to the shared UI.
- `links.ts` maps backstage links from Console pause details to this page.
Public V2 and unrelated links are left unchanged.
Reads and submissions use the generated GET/POST contract for
`/console/api/form/human-input/v2/{form_token}`. Submission sends `inputs` and
`action`. Errors never fall back to the old form endpoint or another auth surface.
No generated contracts or backend code are modified here.
Public `/form/[token]` and `/form-v2/[token]` pages keep their existing behavior.
This Console page retains its current authenticated upload path. Form-scoped
Console upload authorization is a separate pending API contract (WTA-3537);
module consolidation does not implement that authorization or add an endpoint.
[Human Input feature]: ../README.md
[form]: ../form/README.md
@@ -0,0 +1,186 @@
import type {
ConsoleHumanInputV2FormDefinitionResponse,
ResolvedForm,
} from '@dify/contracts/api/console/form/types.gen'
import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import { normalizeConsoleFormDefinition } from '../definition'
const createResponse = (
overrides: Partial<ResolvedForm> = {},
): ConsoleHumanInputV2FormDefinitionResponse => ({
expiration_time: 1_900_000_000,
resolved_form: {
title: 'Review request',
legacy_form_content: 'Unrelated legacy body {{#$output.OldField#}}',
parts: [],
actions: [{ id: 'Approve_A', title: 'Approve', button_style: 'primary' }],
...overrides,
},
})
describe('normalizeConsoleFormDefinition', () => {
it('renders authoritative parts in source order with case-sensitive field and action names', () => {
const definition = normalizeConsoleFormDefinition(
createResponse({
parts: [
{ type: 'markdown_fragment', text: '# Please review\n\n' },
{
type: 'paragraph_input',
output_variable_name: 'ReviewNote',
default_value: 'First\nSecond',
},
{ type: 'markdown_fragment', text: '\n\nDecision: ' },
{
type: 'select_input',
output_variable_name: 'Decision',
options: ['Accept', 'Reject'],
default_value: 'Accept',
},
{ type: 'markdown_fragment', text: '\n\nThank you.' },
],
}),
)
expect(definition.formContent).toBe(
'# Please review\n\n{{#$output.ReviewNote#}}\n\nDecision: {{#$output.Decision#}}\n\nThank you.',
)
expect(definition.inputs).toEqual([
{
type: InputVarType.paragraph,
output_variable_name: 'ReviewNote',
default: { type: 'constant', value: 'First\nSecond', selector: [] },
},
{
type: InputVarType.select,
output_variable_name: 'Decision',
option_source: { type: 'constant', value: ['Accept', 'Reject'], selector: [] },
},
])
expect(definition.resolvedDefaultValues).toEqual({
ReviewNote: 'First\nSecond',
Decision: 'Accept',
})
expect(definition.actions).toEqual([
{ id: 'Approve_A', title: 'Approve', button_style: 'primary' },
])
expect(definition.expirationTime).toBe(1_900_000_000)
})
it('retains repeated output slots with one input configuration per field', () => {
const field = {
type: 'paragraph_input',
output_variable_name: 'Note',
default_value: 'Same value',
} satisfies ResolvedForm['parts'][number]
const definition = normalizeConsoleFormDefinition(
createResponse({ parts: [field, { type: 'markdown_fragment', text: '\nAgain: ' }, field] }),
)
expect(definition.formContent).toBe('{{#$output.Note#}}\nAgain: {{#$output.Note#}}')
expect(definition.inputs.map((input) => input.output_variable_name)).toEqual(['Note'])
expect(definition.resolvedDefaultValues).toEqual({ Note: 'Same value' })
})
it('distinguishes absent defaults from intentionally empty text and selection defaults', () => {
const definition = normalizeConsoleFormDefinition(
createResponse({
parts: [
{ type: 'paragraph_input', output_variable_name: 'NoDefault', default_value: null },
{ type: 'paragraph_input', output_variable_name: 'EmptyText', default_value: '' },
{
type: 'select_input',
output_variable_name: 'NoSelection',
options: ['A'],
default_value: null,
},
{
type: 'select_input',
output_variable_name: 'EmptySelection',
options: ['', 'A'],
default_value: '',
},
],
}),
)
expect(definition.resolvedDefaultValues).toEqual({ EmptyText: '', EmptySelection: '' })
expect(definition.inputs[0]).toMatchObject({ default: { type: 'constant', value: '' } })
})
it('preserves single and multiple file restrictions without inventing string defaults', () => {
const definition = normalizeConsoleFormDefinition(
createResponse({
parts: [
{
type: 'file_input',
output_variable_name: 'EvidenceImage',
allowed_file_types: ['image', 'custom'],
allowed_file_extensions: ['.png', '.webp'],
allowed_file_upload_methods: ['local_file', 'remote_url'],
},
{
type: 'file_list_input',
output_variable_name: 'Documents',
allowed_file_types: ['document'],
allowed_file_extensions: ['.pdf'],
allowed_file_upload_methods: ['local_file'],
number_limits: 3,
},
],
}),
)
expect(definition.formContent).toBe('{{#$output.EvidenceImage#}}{{#$output.Documents#}}')
expect(definition.inputs).toEqual([
{
type: InputVarType.singleFile,
output_variable_name: 'EvidenceImage',
allowed_file_types: [SupportUploadFileTypes.image, SupportUploadFileTypes.custom],
allowed_file_extensions: ['.png', '.webp'],
allowed_file_upload_methods: ['local_file', 'remote_url'],
},
{
type: InputVarType.multiFiles,
output_variable_name: 'Documents',
allowed_file_types: [SupportUploadFileTypes.document],
allowed_file_extensions: ['.pdf'],
allowed_file_upload_methods: ['local_file'],
number_limits: 3,
},
])
expect(definition.resolvedDefaultValues).toEqual({})
})
it('uses the shared uploader restriction for interactive transfer methods', () => {
const definition = normalizeConsoleFormDefinition(
createResponse({
parts: [
{
type: 'file_input',
output_variable_name: 'Attachment',
allowed_file_types: ['document'],
allowed_file_extensions: [],
allowed_file_upload_methods: [
'tool_file',
'local_file',
'datasource_file',
'remote_url',
],
},
],
}),
)
expect(definition.inputs[0]).toMatchObject({
allowed_file_upload_methods: ['local_file', 'remote_url'],
})
})
it('does not resurrect legacy controls when the authoritative form has no parts', () => {
const definition = normalizeConsoleFormDefinition(createResponse())
expect(definition.formContent).toBe('')
expect(definition.inputs).toEqual([])
expect(definition.resolvedDefaultValues).toEqual({})
})
})
@@ -0,0 +1,468 @@
import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
import type { ConsoleHumanInputV2FormDefinitionResponse } from '@dify/contracts/api/console/form/types.gen'
import type { UseQueryOptions } from '@tanstack/react-query'
import type { HumanInputFormDefinition } from '@/features/human-input/form/types'
import type { consoleClient, consoleQuery } from '@/service/console'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ConsoleHumanInputForm from '../form'
type ConsoleFormSubmitInput = Parameters<
typeof consoleClient.form.humanInput.v2.byFormToken.post
>[0]
type LogoutMutationOptions = Parameters<typeof consoleQuery.logout.post.mutationOptions>[0]
const {
fetchForm,
fetchLegacyForm,
submitForm,
submitLegacyForm,
fetchProfile,
logout,
deployment,
} = vi.hoisted(() => ({
fetchForm: vi.fn<(token: string) => Promise<ConsoleHumanInputV2FormDefinitionResponse>>(),
fetchLegacyForm: vi.fn(),
submitForm: vi.fn<(input: ConsoleFormSubmitInput) => Promise<Record<string, unknown>>>(),
submitLegacyForm: vi.fn(),
fetchProfile: vi.fn<typeof consoleClient.account.profile.get>(),
logout: vi.fn<() => ReturnType<typeof consoleClient.logout.post>>(),
deployment: { basePath: '' },
}))
type FormQueryOptions = Omit<
UseQueryOptions<ConsoleHumanInputV2FormDefinitionResponse, Error, HumanInputFormDefinition>,
'queryKey' | 'queryFn'
> & {
input: { params: { form_token: string } }
context: { silent: boolean }
}
// Load the real code-split renderer before assertions start their interaction deadlines.
beforeAll(async () => {
await import('@/app/components/base/markdown/streamdown-wrapper')
})
vi.mock('@/service/console', () => ({
consoleClient: {
account: { profile: { get: fetchProfile } },
},
consoleQuery: {
account: {
profile: { get: { queryKey: () => ['account-profile'] } },
},
logout: {
post: {
mutationOptions: (options: LogoutMutationOptions) => ({
...options,
mutationFn: logout,
}),
},
},
form: {
humanInput: {
byFormToken: {
get: {
queryOptions: ({ input, context: _context, ...options }: FormQueryOptions) => ({
...options,
queryKey: ['legacy-console-human-input-form', input.params.form_token],
queryFn: () => fetchLegacyForm(input.params.form_token),
}),
},
},
v2: {
byFormToken: {
get: {
queryOptions: ({ input, context: _context, ...options }: FormQueryOptions) => ({
...options,
queryKey: ['console-human-input-v2-form', input.params.form_token],
queryFn: () => fetchForm(input.params.form_token),
}),
},
post: {
mutationOptions: () => ({
mutationFn: (input: ConsoleFormSubmitInput) => submitForm(input),
}),
},
},
},
},
},
},
}))
vi.mock('@/service/workflow', () => ({
submitHumanInputForm: submitLegacyForm,
}))
vi.mock('@/app/components/base/amplitude/utils', () => ({ resetUser: vi.fn() }))
vi.mock('@/utils/var', async (importOriginal) => ({
...(await importOriginal<typeof import('@/utils/var')>()),
get basePath() {
return deployment.basePath
},
}))
vi.mock('@/hooks/use-document-title', () => ({ default: vi.fn() }))
const createDefinition = (
overrides: Partial<ConsoleHumanInputV2FormDefinitionResponse> = {},
): ConsoleHumanInputV2FormDefinitionResponse => ({
resolved_form: {
title: 'Console approval',
legacy_form_content: '# {{#start.title#}}\n\n{{#$output.response#}}',
parts: [
{ type: 'markdown_fragment', text: '# Review the request\n\n' },
{
type: 'paragraph_input',
output_variable_name: 'response',
default_value: 'Resolved approval notes',
},
],
actions: [
{ id: 'approve', title: 'Approve', button_style: 'primary' },
{ id: 'reject', title: 'Reject', button_style: 'default' },
],
},
expiration_time: Math.floor(Date.now() / 1000) + 3600,
...overrides,
})
const createProfile = (
overrides: Partial<GetAccountProfileResponse> = {},
): GetAccountProfileResponse => ({
id: 'reviewer-account',
name: 'Approval Reviewer',
email: 'reviewer@example.com',
avatar: '',
avatar_url: null,
is_password_set: true,
...overrides,
})
const renderForm = (formToken = 'console-token') => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={client}>
<ConsoleHumanInputForm formToken={formToken} />
</QueryClientProvider>,
)
}
describe('ConsoleHumanInputForm', () => {
beforeEach(() => {
fetchForm.mockReset().mockResolvedValue(createDefinition())
fetchLegacyForm.mockReset().mockRejectedValue({ status: 404 })
submitForm.mockReset().mockResolvedValue({})
submitLegacyForm.mockReset()
fetchProfile.mockReset().mockResolvedValue(createProfile())
logout.mockReset().mockResolvedValue({ result: 'success' })
deployment.basePath = ''
})
afterEach(() => vi.restoreAllMocks())
it('reads and submits the resolved Console form using only the new Console API', async () => {
const user = userEvent.setup()
renderForm()
expect(await screen.findByRole('heading', { name: 'Review the request' })).toBeInTheDocument()
const response = screen.getByRole('textbox', { name: 'Review the request' })
expect(response).toHaveValue('Resolved approval notes')
expect(fetchForm).toHaveBeenCalledWith('console-token')
expect(fetchLegacyForm).not.toHaveBeenCalled()
expect(screen.queryByText('{{#start.title#}}')).not.toBeInTheDocument()
expect(fetchProfile).not.toHaveBeenCalled()
await user.clear(response)
await user.type(response, 'Approved after review')
await user.click(screen.getByRole('button', { name: 'Approve' }))
expect(submitForm).toHaveBeenCalledWith({
params: { form_token: 'console-token' },
body: { inputs: { response: 'Approved after review' }, action: 'approve' },
})
expect(submitLegacyForm).not.toHaveBeenCalled()
expect(await screen.findByText('share.humanInput.thanks')).toBeInTheDocument()
expect(screen.getByText('share.humanInput.recorded')).toBeInTheDocument()
expect(screen.queryByRole('textbox', { name: 'Review the request' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'share.humanInput.switchAccount' }),
).not.toBeInTheDocument()
expect(fetchProfile).not.toHaveBeenCalled()
})
it('keeps edited input after a failed submission and allows retry', async () => {
const user = userEvent.setup()
submitForm.mockRejectedValueOnce(
new Response(JSON.stringify({ code: 'internal_server_error' }), { status: 500 }),
)
renderForm()
const response = await screen.findByRole('textbox', { name: 'Review the request' })
await user.clear(response)
await user.type(response, 'Keep these approval notes')
await user.click(screen.getByRole('button', { name: 'Approve' }))
expect(await screen.findByRole('alert')).toHaveTextContent('share.humanInputV2.unknownError')
expect(response).toHaveValue('Keep these approval notes')
const approve = screen.getByRole('button', { name: 'Approve' })
expect(approve).toBeEnabled()
await user.click(approve)
expect(submitForm).toHaveBeenCalledTimes(2)
expect(submitForm).toHaveBeenLastCalledWith({
params: { form_token: 'console-token' },
body: { inputs: { response: 'Keep these approval notes' }, action: 'approve' },
})
expect(await screen.findByText('share.humanInput.thanks')).toBeInTheDocument()
})
it('maps generated workflow-not-active submission errors without discarding edited input', async () => {
const user = userEvent.setup()
submitForm.mockRejectedValueOnce({
status: 400,
data: { body: { code: 'workflow_not_active' } },
})
renderForm()
const response = await screen.findByRole('textbox', { name: 'Review the request' })
await user.clear(response)
await user.type(response, 'Retained after workflow stops')
await user.click(screen.getByRole('button', { name: 'Approve' }))
expect(await screen.findByRole('alert')).toHaveTextContent('share.humanInputV2.unavailable')
expect(response).toHaveValue('Retained after workflow stops')
expect(screen.getByRole('button', { name: 'Approve' })).toBeEnabled()
})
it('disables every action while submitting to prevent duplicate approvals', async () => {
const user = userEvent.setup()
let resolveSubmission: ((value: Record<string, unknown>) => void) | undefined
const pendingSubmission = new Promise<Record<string, unknown>>((resolve) => {
resolveSubmission = resolve
})
submitForm.mockReturnValue(pendingSubmission)
renderForm()
const approve = await screen.findByRole('button', { name: 'Approve' })
const reject = screen.getByRole('button', { name: 'Reject' })
await user.click(approve)
expect(approve).toHaveAttribute('aria-disabled', 'true')
expect(reject).toHaveAttribute('aria-disabled', 'true')
await user.click(approve)
await user.click(reject)
expect(submitForm).toHaveBeenCalledTimes(1)
await act(async () => {
resolveSubmission?.({})
await pendingSubmission
})
expect(await screen.findByText('share.humanInput.thanks')).toBeInTheDocument()
})
it.each([
{ error: { status: 404 }, name: 'Approval Reviewer', expectedName: 'Approval Reviewer' },
{
error: { data: { body: { code: 'not_found' } } },
name: '',
expectedName: 'reviewer@example.com',
},
{ error: { code: 'not_found' }, name: ' ', expectedName: 'reviewer@example.com' },
])(
'shows account recovery for an unavailable definition: $error',
async ({ error, name, expectedName }) => {
fetchProfile.mockResolvedValue(createProfile({ name }))
fetchForm.mockRejectedValue(error)
renderForm()
expect(await screen.findByText('share.humanInput.unavailableTitle')).toBeInTheDocument()
expect(screen.getByText('share.humanInput.unavailableDescription')).toBeInTheDocument()
expect(
await screen.findByText(
`share.humanInput.currentAccount:${JSON.stringify({ name: expectedName })}`,
),
).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'share.humanInput.switchAccount' })).toBeEnabled()
expect(fetchProfile).toHaveBeenCalledOnce()
expect(screen.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'common.operation.retry' }),
).not.toBeInTheDocument()
expect(submitForm).not.toHaveBeenCalled()
expect(fetchLegacyForm).not.toHaveBeenCalled()
expect(submitLegacyForm).not.toHaveBeenCalled()
},
)
it.each([
[{ status: 500 }, 'share.humanInputV2.unknownError'],
[{ status: 429 }, 'share.humanInput.rateLimitExceeded'],
[{ status: 410, data: { body: { code: 'expired' } } }, 'share.humanInput.expired'],
])('does not offer account recovery for other definition errors: %j', async (error, expected) => {
fetchForm.mockRejectedValue(error)
renderForm()
expect(await screen.findByText(expected)).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'share.humanInput.switchAccount' }),
).not.toBeInTheDocument()
expect(fetchProfile).not.toHaveBeenCalled()
})
it.each(['', '/console'])(
'switches account once while pending and returns to the original form with base path "%s"',
async (basePath) => {
const user = userEvent.setup()
const replace = vi.spyOn(window.location, 'replace').mockImplementation(() => {})
deployment.basePath = basePath
fetchForm.mockRejectedValue({ status: 404 })
let completeLogout:
| ((value: Awaited<ReturnType<typeof consoleClient.logout.post>>) => void)
| undefined
const pendingLogout = new Promise<Awaited<ReturnType<typeof consoleClient.logout.post>>>(
(resolve) => {
completeLogout = resolve
},
)
logout.mockReturnValue(pendingLogout)
const formToken = 'approval/request?待办+1'
renderForm(formToken)
const switchAccount = await screen.findByRole('button', {
name: 'share.humanInput.switchAccount',
})
await user.click(switchAccount)
expect(switchAccount).toHaveAttribute('aria-disabled', 'true')
await user.click(switchAccount)
expect(logout).toHaveBeenCalledOnce()
expect(replace).not.toHaveBeenCalled()
await act(async () => {
completeLogout?.({ result: 'success' })
await pendingLogout
})
const returnPath = `${basePath}/human-input/${encodeURIComponent(formToken)}`
expect(replace).toHaveBeenCalledExactlyOnceWith(
`${basePath}/signin?redirect_url=${encodeURIComponent(returnPath)}`,
)
},
)
it('keeps the unavailable page when switching account fails and allows retry', async () => {
const user = userEvent.setup()
const replace = vi.spyOn(window.location, 'replace').mockImplementation(() => {})
fetchForm.mockRejectedValue({ status: 404 })
logout.mockRejectedValue(new Error('Logout failed'))
renderForm()
const switchAccount = await screen.findByRole('button', {
name: 'share.humanInput.switchAccount',
})
await user.click(switchAccount)
await waitFor(() => expect(switchAccount).not.toHaveAttribute('aria-disabled', 'true'))
expect(screen.getByText('share.humanInput.unavailableTitle')).toBeInTheDocument()
expect(replace).not.toHaveBeenCalled()
await user.click(switchAccount)
await waitFor(() => expect(logout).toHaveBeenCalledTimes(2))
expect(replace).not.toHaveBeenCalled()
})
it('shows the same account recovery if access is lost before submission', async () => {
const user = userEvent.setup()
submitForm.mockRejectedValue(
new Response(JSON.stringify({ code: 'not_found' }), { status: 404 }),
)
renderForm()
await user.click(await screen.findByRole('button', { name: 'Approve' }))
expect(await screen.findByText('share.humanInput.unavailableTitle')).toBeInTheDocument()
expect(
await screen.findByText('share.humanInput.currentAccount:{"name":"Approval Reviewer"}'),
).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'share.humanInput.switchAccount' })).toBeEnabled()
expect(screen.queryByRole('textbox', { name: 'Review the request' })).not.toBeInTheDocument()
expect(submitForm).toHaveBeenCalledOnce()
})
it.each([{ status: 409, code: 'already_submitted' }])(
'shows the complete already-processed status when opening a resolved form: %j',
async (error) => {
fetchForm.mockRejectedValue(error)
renderForm()
expect(await screen.findByText('share.humanInput.completed')).toBeInTheDocument()
expect(screen.getByText('share.humanInput.sorry')).toBeInTheDocument()
expect(
screen.getByText('share.humanInput.submissionID:{"id":"console-token"}'),
).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'common.operation.retry' }),
).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'share.humanInput.switchAccount' }),
).not.toBeInTheDocument()
expect(fetchProfile).not.toHaveBeenCalled()
},
)
it('blocks submission when the form expires before approval', async () => {
const user = userEvent.setup()
submitForm.mockRejectedValue(new Response(JSON.stringify({ code: 'expired' }), { status: 410 }))
renderForm()
await user.click(await screen.findByRole('button', { name: 'Approve' }))
expect(await screen.findByText('share.humanInput.expired')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument()
expect(submitForm).toHaveBeenCalledTimes(1)
})
it('shows the complete already-processed status if another recipient approves before submission', async () => {
const user = userEvent.setup()
submitForm.mockRejectedValue({ status: 409, code: 'already_submitted' })
renderForm()
await user.click(await screen.findByRole('button', { name: 'Approve' }))
expect(await screen.findByText('share.humanInput.completed')).toBeInTheDocument()
expect(screen.getByText('share.humanInput.sorry')).toBeInTheDocument()
expect(
screen.getByText('share.humanInput.submissionID:{"id":"console-token"}'),
).toBeInTheDocument()
expect(screen.queryByRole('textbox', { name: 'Review the request' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.operation.retry' })).not.toBeInTheDocument()
expect(submitForm).toHaveBeenCalledTimes(1)
})
it('allows retry after a temporary definition load failure', async () => {
const user = userEvent.setup()
fetchForm.mockRejectedValueOnce({ status: 503 })
renderForm()
const retry = await screen.findByRole('button', { name: 'common.operation.retry' })
expect(fetchForm).toHaveBeenCalledTimes(1)
await user.click(retry)
expect(await screen.findByRole('textbox', { name: 'Review the request' })).toHaveValue(
'Resolved approval notes',
)
await waitFor(() => expect(fetchForm).toHaveBeenCalledTimes(2))
})
it('blocks approval when Console returns a definition whose deadline has already passed', async () => {
fetchForm.mockResolvedValue(
createDefinition({ expiration_time: Math.floor(Date.now() / 1000) - 60 }),
)
renderForm()
expect(await screen.findByText('share.humanInput.expired')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument()
expect(submitForm).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,63 @@
import type { ConsoleHumanInputV2FormDefinitionResponse } from '@dify/contracts/api/console/form/types.gen'
import type { HumanInputFormDefinition } from '@/features/human-input/form/types'
import { zConsoleHumanInputV2FormDefinitionResponse } from '@dify/contracts/api/console/form/zod.gen'
import { normalizeHumanInputFormInput } from '@/app/components/workflow/nodes/human-input/shared/types'
export const normalizeConsoleFormDefinition = (
response: ConsoleHumanInputV2FormDefinitionResponse,
): HumanInputFormDefinition => {
const { resolved_form: form, expiration_time } =
zConsoleHumanInputV2FormDefinitionResponse.parse(response)
const inputs: HumanInputFormDefinition['inputs'] = []
const resolvedDefaultValues: HumanInputFormDefinition['resolvedDefaultValues'] = {}
const inputNames = new Set<string>()
const content = form.parts.map((part) => {
if (part.type === 'markdown_fragment') return part.text
const name = part.output_variable_name
if (!inputNames.has(name)) {
inputNames.add(name)
switch (part.type) {
case 'paragraph_input':
inputs.push(
normalizeHumanInputFormInput({
type: 'paragraph',
output_variable_name: name,
default:
part.default_value === null
? null
: { type: 'constant', value: part.default_value },
}),
)
if (part.default_value !== null) resolvedDefaultValues[name] = part.default_value
break
case 'select_input':
inputs.push(
normalizeHumanInputFormInput({
type: 'select',
output_variable_name: name,
option_source: { type: 'constant', value: part.options },
}),
)
if (part.default_value !== null) resolvedDefaultValues[name] = part.default_value
break
case 'file_input':
inputs.push(normalizeHumanInputFormInput({ ...part, type: 'file' }))
break
case 'file_list_input':
inputs.push(normalizeHumanInputFormInput({ ...part, type: 'file-list' }))
break
}
}
return `{{#$output.${name}#}}`
})
return {
formContent: content.join(''),
inputs,
resolvedDefaultValues,
actions: form.actions,
expirationTime: expiration_time,
}
}
@@ -0,0 +1,163 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import FormStatusCard from '@/features/human-input/form/form-status-card'
import LoadedFormContent from '@/features/human-input/form/loaded-form-content'
import useDocumentTitle from '@/hooks/use-document-title'
import { consoleQuery } from '@/service/console'
import { useLogout } from '@/service/use-common'
import { basePath } from '@/utils/var'
import { normalizeHumanInputV2Error } from '../public/errors'
import { normalizeConsoleFormDefinition } from './definition'
function UnavailableConsoleForm({ formToken }: { formToken: string }) {
const { t } = useTranslation(['share'])
const { data } = useQuery(userProfileQueryOptions())
const profile = data?.profile
const accountName = profile?.name?.trim() || profile?.email
const returnPath = `${basePath}/human-input/${encodeURIComponent(formToken)}`
const logout = useLogout({
redirectTo: `/signin?redirect_url=${encodeURIComponent(returnPath)}`,
})
return (
<FormStatusCard
iconClassName="i-ri-information-2-fill text-text-accent"
title={t(($) => $['humanInput.unavailableTitle'])}
description={t(($) => $['humanInput.unavailableDescription'])}
>
<div className="flex flex-col items-start gap-3">
{accountName && (
<p className="system-sm-regular wrap-anywhere text-text-tertiary">
{t(($) => $['humanInput.currentAccount'], { name: accountName })}
</p>
)}
<Button loading={logout.isPending} onClick={() => logout.mutate()}>
{t(($) => $['humanInput.switchAccount'])}
</Button>
</div>
</FormStatusCard>
)
}
export default function ConsoleHumanInputForm({ formToken }: { formToken: string }) {
const { t } = useTranslation(['workflow', 'share', 'common'])
useDocumentTitle(t(($) => $['blocks.human-input'], { ns: 'workflow' }))
const [now, setNow] = useState(Date.now)
const form = useQuery(
consoleQuery.form.humanInput.v2.byFormToken.get.queryOptions({
input: { params: { form_token: formToken } },
context: { silent: true },
select: normalizeConsoleFormDefinition,
retry: false,
staleTime: 0,
gcTime: 0,
refetchOnWindowFocus: false,
}),
)
const expiresAt =
form.data?.expirationTime === undefined ? undefined : form.data.expirationTime * 1000
useEffect(() => {
if (expiresAt === undefined || expiresAt <= now) return
const timer = window.setTimeout(
() => setNow(Date.now()),
Math.min(Math.max(0, expiresAt - Date.now()), 2_147_483_647),
)
return () => window.clearTimeout(timer)
}, [expiresAt, now])
const submission = useMutation(
consoleQuery.form.humanInput.v2.byFormToken.post.mutationOptions({
context: { silent: true },
}),
)
const errorKind =
expiresAt !== undefined && expiresAt <= now
? 'form-expired'
: normalizeHumanInputV2Error(submission.error ?? form.error).category
const terminal = ['form-expired', 'already-submitted', 'not-found'].includes(errorKind)
const errorText =
errorKind === 'form-expired'
? t(($) => $['humanInput.expired'], { ns: 'share' })
: errorKind === 'already-submitted'
? t(($) => $['humanInput.completed'], { ns: 'share' })
: errorKind === 'form-rate-limit'
? t(($) => $['humanInput.rateLimitExceeded'], { ns: 'share' })
: errorKind === 'unavailable'
? t(($) => $['humanInputV2.unavailable'], { ns: 'share' })
: t(($) => $['humanInputV2.unknownError'], { ns: 'share' })
if (form.isPending) return <LoadingPlaceholder className="h-full" />
if (submission.isSuccess) {
return (
<FormStatusCard
iconClassName="i-ri-checkbox-circle-fill text-text-success"
title={t(($) => $['humanInput.thanks'], { ns: 'share' })}
subtitle={t(($) => $['humanInput.recorded'], { ns: 'share' })}
submissionID={formToken}
/>
)
}
if (errorKind === 'already-submitted') {
return (
<FormStatusCard
iconClassName="i-ri-information-2-fill text-text-accent"
title={t(($) => $['humanInput.sorry'], { ns: 'share' })}
subtitle={errorText}
submissionID={formToken}
/>
)
}
if (errorKind === 'not-found') return <UnavailableConsoleForm formToken={formToken} />
if (form.isError || terminal) {
return (
<FormStatusCard
iconClassName="i-ri-information-2-fill text-text-accent"
title={errorText}
subtitle={
!terminal && (
<Button onClick={() => form.refetch()} loading={form.isFetching}>
{t(($) => $['operation.retry'], { ns: 'common' })}
</Button>
)
}
/>
)
}
return (
<div className="h-full">
<LoadedFormContent
definition={form.data}
isSubmitting={submission.isPending}
verificationContent={
submission.isError ? (
<p role="alert" className="system-sm-regular text-text-destructive">
{errorText}
</p>
) : undefined
}
onSubmit={(inputs, action) => {
if (expiresAt !== undefined && expiresAt <= Date.now()) {
setNow(Date.now())
return
}
return new Promise<void>((resolve) => {
submission.mutate(
{ params: { form_token: formToken }, body: { inputs, action } },
{ onSettled: () => resolve() },
)
})
}}
/>
</div>
)
}
@@ -0,0 +1,14 @@
export const resolveConsoleHumanInputFormURL = (backstageURL: string, basePath = ''): string => {
try {
const url = new URL(backstageURL, 'http://localhost')
if (url.protocol !== 'http:' && url.protocol !== 'https:') return backstageURL
const match = url.pathname.match(/(?:^|\/)form\/([^/]+)\/?$/)
if (!match?.[1]) return backstageURL
const token = encodeURIComponent(decodeURIComponent(match[1]))
return `${basePath.replace(/\/$/, '')}/human-input/${token}`
} catch {
return backstageURL
}
}