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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(web): scope workflow editing sessions to dialog popups (#43519)
yyhc21f5ce07065
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex c01d623d60f..f3e076f6cc4 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -3021,14 +3021,6 @@"count": 1}},- "web/app/components/workflow/nodes/http/panel.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- }- },"web/app/components/workflow/nodes/http/use-config.ts": {"eslint-react/set-state-in-effect": {"count": 1@@ -3236,11 +3228,6 @@"count": 1}},- "web/app/components/workflow/nodes/llm/components/structure-output.tsx": {- "typescript/no-explicit-any": {- "count": 2- }- },"web/app/components/workflow/nodes/llm/use-config.ts": {"eslint-react/set-state-in-effect": {"count": 1diff --git a/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsxindex f5d3bb677b7..9c2f5556a70 100644--- a/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx@@ -8,7 +8,6 @@ import Panel from '../panel'import { AuthorizationType, BodyPayloadValueType, BodyType, Method } from '../types'const mockUseConfig = vi.hoisted(() => vi.fn())-const mockCurlPanel = vi.hoisted(() => vi.fn())const mockApiInput = vi.hoisted(() => vi.fn())const mockKeyValue = vi.hoisted(() => vi.fn())const mockEditBody = vi.hoisted(() => vi.fn())@@ -47,18 +46,6 @@ vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', ()default: () => ({ availableVars: [], availableNodesWithParent: [] }),}))-vi.mock('../components/curl-panel', () => ({- __esModule: true,- default: (props: {- nodeId: string- onHide: () => void- handleCurlImport: (node: HttpNodeType) => void- }) => {- mockCurlPanel(props)- return <div data-testid="curl-panel">{props.nodeId}</div>- },-}))-vi.mock('../components/api-input', () => ({__esModule: true,default: (props: ApiInputProps) => {@@ -161,8 +148,6 @@ describe('http/panel', () => {const setBody = vi.fn()const setAuthorization = vi.fn()const setTimeout = vi.fn()- const showCurlPanel = vi.fn()- const hideCurlPanel = vi.fn()const handleCurlImport = vi.fn()const createConfigResult = (overrides: Record<string, unknown> = {}) => ({@@ -182,9 +167,6 @@ describe('http/panel', () => {setBody,setAuthorization,setTimeout,- isShowCurlPanel: false,- showCurlPanel,- hideCurlPanel,handleCurlImport,handleSSLVerifyChange: vi.fn(),...overrides,@@ -214,7 +196,12 @@ describe('http/panel', () => {await user.click(screen.getAllByRole('button', { name: 'emit-key-value-add' })[1]!)await user.click(screen.getByRole('button', { name: 'emit-body-change' }))await user.click(screen.getByRole('button', { name: 'emit-timeout-change' }))- await user.click(screen.getByText('workflowIntegrations.nodes.http.curl.title'))+ await user.click(+ screen.getByRole('button', { name: 'workflowIntegrations.nodes.http.curl.title' }),+ )+ expect(+ screen.getByRole('dialog', { name: 'workflowIntegrations.nodes.http.curl.title' }),+ ).toBeInTheDocument()expect(handleMethodChange).toHaveBeenCalledWith(Method.post)expect(handleUrlChange).toHaveBeenCalledWith('https://changed.example.com')@@ -227,7 +214,6 @@ describe('http/panel', () => {data: [{ type: 'text', value: '{"hello":"world"}' }],})expect(setTimeout).toHaveBeenCalledWith(expect.objectContaining({ connect: 9 }))- expect(showCurlPanel).toHaveBeenCalledTimes(1)expect(mockApiInput).toHaveBeenCalledWith(expect.objectContaining({method: Method.get,@@ -247,23 +233,18 @@ describe('http/panel', () => {})it('disables authorization and hides the curl panel when read-only', () => {- mockUseConfig.mockReturnValueOnce(- createConfigResult({- isShowCurlPanel: true,- }),- )-const { rerender } = render(<Panel id="http-node" data={createData()} panelProps={panelProps} />,)expect(screen.getByRole('button', { name: /authorization.authorization/ })).toBeEnabled()- expect(screen.getByTestId('curl-panel')).toHaveTextContent('http-node')+ expect(+ screen.getByRole('button', { name: 'workflowIntegrations.nodes.http.curl.title' }),+ ).toBeEnabled()mockUseConfig.mockReturnValueOnce(createConfigResult({readOnly: true,- isShowCurlPanel: true,}),)@@ -275,7 +256,9 @@ describe('http/panel', () => {expect(screen.getByText('workflowIntegrations.nodes.http.authorization.authorization'),).toBeInTheDocument()- expect(screen.queryByTestId('curl-panel')).not.toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: 'workflowIntegrations.nodes.http.curl.title' }),+ ).not.toBeInTheDocument()expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')})})diff --git a/web/app/components/workflow/nodes/http/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/http/__tests__/use-config.spec.tsindex 3df9aae5936..b4ceff3f05c 100644--- a/web/app/components/workflow/nodes/http/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/http/__tests__/use-config.spec.ts@@ -5,6 +5,7 @@ import { useStore } from '@/app/components/workflow/store'import { BlockEnum, VarType } from '@/app/components/workflow/types'import { useNodesReadOnly } from '../../../hooks/use-workflow'import useVarList from '../../_base/hooks/use-var-list'+import { parseCurl } from '../components/curl-parser'import useKeyValueList from '../hooks/use-key-value-list'import { APIType, AuthorizationType, BodyPayloadValueType, BodyType, Method } from '../types'import useConfig from '../use-config'@@ -208,6 +209,36 @@ describe('http/use-config', () => {})})+ it.each([+ [+ 'a JSON body',+ `curl --json '{"ok":true}' https://example.com/items`,+ BodyType.json,+ [{ type: BodyPayloadValueType.text, value: '{"ok":true}' }],+ ],+ [+ 'form fields',+ 'curl --form "name=openai" https://example.com/upload',+ BodyType.formData,+ [expect.objectContaining({ key: 'name', value: 'openai' })],+ ],+ ])(+ 'stores %s from a parsed curl command as an editable body payload',+ async (_label, command, type, data) => {+ const { result } = renderHook(() => useConfig('http-node', currentInputs))+ await waitFor(() => expect(result.current.isDataReady).toBe(true))+ mockSetInputs.mockClear()+ const parsed = parseCurl(command)+ expect(parsed.error).toBeNull()++ act(() => result.current.handleCurlImport(parsed.node!))++ expect(mockSetInputs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ body: { type, data } }),+ )+ },+ )+it('updates request fields, authorization state, curl imports, and ssl verification', async () => {const { result } = renderHook(() => useConfig('http-node', currentInputs))@@ -234,17 +265,19 @@ describe('http/use-config', () => {},})result.current.setTimeout({ connect: 30, read: 40, write: 50 })- result.current.showCurlPanel()})- expect(result.current.isShowCurlPanel).toBe(true)-act(() => {- result.current.hideCurlPanel()result.current.handleCurlImport(createPayload({method: Method.patch,url: 'https://imported.example.com',+ authorization: {+ type: AuthorizationType.apiKey,+ config: { type: APIType.bearer, api_key: 'imported' },+ },+ timeout: { connect: 99, read: 99, write: 99 },+ ssl_verify: false,headers: 'authorization:Bearer imported',params: 'debug:true',body: {@@ -256,7 +289,6 @@ describe('http/use-config', () => {result.current.handleSSLVerifyChange(false)})- expect(result.current.isShowCurlPanel).toBe(false)expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ method: Method.delete }))expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ url: 'https://changed.example.com' }),@@ -284,6 +316,9 @@ describe('http/use-config', () => {expect.objectContaining({method: Method.patch,url: 'https://imported.example.com',+ authorization: currentInputs.authorization,+ timeout: currentInputs.timeout,+ ssl_verify: currentInputs.ssl_verify,headers: 'authorization:Bearer imported',params: 'debug:true',body: {diff --git a/web/app/components/workflow/nodes/http/components/__tests__/curl-import-dialog.browser.spec.tsx b/web/app/components/workflow/nodes/http/components/__tests__/curl-import-dialog.browser.spec.tsxnew file mode 100644index 00000000000..3d534e10834--- /dev/null+++ b/web/app/components/workflow/nodes/http/components/__tests__/curl-import-dialog.browser.spec.tsx@@ -0,0 +1,50 @@+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { CurlImportDialog } from '../curl-import-dialog'++afterEach(() => vi.unstubAllGlobals())++it('keeps Enter as a newline and restores focus with a fresh draft after Cancel and Escape', async () => {+ vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false)+ const onImport = vi.fn()+ const screen = await render(<CurlImportDialog onImport={onImport} readOnly={false} />)+ const trigger = screen.getByRole('button', { name: 'workflowIntegrations.nodes.http.curl.title' })+ const dialog = screen.getByRole('dialog', { name: 'workflowIntegrations.nodes.http.curl.title' })+ const textarea = screen.getByRole('textbox', {+ name: 'workflowIntegrations.nodes.http.curl.title',+ })+ for (const dismissal of ['Cancel', 'Escape']) {+ await trigger.click()+ await expect.element(textarea).toHaveFocus()+ await expect.element(textarea).toHaveValue('')+ await textarea.fill('curl https://example.com')+ await userEvent.keyboard('{Enter}')+ await expect.element(textarea).toHaveValue('curl https://example.com\n')+ await expect.element(dialog).toBeVisible()+ expect(onImport).not.toHaveBeenCalled()+ if (dismissal === 'Cancel')+ await screen.getByRole('button', { name: 'common.operation.cancel' }).click()+ else await userEvent.keyboard('{Escape}')+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ }+})++it('returns focus to the trigger after a successful import', async () => {+ vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false)+ const onImport = vi.fn()+ const screen = await render(<CurlImportDialog onImport={onImport} readOnly={false} />)+ const trigger = screen.getByRole('button', { name: 'workflowIntegrations.nodes.http.curl.title' })+ await trigger.click()+ const dialog = screen.getByRole('dialog', { name: 'workflowIntegrations.nodes.http.curl.title' })+ await screen+ .getByRole('textbox', { name: 'workflowIntegrations.nodes.http.curl.title' })+ .fill('curl https://example.com')+ await screen.getByRole('button', { name: 'common.operation.save' }).click()++ expect(onImport).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ method: 'get', url: 'https://example.com' }),+ )+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+})diff --git a/web/app/components/workflow/nodes/http/components/__tests__/curl-panel.spec.tsx b/web/app/components/workflow/nodes/http/components/__tests__/curl-import-dialog.spec.tsxsimilarity index 53%rename from web/app/components/workflow/nodes/http/components/__tests__/curl-panel.spec.tsxrename to web/app/components/workflow/nodes/http/components/__tests__/curl-import-dialog.spec.tsxindex fecea7190e9..fdf246990f4 100644--- a/web/app/components/workflow/nodes/http/components/__tests__/curl-panel.spec.tsx+++ b/web/app/components/workflow/nodes/http/components/__tests__/curl-import-dialog.spec.tsx@@ -1,33 +1,21 @@-import { render, screen } from '@testing-library/react'+import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { toast } from '@/app/notifications'import { BodyPayloadValueType, BodyType } from '../../types'-import CurlPanel from '../curl-panel'+import { CurlImportDialog } from '../curl-import-dialog'import * as curlParser from '../curl-parser'-const { mockHandleNodeSelect, mockToastError } = vi.hoisted(() => ({- mockHandleNodeSelect: vi.fn(),+const { mockToastError } = vi.hoisted(() => ({mockToastError: vi.fn(),}))-vi.mock('../../../../hooks/use-nodes-interactions', async (importOriginal) => {- const actual = await importOriginal<typeof import('../../../../hooks/use-nodes-interactions')>()-- return {- ...actual,- useNodesInteractions: () => ({- handleNodeSelect: mockHandleNodeSelect,- }),- }-})-vi.mock('@/app/notifications', () => ({toast: {error: mockToastError,},}))-describe('curl-panel', () => {+describe('CurlImportDialog', () => {beforeEach(() => {vi.clearAllMocks()})@@ -103,61 +91,72 @@ describe('curl-panel', () => {})})- describe('component actions', () => {- it('should import a parsed curl node and reselect the node after saving', async () => {- const user = userEvent.setup()- const onHide = vi.fn()- const handleCurlImport = vi.fn()-- render(- <CurlPanel nodeId="node-1" isShow onHide={onHide} handleCurlImport={handleCurlImport} />,- )+ describe('dialog sessions', () => {+ const triggerName = 'workflowIntegrations.nodes.http.curl.title'+ it('imports the parsed request and closes', async () => {+ const user = userEvent.setup()+ const onImport = vi.fn()+ render(<CurlImportDialog readOnly={false} onImport={onImport} />)+ await user.click(screen.getByRole('button', { name: triggerName }))await user.type(screen.getByRole('textbox'), 'curl https://example.com')await user.click(screen.getByRole('button', { name: 'common.operation.save' }))- expect(onHide).toHaveBeenCalledTimes(1)- expect(handleCurlImport).toHaveBeenCalledWith(- expect.objectContaining({- method: 'get',- url: 'https://example.com',- }),+ expect(onImport).toHaveBeenCalledWith(+ expect.objectContaining({ method: 'get', url: 'https://example.com' }),)- expect(mockHandleNodeSelect).toHaveBeenNthCalledWith(1, 'node-1', true)+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())})- it('should notify the user when the curl command is invalid', async () => {+ it.each(['Cancel', 'Escape'])(+ 'discards the draft after %s and opens a fresh form',+ async (dismissal) => {+ const user = userEvent.setup()+ const onImport = vi.fn()+ render(<CurlImportDialog readOnly={false} onImport={onImport} />)+ const trigger = screen.getByRole('button', { name: triggerName })+ await user.click(trigger)+ await user.type(screen.getByRole('textbox'), 'curl https://example.com')+ if (dismissal === 'Cancel')+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ else await user.keyboard('{Escape}')+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await user.click(trigger)+ expect(screen.getByRole('textbox')).toHaveValue('')+ expect(onImport).not.toHaveBeenCalled()+ },+ )++ it('keeps invalid input available for correction without importing', async () => {const user = userEvent.setup()-- render(<CurlPanel nodeId="node-1" isShow onHide={vi.fn()} handleCurlImport={vi.fn()} />)-+ const onImport = vi.fn()+ render(<CurlImportDialog readOnly={false} onImport={onImport} />)+ await user.click(screen.getByRole('button', { name: triggerName }))await user.type(screen.getByRole('textbox'), 'invalid')await user.click(screen.getByRole('button', { name: 'common.operation.save' }))-expect(vi.mocked(toast.error)).toHaveBeenCalledWith(expect.stringContaining('Invalid cURL command'),)+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(screen.getByRole('textbox')).toHaveValue('invalid')+ expect(onImport).not.toHaveBeenCalled()})- it('should keep the panel open when parsing returns no node and no error', async () => {+ it('offers no editor while read-only and ends an open session when permission changes', async () => {const user = userEvent.setup()- const onHide = vi.fn()- const handleCurlImport = vi.fn()- vi.spyOn(curlParser, 'parseCurl').mockReturnValueOnce({- node: null,- error: null,- })-- render(- <CurlPanel nodeId="node-1" isShow onHide={onHide} handleCurlImport={handleCurlImport} />,- )-- await user.click(screen.getByRole('button', { name: 'common.operation.save' }))-- expect(onHide).not.toHaveBeenCalled()- expect(handleCurlImport).not.toHaveBeenCalled()- expect(mockHandleNodeSelect).not.toHaveBeenCalled()- expect(vi.mocked(toast.error)).not.toHaveBeenCalled()+ const onImport = vi.fn()+ const { rerender } = render(<CurlImportDialog readOnly onImport={onImport} />)+ expect(screen.getByText(triggerName)).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: triggerName })).not.toBeInTheDocument()+ rerender(<CurlImportDialog readOnly={false} onImport={onImport} />)+ await user.click(screen.getByRole('button', { name: triggerName }))+ await user.type(screen.getByRole('textbox'), 'curl https://example.com')+ rerender(<CurlImportDialog readOnly onImport={onImport} />)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ rerender(<CurlImportDialog readOnly={false} onImport={onImport} />)+ await user.click(screen.getByRole('button', { name: triggerName }))+ expect(screen.getByRole('textbox')).toHaveValue('')+ expect(onImport).not.toHaveBeenCalled()})})})diff --git a/web/app/components/workflow/nodes/http/components/curl-import-dialog.tsx b/web/app/components/workflow/nodes/http/components/curl-import-dialog.tsxnew file mode 100644index 00000000000..50791dd96ea--- /dev/null+++ b/web/app/components/workflow/nodes/http/components/curl-import-dialog.tsx@@ -0,0 +1,89 @@+'use client'++import type { DialogActions } from '@langgenius/dify-ui/dialog'+import type { HttpNodeType } from '../types'+import { Button } from '@langgenius/dify-ui/button'+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogTitle,+ DialogTrigger,+} from '@langgenius/dify-ui/dialog'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from '@/app/notifications'+import { parseCurl } from './curl-parser'++type CurlImportDialogProps = {+ readOnly: boolean+ onImport: (node: HttpNodeType) => void+}++function CurlImportForm({ onImport }: Pick<CurlImportDialogProps, 'onImport'>) {+ const { t } = useTranslation(['common', 'workflowIntegrations'])++ return (+ <form+ onSubmit={(event) => {+ event.preventDefault()+ const command = new FormData(event.currentTarget).get('curl')+ const result = parseCurl(typeof command === 'string' ? command : '')+ if (result.error === null) onImport(result.node)+ else toast.error(result.error)+ }}+ >+ <Textarea+ name="curl"+ aria-label={t(($) => $['nodes.http.curl.title'], { ns: 'workflowIntegrations' })}+ className="my-3 h-40 w-full grow"+ placeholder={t(($) => $['nodes.http.curl.placeholder'], { ns: 'workflowIntegrations' })}+ />+ <div className="mt-4 flex justify-end space-x-2">+ <DialogClose render={<Button className="w-23.75!" />}>+ {t(($) => $['operation.cancel'], { ns: 'common' })}+ </DialogClose>+ <Button type="submit" className="w-23.75!" variant="primary">+ {t(($) => $['operation.save'], { ns: 'common' })}+ </Button>+ </div>+ </form>+ )+}++export function CurlImportDialog({ readOnly, onImport }: CurlImportDialogProps) {+ const actionsRef = useRef<DialogActions>(null)+ const { t } = useTranslation(['workflowIntegrations'])+ const label = (+ <span className="text-xs font-medium text-text-tertiary">+ {t(($) => $['nodes.http.curl.title'], { ns: 'workflowIntegrations' })}+ </span>+ )++ if (readOnly)+ return <div className="flex h-6 items-center space-x-1 rounded-md px-2">{label}</div>++ const handleImport = (node: HttpNodeType) => {+ onImport(node)+ actionsRef.current?.close()+ }++ return (+ <Dialog actionsRef={actionsRef}>+ <DialogTrigger className="flex h-6 cursor-pointer items-center space-x-1 rounded-md px-2 hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden">+ <span+ aria-hidden+ className="i-custom-vender-line-files-file-arrow-01 size-3 text-text-tertiary"+ />+ {label}+ </DialogTrigger>+ <DialogContent className="w-100! max-w-100! overflow-hidden! border-none p-4! text-left align-middle">+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {t(($) => $['nodes.http.curl.title'], { ns: 'workflowIntegrations' })}+ </DialogTitle>+ <CurlImportForm onImport={handleImport} />+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/app/components/workflow/nodes/http/components/curl-panel.tsx b/web/app/components/workflow/nodes/http/components/curl-panel.tsxdeleted file mode 100644index f4648c80f55..00000000000--- a/web/app/components/workflow/nodes/http/components/curl-panel.tsx+++ /dev/null@@ -1,80 +0,0 @@-'use client'-import type { FC } from 'react'-import type { HttpNodeType } from '../types'-import { Button } from '@langgenius/dify-ui/button'-import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'-import { Textarea } from '@langgenius/dify-ui/textarea'-import * as React from 'react'-import { useCallback, useState } from 'react'-import { useTranslation } from 'react-i18next'-import { toast } from '@/app/notifications'-import { useNodesInteractions } from '../../../hooks/use-nodes-interactions'-import { parseCurl } from './curl-parser'--type Props = Readonly<{- nodeId: string- isShow: boolean- onHide: () => void- handleCurlImport: (node: HttpNodeType) => void-}>--const CurlPanel: FC<Props> = ({ nodeId, isShow, onHide, handleCurlImport }) => {- const [inputString, setInputString] = useState('')- const { handleNodeSelect } = useNodesInteractions()- const { t } = useTranslation(['common', 'workflowIntegrations'])-- const handleSave = useCallback(() => {- const { node, error } = parseCurl(inputString)- if (error) {- toast.error(error)- return- }- if (!node) return-- onHide()- handleCurlImport(node)- // Close the panel then open it again to make the panel re-render- handleNodeSelect(nodeId, true)- setTimeout(() => {- handleNodeSelect(nodeId)- }, 0)- }, [onHide, nodeId, inputString, handleNodeSelect, handleCurlImport])-- return (- <Dialog- open={isShow}- onOpenChange={(open) => {- if (!open) onHide()- }}- >- <DialogContent className="w-100! max-w-100! overflow-hidden! border-none p-4! text-left align-middle">- <DialogTitle className="title-2xl-semi-bold text-text-primary">- {t(($) => $['nodes.http.curl.title'], { ns: 'workflowIntegrations' })}- </DialogTitle>-- <div>- <Textarea- aria-label={t(($) => $['nodes.http.curl.title'], { ns: 'workflowIntegrations' })}- value={inputString}- className="my-3 h-40 w-full grow"- onValueChange={(value) => setInputString(value)}- placeholder={t(($) => $['nodes.http.curl.placeholder'], {- ns: 'workflowIntegrations',- })!}- />- </div>- <div className="mt-4 flex justify-end space-x-2">- <Button className="w-23.75!" onClick={onHide}>- {t(($) => $['operation.cancel'], { ns: 'common' })}- </Button>- <Button className="w-23.75!" variant="primary" onClick={handleSave}>- {' '}- {t(($) => $['operation.save'], { ns: 'common' })}- </Button>- </div>- </DialogContent>- </Dialog>- )-}--export default React.memo(CurlPanel)diff --git a/web/app/components/workflow/nodes/http/components/curl-parser.ts b/web/app/components/workflow/nodes/http/components/curl-parser.tsindex b349c510b4f..ea22026c3f1 100644--- a/web/app/components/workflow/nodes/http/components/curl-parser.ts+++ b/web/app/components/workflow/nodes/http/components/curl-parser.ts@@ -157,7 +157,7 @@ const handleCurlArg = (export const parseCurl = (curlCommand: string,-): { node: HttpNodeType | null; error: string | null } => {+): { node: HttpNodeType; error: null } | { node: null; error: string } => {if (!curlCommand.trim().toLowerCase().startsWith('curl'))return { node: null, error: 'Invalid cURL command. Command must start with "curl".' }diff --git a/web/app/components/workflow/nodes/http/panel.tsx b/web/app/components/workflow/nodes/http/panel.tsxindex 567746d4d6c..9042d67979c 100644--- a/web/app/components/workflow/nodes/http/panel.tsx+++ b/web/app/components/workflow/nodes/http/panel.tsx@@ -1,7 +1,6 @@import type { FC } from 'react'import type { HttpNodeType } from './types'import type { NodePanelProps } from '@/app/components/workflow/types'-import { cn } from '@langgenius/dify-ui/cn'import { Switch } from '@langgenius/dify-ui/switch'import { memo } from 'react'import { useTranslation } from 'react-i18next'@@ -10,7 +9,7 @@ import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/compoimport Split from '@/app/components/workflow/nodes/_base/components/split'import ApiInput from './components/api-input'import { AuthorizationDialog } from './components/authorization'-import CurlPanel from './components/curl-panel'+import { CurlImportDialog } from './components/curl-import-dialog'import EditBody from './components/edit-body'import KeyValue from './components/key-value'import Timeout from './components/timeout'@@ -36,9 +35,6 @@ const Panel: FC<NodePanelProps<HttpNodeType>> = ({ id, data }) => {setBody,setAuthorization,setTimeout,- isShowCurlPanel,- showCurlPanel,- hideCurlPanel,handleCurlImport,handleSSLVerifyChange,} = useConfig(id, data)@@ -59,23 +55,7 @@ const Panel: FC<NodePanelProps<HttpNodeType>> = ({ id, data }) => {onChange={setAuthorization}readOnly={readOnly}/>- <div- onClick={showCurlPanel}- className={cn(- !readOnly && 'cursor-pointer hover:bg-state-base-hover',- 'flex h-6 items-center space-x-1 rounded-md px-2',- )}- >- {!readOnly && (- <span- aria-hidden- className="i-custom-vender-line-files-file-arrow-01 size-3 text-text-tertiary"- />- )}- <div className="text-xs font-medium text-text-tertiary">- {t(($) => $[`${i18nPrefix}.curl.title`], { ns: 'workflowIntegrations' })}- </div>- </div>+ <CurlImportDialog readOnly={readOnly} onImport={handleCurlImport} /></div>}>@@ -161,9 +141,6 @@ const Panel: FC<NodePanelProps<HttpNodeType>> = ({ id, data }) => {</></OutputVars></div>- {isShowCurlPanel && !readOnly && (- <CurlPanel nodeId={id} isShow onHide={hideCurlPanel} handleCurlImport={handleCurlImport} />- )}</div>)}diff --git a/web/app/components/workflow/nodes/http/use-config.ts b/web/app/components/workflow/nodes/http/use-config.tsindex 61b29bf5c2b..2ab85b05a09 100644--- a/web/app/components/workflow/nodes/http/use-config.ts+++ b/web/app/components/workflow/nodes/http/use-config.ts@@ -11,6 +11,19 @@ import useKeyValueList from './hooks/use-key-value-list'import { BodyType } from './types'import { transformToBodyPayload } from './utils'+const keyValueBodyTypes: readonly BodyType[] = [BodyType.formData, BodyType.xWwwFormUrlencoded]++// Stored and imported bodies may still carry the legacy string form of their data.+const normalizeBody = (body: Body): Body => {+ if (typeof body.data === 'string') {+ return {+ ...body,+ data: transformToBodyPayload(body.data, keyValueBodyTypes.includes(body.type)),+ }+ }+ return body.data ? body : { ...body, data: [] }+}+const useConfig = (id: string, payload: HttpNodeType) => {const { nodesReadOnly: readOnly } = useNodesReadOnly()@@ -32,21 +45,7 @@ const useConfig = (id: string, payload: HttpNodeType) => {...defaultConfig,...inputs,}- const bodyData = newInputs.body.data- if (typeof bodyData === 'string') {- newInputs.body = {- ...newInputs.body,- data: transformToBodyPayload(- bodyData,- [BodyType.formData, BodyType.xWwwFormUrlencoded].includes(newInputs.body.type),- ),- }- } else if (!bodyData) {- newInputs.body = {- ...newInputs.body,- data: [],- }- }+ newInputs.body = normalizeBody(newInputs.body)setInputs(newInputs)setIsDataReady(true)@@ -137,9 +136,6 @@ const useConfig = (id: string, payload: HttpNodeType) => {return textVariableTypes.includes(varPayload.type)}, [])- // curl import panel- const [isShowCurlPanel, setIsShowCurlPanel] = useState(false)-const handleCurlImport = useCallback((newNode: HttpNodeType) => {const newInputs = produce(inputs, (draft: HttpNodeType) => {@@ -147,7 +143,7 @@ const useConfig = (id: string, payload: HttpNodeType) => {draft.url = newNode.urldraft.headers = newNode.headersdraft.params = newNode.params- draft.body = newNode.body+ draft.body = normalizeBody(newNode.body)})setInputs(newInputs)},@@ -193,9 +189,6 @@ const useConfig = (id: string, payload: HttpNodeType) => {setAuthorization,setTimeout,// curl import- isShowCurlPanel,- showCurlPanel: () => setIsShowCurlPanel(true),- hideCurlPanel: () => setIsShowCurlPanel(false),handleCurlImport,}}diff --git a/web/app/components/workflow/nodes/llm/components/__tests__/panel-output-section.spec.tsx b/web/app/components/workflow/nodes/llm/components/__tests__/panel-output-section.spec.tsxindex 028bcd5c918..7ddd1aec12b 100644--- a/web/app/components/workflow/nodes/llm/components/__tests__/panel-output-section.spec.tsx+++ b/web/app/components/workflow/nodes/llm/components/__tests__/panel-output-section.spec.tsx@@ -35,6 +35,7 @@ vi.mock('../structure-output', () => ({__esModule: true,StructureOutput: (props: {className?: string+ readOnly: booleanvalue?: StructuredOutputonChange: (value: StructuredOutput) => void}) => {@@ -90,10 +91,10 @@ describe('llm/panel-output-section', () => {expect(screen.queryByTestId('structure-output')).not.toBeInTheDocument()})- it('renders the structured output editor when structured output is enabled', () => {+ it('passes the read-only permission to configured output', () => {render(<PanelOutputSection- readOnly={false}+ readOnly={true}inputs={createInputs({structured_output_enabled: true,structured_output: {@@ -113,7 +114,7 @@ describe('llm/panel-output-section', () => {)expect(screen.getByTestId('structure-output')).toBeInTheDocument()- expect(mockStructureOutput).toHaveBeenCalled()+ expect(mockStructureOutput).toHaveBeenCalledWith(expect.objectContaining({ readOnly: true }))})it('opens the model warning with the keyboard without changing structured output', async () => {const user = userEvent.setup()diff --git a/web/app/components/workflow/nodes/llm/components/__tests__/structure-output.browser.spec.tsx b/web/app/components/workflow/nodes/llm/components/__tests__/structure-output.browser.spec.tsxnew file mode 100644index 00000000000..e80237b08dd--- /dev/null+++ b/web/app/components/workflow/nodes/llm/components/__tests__/structure-output.browser.spec.tsx@@ -0,0 +1,135 @@+import type { StructuredOutput } from '../../types'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { useState } from 'react'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { consoleQuery } from '@/service/console'+import { commonQueryKeys } from '@/service/use-common'+import { Type } from '../../types'+import { StructureOutput } from '../structure-output'++vi.mock('@monaco-editor/react', () => {+ function Editor({+ value,+ onChange,+ options,+ }: {+ value?: string+ onChange?: (value: string) => void+ options?: { readOnly?: boolean }+ }) {+ return (+ <textarea+ aria-label="JSON schema editor"+ value={value}+ readOnly={options?.readOnly}+ onChange={(event) => onChange?.(event.target.value)}+ />+ )+ }+ return {+ Editor,+ default: Editor,+ DiffEditor: Editor,+ useMonaco: () => null,+ loader: { config: vi.fn() },+ }+})++const emptySchema = {+ type: Type.object,+ properties: {},+ required: [],+ additionalProperties: false as const,+}+const namedSchema = {+ ...emptySchema,+ properties: { name: { type: Type.string } },+ required: ['name'],+}++function StructuredOutputFixture() {+ const [value, setValue] = useState<StructuredOutput>({ schema: emptySchema })+ return <StructureOutput value={value} onChange={setValue} readOnly={false} />+}++function renderOutput() {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ })+ queryClient.setQueryData(+ consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({+ input: { params: { model_type: ModelTypeEnum.textGeneration } },+ }).queryKey,+ { data: [] },+ )+ queryClient.setQueryData(commonQueryKeys.defaultModel(ModelTypeEnum.textGeneration), {+ data: null,+ })+ return render(+ <QueryClientProvider client={queryClient}>+ <StructuredOutputFixture />+ </QueryClientProvider>,+ )+}++beforeEach(() => vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false))+afterEach(() => vi.unstubAllGlobals())++it.each(['configure', 'notConfiguredTip'])(+ 'returns focus to the %s trigger and starts a fresh schema session',+ async (entrypoint) => {+ const screen = await renderOutput()+ const trigger = screen.getByRole('button', { name: `app.structOutput.${entrypoint}` })+ const dialog = screen.getByRole('dialog', { name: 'workflowModels.nodes.llm.jsonSchema.title' })+ await trigger.click()+ await expect.element(dialog).toBeVisible()+ const visualTab = screen.getByRole('tab', { name: 'Visual Editor' })+ const jsonTab = screen.getByRole('tab', { name: 'JSON Schema' })+ await expect.element(visualTab).toHaveAttribute('aria-selected', 'true')+ await jsonTab.click()+ await screen.getByRole('textbox', { name: 'JSON schema editor' }).fill('unfinished draft')+ if (entrypoint === 'configure')+ await screen.getByRole('button', { name: 'common.operation.cancel' }).click()+ else await userEvent.keyboard('{Escape}')+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()++ await trigger.click()+ await expect.element(visualTab).toHaveAttribute('aria-selected', 'true')+ await jsonTab.click()+ await expect+ .element(screen.getByRole('textbox', { name: 'JSON schema editor' }))+ .toHaveValue(JSON.stringify(emptySchema, null, 2))+ await screen.getByRole('button', { name: 'common.operation.save' }).click()+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ },+)++it('returns focus to Configure when saving a schema removes the empty-state trigger', async () => {+ const screen = await renderOutput()+ const emptyTrigger = screen.getByRole('button', { name: 'app.structOutput.notConfiguredTip' })+ const configure = screen.getByRole('button', { name: 'app.structOutput.configure' })+ const dialog = screen.getByRole('dialog', { name: 'workflowModels.nodes.llm.jsonSchema.title' })+ await emptyTrigger.click()+ await screen.getByRole('tab', { name: 'JSON Schema' }).click()+ await screen+ .getByRole('textbox', { name: 'JSON schema editor' })+ .fill(JSON.stringify(namedSchema))+ await screen.getByRole('button', { name: 'common.operation.save' }).click()+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(emptyTrigger).not.toBeInTheDocument()+ await expect.element(configure).toHaveFocus()++ await userEvent.keyboard('{Enter}')+ await expect.element(dialog).toBeVisible()+ await screen.getByRole('tab', { name: 'JSON Schema' }).click()+ await expect+ .element(screen.getByRole('textbox', { name: 'JSON schema editor' }))+ .toHaveValue(JSON.stringify(namedSchema, null, 2))+ await userEvent.keyboard('{Escape}')+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(configure).toHaveFocus()+})diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-schema-config.spec.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-schema-config.spec.tsxindex bf27746297b..d045323c663 100644--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-schema-config.spec.tsx+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-schema-config.spec.tsx@@ -1,90 +1,305 @@-import type { ReactNode } from 'react'-import { render, screen } from '@testing-library/react'+import type { StructuredOutput } from '../../../types'+import { QueryClient } from '@tanstack/react-query'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { JsonSchemaConfig } from '../json-schema-config'+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'+import { useState } from 'react'+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { consoleQuery } from '@/service/console'+import { commonQueryKeys } from '@/service/use-common'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { createSystemFeaturesFixture } from '@/test/console/system-features'+import { Type } from '../../../types'+import { StructureOutput } from '../../structure-output'-const emit = vi.fn()-const visualEditorState = {- advancedEditing: false,- isAddingNewField: false,- setAdvancedEditing: vi.fn(),- setHoveringProperty: vi.fn(),- setIsAddingNewField: vi.fn(),+vi.mock('@monaco-editor/react', () => {+ function Editor({+ value,+ onChange,+ options,+ }: {+ value?: string+ onChange?: (value: string) => void+ options?: { readOnly?: boolean }+ }) {+ return (+ <textarea+ aria-label="JSON schema editor"+ value={value}+ readOnly={options?.readOnly}+ onChange={(event) => onChange?.(event.target.value)}+ />+ )+ }+ return {+ Editor,+ default: Editor,+ DiffEditor: Editor,+ useMonaco: () => null,+ loader: { config: vi.fn() },+ }+})+const emptySchema = {+ type: Type.object,+ properties: {},+ required: [],+ additionalProperties: false as const,}+const namedSchema = {+ ...emptySchema,+ properties: { name: { type: Type.string } },+ required: ['name'],+}+const dialogName = 'workflowModels.nodes.llm.jsonSchema.title'+const saveName = 'common.operation.save'+const generatorName = 'workflowModels.nodes.llm.jsonSchema.generateJsonSchema'+const instructionName = 'workflowModels.nodes.llm.jsonSchema.instruction'+const applyName = 'workflowModels.nodes.llm.jsonSchema.apply'-vi.mock('../visual-editor/context', () => ({- MittProvider: ({ children }: { children: ReactNode }) => children,- VisualEditorContextProvider: ({ children }: { children: ReactNode }) => children,- useMittContext: () => ({ emit }),-}))--vi.mock('../visual-editor/store', () => ({- useVisualEditorStore: (selector: (state: typeof visualEditorState) => unknown) =>- selector(visualEditorState),-}))--vi.mock('../visual-editor', () => ({- default: () => <div>Visual editor panel</div>,-}))--vi.mock('../schema-editor', () => ({- default: ({ schema, onUpdate }: { schema: string; onUpdate: (schema: string) => void }) => (- <textarea- aria-label="JSON schema editor"- value={schema}- onChange={(event) => onUpdate(event.target.value)}- />- ),-}))--vi.mock('../error-message', () => ({- default: ({ message }: { message: string }) => <div role="alert">{message}</div>,-}))--vi.mock('../json-schema-generator', () => ({- default: () => null,-}))--vi.mock('../json-importer', () => ({- default: () => null,-}))--describe('JsonSchemaConfig', () => {- beforeEach(() => {- vi.clearAllMocks()+function renderOutput({ readOnly = false, onChange = vi.fn() } = {}) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },})+ client.setQueryData(+ consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({+ input: { params: { model_type: ModelTypeEnum.textGeneration } },+ }).queryKey,+ { data: [] },+ )+ client.setQueryData(commonQueryKeys.defaultModel(ModelTypeEnum.textGeneration), { data: null })+ client.setQueryData(+ consoleQuery.systemFeatures.get.queryOptions().queryKey,+ createSystemFeaturesFixture(),+ )+ client.setQueryData(+ consoleQuery.workspaces.current.modelProviders.credits.get.queryOptions().queryKey,+ {+ pool_type: 'trial',+ quota_limit: 200,+ quota_used: 0,+ remaining_credits: 200,+ is_unlimited: false,+ is_exhausted: false,+ exhausted_at: null,+ next_credit_reset_date: null,+ },+ )+ function Fixture({ readOnly }: { readOnly: boolean }) {+ const [value, setValue] = useState<StructuredOutput>({ schema: emptySchema })+ return (+ <StructureOutput+ value={value}+ onChange={(next) => {+ onChange(next)+ setValue(next)+ }}+ readOnly={readOnly}+ />+ )+ }+ const view = render(+ <NuqsTestingAdapter>+ <QueryClientTestProvider queryClient={client}>+ <Fixture readOnly={readOnly} />+ </QueryClientTestProvider>+ </NuqsTestingAdapter>,+ )+ return {+ onChange,+ setReadOnly(next: boolean) {+ view.rerender(+ <NuqsTestingAdapter>+ <QueryClientTestProvider queryClient={client}>+ <Fixture readOnly={next} />+ </QueryClientTestProvider>+ </NuqsTestingAdapter>,+ )+ },+ }+}+async function openEditor(user: ReturnType<typeof userEvent.setup>) {+ await user.click(screen.getByRole('button', { name: 'app.structOutput.configure' }))+ return screen.findByRole('dialog', { name: dialogName })+}+async function editJSON(user: ReturnType<typeof userEvent.setup>, json: string) {+ await user.click(screen.getByRole('tab', { name: 'JSON Schema' }))+ fireEvent.change(screen.getByRole('textbox', { name: 'JSON schema editor' }), {+ target: { value: json },+ })+}+async function closeEditor(user: ReturnType<typeof userEvent.setup>) {+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ await waitFor(() =>+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),+ )+}+async function generate(user: ReturnType<typeof userEvent.setup>) {+ await user.click(screen.getByRole('button', { name: generatorName }))+ await user.type(await screen.findByRole('textbox', { name: instructionName }), 'Generate a name')+ await user.click(+ screen.getByRole('button', {+ name: 'workflowModels.nodes.llm.jsonSchema.generate',+ }),+ )+}+beforeEach(() => vi.restoreAllMocks())+describe('StructureOutput schema sessions', () => {it('moves tab focus without activating a different editor', async () => {const user = userEvent.setup()- render(<JsonSchemaConfig onSave={vi.fn()} onClose={vi.fn()} />)-+ renderOutput()+ await openEditor(user)const visualTab = screen.getByRole('tab', { name: 'Visual Editor' })- const jsonTab = screen.getByRole('tab', { name: 'JSON Schema' })-visualTab.focus()await user.keyboard('{ArrowRight}')-- expect(jsonTab).toHaveFocus()+ expect(screen.getByRole('tab', { name: 'JSON Schema' })).toHaveFocus()expect(visualTab).toHaveAttribute('aria-selected', 'true')- expect(screen.getByText('Visual editor panel')).toBeInTheDocument()})-- it('keeps the JSON editor active when its value cannot be validated', async () => {+ it('keeps invalid JSON open and resets draft, errors and tab after cancel', async () => {const user = userEvent.setup()- render(<JsonSchemaConfig onSave={vi.fn()} onClose={vi.fn()} />)-- await user.click(screen.getByRole('tab', { name: 'JSON Schema' }))-- const editor = screen.getByRole('textbox', { name: 'JSON schema editor' })- await user.clear(editor)- await user.type(editor, 'invalid json')+ const { onChange } = renderOutput()+ await openEditor(user)+ await editJSON(user, 'invalid json')await user.click(screen.getByRole('tab', { name: 'Visual Editor' }))-expect(screen.getByRole('tab', { name: 'JSON Schema' })).toHaveAttribute('aria-selected','true',)- expect(editor).toBeInTheDocument()- expect(screen.getByRole('alert')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: saveName }))+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()+ expect(onChange).not.toHaveBeenCalled()+ await closeEditor(user)+ await openEditor(user)+ expect(screen.getByRole('tab', { name: 'Visual Editor' })).toHaveAttribute(+ 'aria-selected',+ 'true',+ )+ await user.click(screen.getByRole('tab', { name: 'JSON Schema' }))+ expect(screen.getByRole('textbox', { name: 'JSON schema editor' })).toHaveValue(+ JSON.stringify(emptySchema, null, 2),+ )+ await user.click(screen.getByRole('button', { name: saveName }))+ expect(onChange).toHaveBeenCalledWith({ schema: emptySchema })+ })+ it('commits valid JSON once and reopens from the saved value', async () => {+ const user = userEvent.setup()+ const { onChange } = renderOutput()+ await openEditor(user)+ await editJSON(user, JSON.stringify(namedSchema))+ await user.click(screen.getByRole('button', { name: saveName }))+ await waitFor(() =>+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),+ )+ expect(onChange).toHaveBeenCalledExactlyOnceWith({ schema: namedSchema })+ await openEditor(user)+ await user.click(screen.getByRole('tab', { name: 'JSON Schema' }))+ expect(screen.getByRole('textbox', { name: 'JSON schema editor' })).toHaveValue(+ JSON.stringify(namedSchema, null, 2),+ )+ })+ it.each([+ ['invalid root', JSON.stringify({ type: 'string' })],+ [+ 'invalid property type',+ JSON.stringify({ ...emptySchema, properties: { name: { type: 'invalid' } } }),+ ],+ [+ 'excessive depth',+ JSON.stringify(+ Array.from({ length: 15 }).reduce<object>(+ (schema) => ({ ...emptySchema, properties: { nested: schema } }),+ emptySchema,+ ),+ ),+ ],+ ])('refuses saving %s', async (_label, json) => {+ const user = userEvent.setup()+ const { onChange } = renderOutput()+ await openEditor(user)+ await editJSON(user, json)+ await user.click(screen.getByRole('button', { name: saveName }))+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()+ expect(onChange).not.toHaveBeenCalled()+ })+ it('refuses unfinished visual edits and creates a clean store after closing', async () => {+ const user = userEvent.setup()+ const { onChange } = renderOutput()+ await openEditor(user)+ await user.click(+ screen.getByRole('button', { name: 'workflowModels.nodes.llm.jsonSchema.addField' }),+ )+ await user.click(screen.getByRole('button', { name: saveName }))+ expect(onChange).not.toHaveBeenCalled()+ await closeEditor(user)+ await openEditor(user)+ await user.click(screen.getByRole('button', { name: saveName }))+ expect(onChange).toHaveBeenCalledExactlyOnceWith({ schema: emptySchema })+ })+ it('gates initial read-only permissions and terminates an active draft when permission changes', async () => {+ const user = userEvent.setup()+ const { onChange, setReadOnly } = renderOutput({ readOnly: true })+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ expect(screen.getByText('app.structOutput.notConfiguredTip')).toBeInTheDocument()+ setReadOnly(false)+ await openEditor(user)+ await editJSON(user, JSON.stringify(namedSchema))+ setReadOnly(true)+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument()+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ expect(onChange).not.toHaveBeenCalled()+ setReadOnly(false)+ await openEditor(user)+ await user.click(screen.getByRole('tab', { name: 'JSON Schema' }))+ expect(screen.getByRole('textbox', { name: 'JSON schema editor' })).toHaveValue(+ JSON.stringify(emptySchema, null, 2),+ )+ })+ it('applies generated schema only to the draft and discards it on main cancel', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ Response.json({ output: JSON.stringify(namedSchema) }),+ )+ const user = userEvent.setup()+ const { onChange } = renderOutput()+ await openEditor(user)+ await generate(user)+ await user.click(await screen.findByRole('button', { name: applyName }))+ await user.click(screen.getByRole('tab', { name: 'JSON Schema' }))+ expect(screen.getByRole('textbox', { name: 'JSON schema editor' })).toHaveValue(+ JSON.stringify(namedSchema, null, 2),+ )+ expect(onChange).not.toHaveBeenCalled()+ await closeEditor(user)+ await openEditor(user)+ await user.click(screen.getByRole('tab', { name: 'JSON Schema' }))+ expect(screen.getByRole('textbox', { name: 'JSON schema editor' })).toHaveValue(+ JSON.stringify(emptySchema, null, 2),+ )+ })+ it('does not let a late generation result populate a newly opened session', async () => {+ let resolve!: (value: Response) => void+ vi.spyOn(globalThis, 'fetch').mockReturnValue(+ new Promise((done) => {+ resolve = done+ }),+ )+ const user = userEvent.setup()+ const { onChange } = renderOutput()+ await openEditor(user)+ await generate(user)+ await user.keyboard('{Escape}')+ await waitFor(() =>+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),+ )+ await openEditor(user)+ await act(async () => resolve(Response.json({ output: JSON.stringify(namedSchema) })))+ await user.click(screen.getByRole('button', { name: generatorName }))+ expect(await screen.findByRole('textbox', { name: instructionName })).toHaveValue('')+ expect(screen.queryByRole('button', { name: applyName })).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: generatorName }))+ await user.click(screen.getByRole('tab', { name: 'JSON Schema' }))+ expect(screen.getByRole('textbox', { name: 'JSON schema editor' })).toHaveValue(+ JSON.stringify(emptySchema, null, 2),+ )+ expect(onChange).not.toHaveBeenCalled()})})diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/index.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/index.tsxdeleted file mode 100644index f559f7c022f..00000000000--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/index.tsx+++ /dev/null@@ -1,30 +0,0 @@-import type { SchemaRoot } from '../../types'-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'-import { JsonSchemaConfig } from './json-schema-config'--type JsonSchemaConfigModalProps = {- isShow: boolean- defaultSchema?: SchemaRoot- onSave: (schema: SchemaRoot) => void- onClose: () => void-}--export function JsonSchemaConfigModal({- isShow,- defaultSchema,- onSave,- onClose,-}: JsonSchemaConfigModalProps) {- return (- <Dialog- open={isShow}- onOpenChange={(open) => {- if (!open) onClose()- }}- >- <DialogContent className="h-[calc(100dvh-32px)] max-h-200 w-full max-w-240 overflow-hidden! border-none p-0 text-left align-middle">- <JsonSchemaConfig defaultSchema={defaultSchema} onSave={onSave} onClose={onClose} />- </DialogContent>- </Dialog>- )-}diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-schema-config.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-schema-config.tsxindex 8658140aac8..1775bc50eee 100644--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-schema-config.tsx+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-schema-config.tsx@@ -1,6 +1,7 @@import type { SchemaRoot } from '../../types'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'+import { DialogClose, DialogTitle } from '@langgenius/dify-ui/dialog'import { Separator } from '@langgenius/dify-ui/separator'import { Tabs, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'import { useState } from 'react'@@ -17,7 +18,7 @@ import {} from '../../utils'import ErrorMessage from './error-message'import JsonImporter from './json-importer'-import JsonSchemaGenerator from './json-schema-generator'+import { JsonSchemaGenerator } from './json-schema-generator'import SchemaEditor from './schema-editor'import VisualEditor from './visual-editor'import { MittProvider, useMittContext, VisualEditorContextProvider } from './visual-editor/context'@@ -26,7 +27,6 @@ import { useVisualEditorStore } from './visual-editor/store'type JsonSchemaConfigProps = {defaultSchema?: SchemaRootonSave: (schema: SchemaRoot) => void- onClose: () => void}type SchemaView = 'visualEditor' | 'jsonSchema'@@ -59,7 +59,7 @@ const DEFAULT_SCHEMA: SchemaRoot = {additionalProperties: false,}-function JsonSchemaConfigContent({ defaultSchema, onSave, onClose }: JsonSchemaConfigProps) {+function JsonSchemaConfigContent({ defaultSchema, onSave }: JsonSchemaConfigProps) {const { t } = useTranslation(['common', 'workflowModels'])const [selectedSchemaView, setSelectedSchemaView] = useState<SchemaView>('visualEditor')const [jsonSchema, setJsonSchema] = useState(defaultSchema || DEFAULT_SCHEMA)@@ -148,10 +148,6 @@ function JsonSchemaConfigContent({ defaultSchema, onSave, onClose }: JsonSchemaCsetJson(JSON.stringify(DEFAULT_SCHEMA, null, 2))}- function handleCancel() {- onClose()- }-function handleSave() {let schema = jsonSchemaif (selectedSchemaView === 'jsonSchema') {@@ -190,7 +186,6 @@ function JsonSchemaConfigContent({ defaultSchema, onSave, onClose }: JsonSchemaC}}onSave(schema)- onClose()}return (@@ -203,17 +198,15 @@ function JsonSchemaConfigContent({ defaultSchema, onSave, onClose }: JsonSchemaC>{/* Header */}<div className="relative flex p-6 pr-14 pb-3">- <div className="grow truncate title-2xl-semi-bold text-text-primary">+ <DialogTitle className="grow truncate title-2xl-semi-bold text-text-primary">{t(($) => $['nodes.llm.jsonSchema.title'], { ns: 'workflowModels' })}- </div>- <button- type="button"+ </DialogTitle>+ <DialogCloseclassName="absolute top-5 right-5 flex size-8 items-center justify-center p-1.5"aria-label={t(($) => $['operation.close'], { ns: 'common' })}- onClick={onClose}>- <span className="i-ri-close-line h-4.5 w-4.5 text-text-tertiary" />- </button>+ <span aria-hidden className="i-ri-close-line h-4.5 w-4.5 text-text-tertiary" />+ </DialogClose></div><div className="flex items-center justify-between px-6 py-2"><TabsList@@ -259,9 +252,9 @@ function JsonSchemaConfigContent({ defaultSchema, onSave, onClose }: JsonSchemaC<Separator orientation="vertical" className="mr-0 ml-1 h-4" /></div><div className="flex items-center gap-x-2">- <Button variant="secondary" onClick={handleCancel}>+ <DialogClose render={<Button variant="secondary" />}>{t(($) => $['operation.cancel'], { ns: 'common' })}- </Button>+ </DialogClose><Button variant="primary" onClick={handleSave}>{t(($) => $['operation.save'], { ns: 'common' })}</Button>diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-schema-generator/index.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-schema-generator/index.tsxindex e27b5e475c3..29a9fd48aa5 100644--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-schema-generator/index.tsx+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-schema-generator/index.tsx@@ -1,10 +1,10 @@-import type { FC } from 'react'import type { SchemaRoot } from '../../../types'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { CompletionParams, Model } from '@/types/app'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import * as React from 'react'import { useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'import { useAutoGenModel } from '@/app/components/app/configuration/config/auto-gen-model-storage'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'@@ -37,7 +37,8 @@ const createEmptyModel = (): Model => ({completion_params: {} as CompletionParams,})-const JsonSchemaGenerator: FC<JsonSchemaGeneratorProps> = ({ onApply, crossAxisOffset }) => {+export function JsonSchemaGenerator({ onApply, crossAxisOffset }: JsonSchemaGeneratorProps) {+ const { t } = useTranslation(['workflowModels'])const [open, setOpen] = useState(false)const [view, setView] = useState<GeneratorView>(GENERATOR_VIEWS.promptEditor)const [model, setModel] = useAutoGenModel()@@ -144,6 +145,7 @@ const JsonSchemaGenerator: FC<JsonSchemaGeneratorProps> = ({ onApply, crossAxisOrender={<buttontype="button"+ aria-label={t(($) => $['nodes.llm.jsonSchema.generateJsonSchema'])}onClick={handleTrigger}className="flex size-6 items-center justify-center rounded-md p-0.5 hover:bg-state-accent-hover data-popup-open:bg-state-accent-active data-popup-open:hover:bg-state-accent-hover">@@ -182,5 +184,3 @@ const JsonSchemaGenerator: FC<JsonSchemaGeneratorProps> = ({ onApply, crossAxisO</Popover>)}--export default JsonSchemaGeneratordiff --git a/web/app/components/workflow/nodes/llm/components/panel-output-section.tsx b/web/app/components/workflow/nodes/llm/components/panel-output-section.tsxindex 3d90c845660..cc478b5d3b9 100644--- a/web/app/components/workflow/nodes/llm/components/panel-output-section.tsx+++ b/web/app/components/workflow/nodes/llm/components/panel-output-section.tsx@@ -103,6 +103,7 @@ const PanelOutputSection: FC<Props> = ({<Split className="mt-3" /><StructureOutputclassName="mt-4"+ readOnly={readOnly}value={inputs.structured_output}onChange={handleStructureOutputChange}/>diff --git a/web/app/components/workflow/nodes/llm/components/structure-output.tsx b/web/app/components/workflow/nodes/llm/components/structure-output.tsxindex 8e67c172eb5..af2569005a8 100644--- a/web/app/components/workflow/nodes/llm/components/structure-output.tsx+++ b/web/app/components/workflow/nodes/llm/components/structure-output.tsx@@ -2,26 +2,36 @@import type { SchemaRoot, StructuredOutput } from '../types'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'-import { useState } from 'react'+import {+ createDialogHandle,+ Dialog,+ DialogContent,+ DialogTrigger,+} from '@langgenius/dify-ui/dialog'+import { useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import ShowPanel from '@/app/components/workflow/nodes/_base/components/variable/object-child-tree-panel/show'-import { Type } from '../types'-import { JsonSchemaConfigModal } from './json-schema-config-modal'+import { JsonSchemaConfig } from './json-schema-config-modal/json-schema-config'type Props = Readonly<{className?: stringvalue?: StructuredOutputonChange: (value: StructuredOutput) => void+ readOnly: boolean}>-export function StructureOutput({ className, value, onChange }: Props) {+export function StructureOutput({ className, value, onChange, readOnly }: Props) {const { t } = useTranslation(['app'])- const [showConfig, setShowConfig] = useState(false)+ // The triggers stay in the summary so it keeps its place when the editing dialog is removed.+ const [dialogHandle] = useState(() => createDialogHandle())+ const configureButtonRef = useRef<HTMLButtonElement>(null)+ const hasSchema = !!value?.schema.properties && Object.keys(value.schema.properties).length > 0function handleChange(value: SchemaRoot) {onChange({schema: value,})+ dialogHandle.close()}return (@@ -31,46 +41,43 @@ export function StructureOutput({ className, value, onChange }: Props) {<div className="code-sm-semibold text-text-secondary">structured_output</div><div className="ml-2 system-xs-regular text-text-tertiary">object</div></div>- <Button- size="small"- variant="secondary"- className="flex"- onClick={() => setShowConfig(true)}- >- <i className="i-ri-edit-line size-3.5" aria-hidden="true" />- <div className="system-xs-medium text-components-button-secondary-text">- {t(($) => $['structOutput.configure'], { ns: 'app' })}- </div>- </Button>+ {!readOnly && (+ <DialogTrigger+ handle={dialogHandle}+ render={+ <Button ref={configureButtonRef} size="small" variant="secondary" className="flex" />+ }+ >+ <i className="i-ri-edit-line size-3.5" aria-hidden="true" />+ <span className="system-xs-medium text-components-button-secondary-text">+ {t(($) => $['structOutput.configure'], { ns: 'app' })}+ </span>+ </DialogTrigger>+ )}</div>- {value?.schema &&- value.schema.properties &&- Object.keys(value.schema.properties).length > 0 ? (+ {hasSchema ? (<ShowPanel payload={value} />+ ) : readOnly ? (+ <div className="mt-1.5 flex h-10 w-full items-center justify-center rounded-[10px] bg-background-section system-xs-regular text-text-tertiary">+ {t(($) => $['structOutput.notConfiguredTip'], { ns: 'app' })}+ </div>) : (- <button- type="button"- className="mt-1.5 flex h-10 w-full cursor-pointer items-center justify-center rounded-[10px] bg-background-section system-xs-regular text-text-tertiary"- onClick={() => setShowConfig(true)}+ <DialogTrigger+ handle={dialogHandle}+ className="mt-1.5 flex h-10 w-full cursor-pointer items-center justify-center rounded-[10px] bg-background-section system-xs-regular text-text-tertiary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden">{t(($) => $['structOutput.notConfiguredTip'], { ns: 'app' })}- </button>+ </DialogTrigger>)}-- {showConfig && (- <JsonSchemaConfigModal- isShow- defaultSchema={- (value?.schema || {- type: Type.object,- properties: {},- required: [],- additionalProperties: false,- }) as any- } // wait for types change- onSave={handleChange as any} // wait for types change- onClose={() => setShowConfig(false)}- />+ {!readOnly && (+ <Dialog handle={dialogHandle}>+ <DialogContent+ className="h-[calc(100dvh-32px)] max-h-200 w-full max-w-240 overflow-hidden! border-none p-0 text-left align-middle"+ finalFocus={hasSchema ? configureButtonRef : undefined}+ >+ <JsonSchemaConfig defaultSchema={value?.schema} onSave={handleChange} />+ </DialogContent>+ </Dialog>)}</div>)