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.

refactor(web): keep configuration drafts inside dialog popups (#43512)

yyh3c7593ba0083
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 156a7a82439..f75a7a398e5 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -276,11 +276,6 @@
"count": 1
}
},
- "web/app/components/app/configuration/config/__tests__/agent-setting-button.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx": {
"typescript/no-explicit-any": {
"count": 1
@@ -3028,10 +3023,10 @@
},
"web/app/components/workflow/nodes/http/panel.tsx": {
"jsx-a11y/click-events-have-key-events": {
- "count": 2
+ "count": 1
},
"jsx-a11y/no-static-element-interactions": {
- "count": 2
+ "count": 1
}
},
"web/app/components/workflow/nodes/http/use-config.ts": {
@@ -3315,19 +3310,6 @@
"count": 3
}
},
- "web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/item.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 2
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 2
- }
- },
- "web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/parameter-extractor/use-config.ts": {
"eslint-react/set-state-in-effect": {
"count": 2
diff --git a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx
index caa35d672ea..72793efaaf6 100644
--- a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx
+++ b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx
@@ -30,10 +30,6 @@ vi.mock('@/app/components/app/configuration/debug', () => ({
default: () => <div data-testid="debug-panel" />,
}))
-vi.mock('@/app/components/app/configuration/config/agent-setting-button', () => ({
- default: () => <div data-testid="agent-setting-button" />,
-}))
-
vi.mock(
'@/app/components/header/account-setting/model-provider-page/model-parameter-modal',
() => ({
diff --git a/web/app/components/app/configuration/config/__tests__/agent-setting-button.spec.tsx b/web/app/components/app/configuration/config/__tests__/agent-setting-button.spec.tsx
deleted file mode 100644
index 9029de61afa..00000000000
--- a/web/app/components/app/configuration/config/__tests__/agent-setting-button.spec.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import type { AgentConfig } from '@/models/debug'
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import * as React from 'react'
-import { AgentStrategy } from '@/types/app'
-import AgentSettingButton from '../agent-setting-button'
-
-let latestAgentSettingProps: any
-vi.mock('../agent/agent-setting', () => ({
- AgentSetting: (props: any) => {
- latestAgentSettingProps = props
- return (
- <div data-testid="agent-setting">
- <button onClick={() => props.onSave({ ...props.payload, max_iteration: 9 })}>
- save-agent
- </button>
- <button onClick={props.onCancel}>cancel-agent</button>
- </div>
- )
- },
-}))
-
-const createAgentConfig = (overrides: Partial<AgentConfig> = {}): AgentConfig => ({
- enabled: true,
- strategy: AgentStrategy.react,
- max_iteration: 3,
- tools: [],
- ...overrides,
-})
-
-const setup = (overrides: Partial<React.ComponentProps<typeof AgentSettingButton>> = {}) => {
- const props: React.ComponentProps<typeof AgentSettingButton> = {
- isFunctionCall: false,
- isChatModel: true,
- onAgentSettingChange: vi.fn(),
- agentConfig: createAgentConfig(),
- ...overrides,
- }
-
- const user = userEvent.setup()
- render(<AgentSettingButton {...props} />)
- return { props, user }
-}
-
-beforeEach(() => {
- vi.clearAllMocks()
- latestAgentSettingProps = undefined
-})
-
-describe('AgentSettingButton', () => {
- it('should render button label from translation key', () => {
- setup()
-
- expect(screen.getByRole('button', { name: 'appDebug.agent.setting.name' })).toBeInTheDocument()
- })
-
- it('should open AgentSetting with the provided configuration when clicked', async () => {
- const { user, props } = setup({ isFunctionCall: true, isChatModel: false })
-
- await user.click(screen.getByRole('button', { name: 'appDebug.agent.setting.name' }))
-
- expect(screen.getByTestId('agent-setting')).toBeInTheDocument()
- expect(latestAgentSettingProps.isFunctionCall).toBe(true)
- expect(latestAgentSettingProps.isChatModel).toBe(false)
- expect(latestAgentSettingProps.payload).toEqual(props.agentConfig)
- })
-
- it('should call onAgentSettingChange and close when AgentSetting saves', async () => {
- const { user, props } = setup()
-
- await user.click(screen.getByRole('button', { name: 'appDebug.agent.setting.name' }))
- await user.click(screen.getByText('save-agent'))
-
- expect(props.onAgentSettingChange).toHaveBeenCalledTimes(1)
- expect(props.onAgentSettingChange).toHaveBeenCalledWith({
- ...props.agentConfig,
- max_iteration: 9,
- })
- expect(screen.queryByTestId('agent-setting')).not.toBeInTheDocument()
- })
-
- it('should close AgentSetting without saving when cancel is triggered', async () => {
- const { user, props } = setup()
-
- await user.click(screen.getByRole('button', { name: 'appDebug.agent.setting.name' }))
- await user.click(screen.getByText('cancel-agent'))
-
- expect(props.onAgentSettingChange).not.toHaveBeenCalled()
- expect(screen.queryByTestId('agent-setting')).not.toBeInTheDocument()
- })
-})
diff --git a/web/app/components/app/configuration/config/agent-setting-button.tsx b/web/app/components/app/configuration/config/agent-setting-button.tsx
deleted file mode 100644
index bf39e6e95de..00000000000
--- a/web/app/components/app/configuration/config/agent-setting-button.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import type { AgentConfig } from '@/models/debug'
-import { Button } from '@langgenius/dify-ui/button'
-import * as React from 'react'
-import { useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { AgentSetting } from './agent/agent-setting'
-
-type Props = Readonly<{
- isFunctionCall: boolean
- isChatModel: boolean
- agentConfig?: AgentConfig
- disabled?: boolean
- onAgentSettingChange: (payload: AgentConfig) => void
-}>
-
-const AgentSettingButton: FC<Props> = ({
- onAgentSettingChange,
- isFunctionCall,
- isChatModel,
- agentConfig,
- disabled = false,
-}) => {
- const { t } = useTranslation(['appDebug'])
- const [isShowAgentSetting, setIsShowAgentSetting] = useState(false)
-
- return (
- <>
- <Button
- onClick={() => setIsShowAgentSetting(true)}
- className="mr-2 shrink-0"
- disabled={disabled}
- >
- <span className="i-ri-settings-2-line size-4 text-text-tertiary" />
- {t(($) => $['agent.setting.name'], { ns: 'appDebug' })}
- </Button>
- {isShowAgentSetting && (
- <AgentSetting
- isFunctionCall={isFunctionCall}
- payload={agentConfig as AgentConfig}
- isChatModel={isChatModel}
- onSave={(payloadNew) => {
- onAgentSettingChange(payloadNew)
- setIsShowAgentSetting(false)
- }}
- onCancel={() => setIsShowAgentSetting(false)}
- />
- )}
- </>
- )
-}
-export default React.memo(AgentSettingButton)
diff --git a/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx b/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
index 483c7352789..86734074195 100644
--- a/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
@@ -1,127 +1,96 @@
import type { AgentConfig } from '@/models/debug'
-import { act, fireEvent, render, screen } from '@testing-library/react'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
import { MAX_ITERATIONS_NUM } from '@/config'
-import { AgentSetting } from '../index'
+import { AgentStrategy } from '@/types/app'
+import { AgentSettingDialog } from '../index'
-const basePayload = {
+const basePayload: AgentConfig = {
enabled: true,
- strategy: 'react',
+ strategy: AgentStrategy.react,
max_iteration: 5,
tools: [],
}
-const renderModal = (props?: Partial<React.ComponentProps<typeof AgentSetting>>) => {
- const onCancel = vi.fn()
- const onSave = vi.fn()
- const utils = render(
- <AgentSetting
+function SettingsFixture({ onSave }: { onSave: (payload: AgentConfig) => void }) {
+ const [payload, setPayload] = useState(basePayload)
+ return (
+ <AgentSettingDialog
isChatModel
- payload={basePayload as AgentConfig}
+ payload={payload}
isFunctionCall={false}
- onCancel={onCancel}
- onSave={onSave}
- {...props}
- />,
+ onSave={(value) => {
+ setPayload(value)
+ onSave(value)
+ }}
+ />
)
- return { ...utils, onCancel, onSave }
}
-describe('AgentSetting', () => {
- it('should render agent mode description and default prompt section when not function call', () => {
- renderModal()
+const settingName = 'appDebug.agent.setting.name'
- expect(screen.getByText('appDebug.agent.agentMode')).toBeInTheDocument()
+describe('AgentSettingDialog', () => {
+ it('discards cancelled edits, submits current iterations, and reopens the saved configuration', async () => {
+ const user = userEvent.setup()
+ const onSave = vi.fn()
+ render(<SettingsFixture onSave={onSave} />)
+ const trigger = screen.getByRole('button', { name: settingName })
+ await user.click(trigger)
expect(screen.getByText('appDebug.agent.agentModeType.ReACT')).toBeInTheDocument()
expect(screen.getByText('tools.builtInPromptTitle')).toBeInTheDocument()
+ await user.clear(screen.getByRole('spinbutton'))
+ await user.type(screen.getByRole('spinbutton'), '7')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(onSave).not.toHaveBeenCalled()
+ expect(trigger).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(screen.getByRole('spinbutton')).toHaveValue(5)
+ await user.clear(screen.getByRole('spinbutton'))
+ await user.type(screen.getByRole('spinbutton'), '6{Enter}')
+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ max_iteration: 6 }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(trigger)
+ expect(screen.getByRole('spinbutton')).toHaveValue(6)
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(trigger).toHaveFocus()
})
- it('should display function call mode when isFunctionCall true', () => {
- renderModal({ isFunctionCall: true })
-
- expect(screen.getByText('appDebug.agent.agentModeType.functionCall')).toBeInTheDocument()
+ it('clamps iterations and saves the minimum when the number input is cleared', async () => {
+ const user = userEvent.setup()
+ const onSave = vi.fn()
+ render(<AgentSettingDialog isChatModel payload={basePayload} isFunctionCall onSave={onSave} />)
+ await user.click(screen.getByRole('button', { name: settingName }))
expect(screen.queryByText('tools.builtInPromptTitle')).not.toBeInTheDocument()
+ const input = screen.getByRole('spinbutton')
+ await user.clear(input)
+ await user.type(input, '999')
+ expect(input).toHaveValue(MAX_ITERATIONS_NUM)
+ await user.clear(input)
+ await user.type(input, '0')
+ expect(input).toHaveValue(1)
+ await user.clear(input)
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ max_iteration: 1 }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
- it('should update iteration via slider and number input', () => {
- renderModal()
- const slider = screen.getByRole('slider')
- const numberInput = screen.getByRole('spinbutton')
-
- fireEvent.change(slider, { target: { value: '7' } })
- expect(screen.getAllByDisplayValue('7')).toHaveLength(2)
-
- fireEvent.change(numberInput, { target: { value: '2' } })
- expect(screen.getAllByDisplayValue('2')).toHaveLength(2)
- })
-
- it('should clamp iteration value within min/max range', () => {
- renderModal()
-
- const numberInput = screen.getByRole('spinbutton')
-
- fireEvent.change(numberInput, { target: { value: '0' } })
- expect(screen.getAllByDisplayValue('1')).toHaveLength(2)
-
- fireEvent.change(numberInput, { target: { value: '999' } })
- expect(screen.getAllByDisplayValue(String(MAX_ITERATIONS_NUM))).toHaveLength(2)
- })
-
- it('should call onCancel when cancel button clicked', () => {
- const { onCancel } = renderModal()
- fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- expect(onCancel).toHaveBeenCalled()
- })
-
- it('should call onCancel when Escape is pressed', () => {
- const { onCancel } = renderModal()
-
- fireEvent.keyDown(document, { key: 'Escape' })
-
- expect(onCancel).toHaveBeenCalledTimes(1)
- })
-
- it('should call onCancel when the backdrop is clicked', () => {
- const { onCancel } = renderModal()
- const dialog = screen.getByRole('dialog')
-
- fireEvent.pointerDown(document.body, { target: document.body })
- fireEvent.mouseDown(document.body, { target: document.body })
- fireEvent.click(document.body, { target: document.body })
-
- expect(dialog).toBeInTheDocument()
- expect(onCancel).toHaveBeenCalledTimes(1)
- })
-
- it('should call onCancel when close button clicked', () => {
- const { onCancel } = renderModal()
-
- fireEvent.click(screen.getByRole('button', { name: 'common.operation.close' }))
-
- expect(onCancel).toHaveBeenCalledTimes(1)
- })
-
- it('should call onSave with updated payload', async () => {
- const { onSave } = renderModal()
- const numberInput = screen.getByRole('spinbutton')
- fireEvent.change(numberInput, { target: { value: '6' } })
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
- })
-
- expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ max_iteration: 6 }))
- })
-
- it('should save the minimum iteration when the number input is empty', async () => {
- const { onSave } = renderModal()
- fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '' } })
-
- expect(screen.getByRole('slider')).toHaveValue('1')
-
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
- })
-
- expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ max_iteration: 1 }))
+ it('keeps readonly settings unavailable', async () => {
+ const user = userEvent.setup()
+ render(
+ <AgentSettingDialog
+ isChatModel
+ payload={basePayload}
+ isFunctionCall
+ disabled
+ onSave={vi.fn()}
+ />,
+ )
+ const trigger = screen.getByRole('button', { name: settingName })
+ expect(trigger).toBeDisabled()
+ await user.click(trigger)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/app/configuration/config/agent/agent-setting/index.tsx b/web/app/components/app/configuration/config/agent/agent-setting/index.tsx
index a0f5f0463a0..29e382a10a7 100644
--- a/web/app/components/app/configuration/config/agent/agent-setting/index.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-setting/index.tsx
@@ -1,7 +1,14 @@
'use client'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
import type { AgentConfig } from '@/models/debug'
import { Button } from '@langgenius/dify-ui/button'
-import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import {
@@ -12,7 +19,7 @@ import {
SliderThumb,
SliderTrack,
} from '@langgenius/dify-ui/slider'
-import { useState } from 'react'
+import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { DEFAULT_AGENT_PROMPT, MAX_ITERATIONS_NUM } from '@/config'
import ItemPanel from './item-panel'
@@ -21,13 +28,41 @@ type Props = Readonly<{
isChatModel: boolean
payload: AgentConfig
isFunctionCall: boolean
- onCancel: () => void
+ disabled?: boolean
onSave: (payload: AgentConfig) => void
}>
const maxIterationsMin = 1
-export function AgentSetting({ isChatModel, payload, isFunctionCall, onCancel, onSave }: Props) {
+export function AgentSettingDialog({ disabled, onSave, ...props }: Props) {
+ const { t } = useTranslation(['appDebug'])
+ const actionsRef = useRef<DialogActions>(null)
+
+ return (
+ <Dialog actionsRef={actionsRef}>
+ <DialogTrigger render={<Button className="mr-2 shrink-0" disabled={disabled} />}>
+ <span aria-hidden className="i-ri-settings-2-line size-4 text-text-tertiary" />
+ {t(($) => $['agent.setting.name'])}
+ </DialogTrigger>
+ <DialogContent className="top-2 right-2 bottom-2 left-auto flex h-auto max-h-none w-160 max-w-[calc(100vw-1rem)] translate-x-0 translate-y-0 flex-col overflow-hidden rounded-xl p-0">
+ <AgentSettingsForm
+ {...props}
+ onSave={(payload) => {
+ onSave(payload)
+ actionsRef.current?.close()
+ }}
+ />
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function AgentSettingsForm({
+ isChatModel,
+ payload,
+ isFunctionCall,
+ onSave,
+}: Omit<Props, 'disabled'>) {
const { t } = useTranslation(['appDebug', 'common', 'tools'])
const [tempPayload, setTempPayload] = useState(payload)
const maximumIterationsLabel = t(($) => $['agent.setting.maximumIterations.name'], {
@@ -45,141 +80,137 @@ export function AgentSetting({ isChatModel, payload, isFunctionCall, onCancel, o
}
return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onCancel()
+ <form
+ className="flex min-h-0 flex-1 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault()
+ handleSave()
}}
>
- <DialogContent className="top-2 right-2 bottom-2 left-auto flex h-auto max-h-none w-160 max-w-[calc(100vw-1rem)] translate-x-0 translate-y-0 flex-col overflow-hidden rounded-xl p-0">
- <div className="flex h-14 shrink-0 items-center justify-between border-b border-divider-regular pr-5 pl-6">
- <DialogTitle className="text-base leading-6 font-semibold text-text-primary">
- {t(($) => $['agent.setting.name'], { ns: 'appDebug' })}
- </DialogTitle>
- <DialogClose
- render={
- <IconButton
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- size="sm"
- className="static z-auto size-6 shrink-0 rounded-2xl"
- >
- <span aria-hidden className="i-ri-close-line size-4" />
- </IconButton>
- }
- />
- </div>
- {/* Body */}
- <div
- className="grow overflow-y-auto border-b border-divider-regular p-6 pt-5 pb-17"
- style={{
- borderBottom: 'rgba(0, 0, 0, 0.05)',
- }}
+ <div className="flex h-14 shrink-0 items-center justify-between border-b border-divider-regular pr-5 pl-6">
+ <DialogTitle className="text-base leading-6 font-semibold text-text-primary">
+ {t(($) => $['agent.setting.name'], { ns: 'appDebug' })}
+ </DialogTitle>
+ <DialogClose
+ render={
+ <IconButton
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ size="sm"
+ className="static z-auto size-6 shrink-0 rounded-2xl"
+ >
+ <span aria-hidden className="i-ri-close-line size-4" />
+ </IconButton>
+ }
+ />
+ </div>
+ {/* Body */}
+ <div
+ className="grow overflow-y-auto border-b border-divider-regular p-6 pt-5 pb-17"
+ style={{
+ borderBottom: 'rgba(0, 0, 0, 0.05)',
+ }}
+ >
+ {/* Agent Mode */}
+ <ItemPanel
+ className="mb-4"
+ icon={
+ <span
+ aria-hidden
+ className="i-custom-vender-solid-communication-cute-robot size-4 text-indigo-600"
+ />
+ }
+ name={t(($) => $['agent.agentMode'], { ns: 'appDebug' })}
+ description={t(($) => $['agent.agentModeDes'], { ns: 'appDebug' })}
>
- {/* Agent Mode */}
- <ItemPanel
- className="mb-4"
- icon={
- <span
- aria-hidden
- className="i-custom-vender-solid-communication-cute-robot size-4 text-indigo-600"
- />
- }
- name={t(($) => $['agent.agentMode'], { ns: 'appDebug' })}
- description={t(($) => $['agent.agentModeDes'], { ns: 'appDebug' })}
- >
- <div className="text-[13px] leading-4.5 font-medium text-text-primary">
- {isFunctionCall
- ? t(($) => $['agent.agentModeType.functionCall'], { ns: 'appDebug' })
- : t(($) => $['agent.agentModeType.ReACT'], { ns: 'appDebug' })}
- </div>
- </ItemPanel>
+ <div className="text-[13px] leading-4.5 font-medium text-text-primary">
+ {isFunctionCall
+ ? t(($) => $['agent.agentModeType.functionCall'], { ns: 'appDebug' })
+ : t(($) => $['agent.agentModeType.ReACT'], { ns: 'appDebug' })}
+ </div>
+ </ItemPanel>
- <ItemPanel
- className="mb-4"
- icon={
- <span
- aria-hidden
- className="i-custom-vender-solid-education-unblur h-4 w-4 text-[#FB6514]"
- />
- }
- name={maximumIterationsLabel}
- description={t(($) => $['agent.setting.maximumIterations.description'], {
- ns: 'appDebug',
- })}
- >
- <Fieldset className="flex items-center">
- <FieldsetLegend className="sr-only">{maximumIterationsLabel}</FieldsetLegend>
- <Slider
- className="mr-3 w-39"
- min={maxIterationsMin}
- max={MAX_ITERATIONS_NUM}
- value={sliderValue}
- onValueChange={(value) => {
- setTempPayload({
- ...tempPayload,
- max_iteration: value,
- })
- }}
- >
- <SliderLabel className="sr-only">{maximumIterationsLabel}</SliderLabel>
- <SliderControl>
- <SliderTrack>
- <SliderIndicator />
- <SliderThumb />
- </SliderTrack>
- </SliderControl>
- </Slider>
+ <ItemPanel
+ className="mb-4"
+ icon={
+ <span
+ aria-hidden
+ className="i-custom-vender-solid-education-unblur h-4 w-4 text-[#FB6514]"
+ />
+ }
+ name={maximumIterationsLabel}
+ description={t(($) => $['agent.setting.maximumIterations.description'], {
+ ns: 'appDebug',
+ })}
+ >
+ <Fieldset className="flex items-center">
+ <FieldsetLegend className="sr-only">{maximumIterationsLabel}</FieldsetLegend>
+ <Slider
+ className="mr-3 w-39"
+ min={maxIterationsMin}
+ max={MAX_ITERATIONS_NUM}
+ value={sliderValue}
+ onValueChange={(value) => {
+ setTempPayload({
+ ...tempPayload,
+ max_iteration: value,
+ })
+ }}
+ >
+ <SliderLabel className="sr-only">{maximumIterationsLabel}</SliderLabel>
+ <SliderControl>
+ <SliderTrack>
+ <SliderIndicator />
+ <SliderThumb />
+ </SliderTrack>
+ </SliderControl>
+ </Slider>
- <input
- aria-label={maximumIterationsLabel}
- type="number"
- min={maxIterationsMin}
- max={MAX_ITERATIONS_NUM}
- step={1}
- className="block h-7 w-11 rounded-lg border-0 bg-components-input-bg-normal px-1.5 pl-1 leading-7 text-text-primary placeholder:text-text-tertiary focus:inset-ring-1 focus:inset-ring-primary-600"
- value={tempPayload.max_iteration}
- onChange={(e) => {
- let value = Number.parseInt(e.target.value, 10)
- if (value < maxIterationsMin) value = maxIterationsMin
+ <input
+ aria-label={maximumIterationsLabel}
+ type="number"
+ min={maxIterationsMin}
+ max={MAX_ITERATIONS_NUM}
+ step={1}
+ className="block h-7 w-11 rounded-lg border-0 bg-components-input-bg-normal px-1.5 pl-1 leading-7 text-text-primary placeholder:text-text-tertiary focus:inset-ring-1 focus:inset-ring-primary-600"
+ value={Number.isFinite(tempPayload.max_iteration) ? tempPayload.max_iteration : ''}
+ onChange={(e) => {
+ let value = Number.parseInt(e.target.value, 10)
+ if (value < maxIterationsMin) value = maxIterationsMin
- if (value > MAX_ITERATIONS_NUM) value = MAX_ITERATIONS_NUM
- setTempPayload({
- ...tempPayload,
- max_iteration: value,
- })
- }}
- />
- </Fieldset>
- </ItemPanel>
+ if (value > MAX_ITERATIONS_NUM) value = MAX_ITERATIONS_NUM
+ setTempPayload({
+ ...tempPayload,
+ max_iteration: value,
+ })
+ }}
+ />
+ </Fieldset>
+ </ItemPanel>
- {!isFunctionCall && (
- <div className="rounded-xl bg-background-section-burn py-2 shadow-xs">
- <div className="flex h-8 items-center px-4 text-sm/6 font-semibold text-text-secondary">
- {t(($) => $.builtInPromptTitle, { ns: 'tools' })}
- </div>
- <div className="h-99 overflow-y-auto px-4 text-sm leading-5 font-normal whitespace-pre-line text-text-secondary">
- {isChatModel ? DEFAULT_AGENT_PROMPT.chat : DEFAULT_AGENT_PROMPT.completion}
- </div>
- <div className="px-4">
- <div className="inline-flex h-5 items-center rounded-md bg-components-input-bg-normal px-1 text-xs leading-4.5 font-medium text-text-tertiary">
- {
- (isChatModel ? DEFAULT_AGENT_PROMPT.chat : DEFAULT_AGENT_PROMPT.completion)
- .length
- }
- </div>
+ {!isFunctionCall && (
+ <div className="rounded-xl bg-background-section-burn py-2 shadow-xs">
+ <div className="flex h-8 items-center px-4 text-sm/6 font-semibold text-text-secondary">
+ {t(($) => $.builtInPromptTitle, { ns: 'tools' })}
+ </div>
+ <div className="h-99 overflow-y-auto px-4 text-sm leading-5 font-normal whitespace-pre-line text-text-secondary">
+ {isChatModel ? DEFAULT_AGENT_PROMPT.chat : DEFAULT_AGENT_PROMPT.completion}
+ </div>
+ <div className="px-4">
+ <div className="inline-flex h-5 items-center rounded-md bg-components-input-bg-normal px-1 text-xs leading-4.5 font-medium text-text-tertiary">
+ {(isChatModel ? DEFAULT_AGENT_PROMPT.chat : DEFAULT_AGENT_PROMPT.completion).length}
</div>
</div>
- )}
- </div>
- <div className="sticky bottom-0 z-5 flex w-full justify-end border-t border-divider-regular bg-background-section-burn px-6 py-4">
- <Button type="button" onClick={onCancel} className="mr-2">
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button type="button" variant="primary" onClick={handleSave}>
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
+ </div>
+ )}
+ </div>
+ <div className="sticky bottom-0 z-5 flex w-full justify-end border-t border-divider-regular bg-background-section-burn px-6 py-4">
+ <DialogClose render={<Button className="mr-2" />}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </DialogClose>
+ <Button type="submit" variant="primary">
+ {t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ </div>
+ </form>
)
}
diff --git a/web/app/components/app/configuration/configuration-view/index.tsx b/web/app/components/app/configuration/configuration-view/index.tsx
index 16c5e01d9ab..95c2ba7af43 100644
--- a/web/app/components/app/configuration/configuration-view/index.tsx
+++ b/web/app/components/app/configuration/configuration-view/index.tsx
@@ -30,7 +30,7 @@ import { useTranslation } from 'react-i18next'
import AppPublisher from '@/app/components/app/app-publisher/features-wrapper'
import Config from '@/app/components/app/configuration/config'
import EditHistoryModal from '@/app/components/app/configuration/config-prompt/conversation-history/edit-modal'
-import AgentSettingButton from '@/app/components/app/configuration/config/agent-setting-button'
+import { AgentSettingDialog } from '@/app/components/app/configuration/config/agent/agent-setting'
import SelectDataSet from '@/app/components/app/configuration/dataset-config/select-dataset'
import Debug from '@/app/components/app/configuration/debug'
import { FeaturesProvider } from '@/app/components/base/features'
@@ -129,12 +129,12 @@ const ConfigurationView: FC<ConfigurationViewModel> = ({
</div>
<div className="flex items-center">
{isAgent && (
- <AgentSettingButton
+ <AgentSettingDialog
isChatModel={contextValue.modelModeType === ModelModeType.chat}
- agentConfig={modelConfig.agentConfig}
+ payload={modelConfig.agentConfig}
isFunctionCall={contextValue.isFunctionCall}
disabled={contextValue.readonly}
- onAgentSettingChange={onAgentSettingChange}
+ onSave={onAgentSettingChange}
/>
)}
{!debugWithMultipleModel && (
diff --git a/web/app/components/base/features/new-feature-panel/__tests__/follow-up-setting-modal.spec.tsx b/web/app/components/base/features/new-feature-panel/__tests__/follow-up-setting-modal.spec.tsx
index 9eadafb3198..fa6f8fc8e7c 100644
--- a/web/app/components/base/features/new-feature-panel/__tests__/follow-up-setting-modal.spec.tsx
+++ b/web/app/components/base/features/new-feature-panel/__tests__/follow-up-setting-modal.spec.tsx
@@ -1,9 +1,9 @@
import type { SuggestedQuestionsAfterAnswer } from '@/app/components/base/features/types'
import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { CompletionParams } from '@/types/app'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import FollowUpSettingModal from '../follow-up-setting-modal'
+import { FollowUpSettingsDialog } from '../follow-up-setting-modal'
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
useModelListAndDefaultModelAndCurrentProviderAndModel: () => ({
@@ -52,15 +52,14 @@ vi.mock(
}),
)
-const renderModal = (data: SuggestedQuestionsAfterAnswer = { enabled: true }) => {
+const renderModal = async (data: SuggestedQuestionsAfterAnswer = { enabled: true }) => {
const onSave = vi.fn()
- const onCancel = vi.fn()
- render(<FollowUpSettingModal data={data} onSave={onSave} onCancel={onCancel} />)
+ render(<FollowUpSettingsDialog data={data} onSave={onSave} />)
+ await userEvent.setup().click(screen.getByRole('button', { name: 'common.operation.settings' }))
return {
onSave,
- onCancel,
}
}
@@ -73,7 +72,7 @@ describe('FollowUpSettingModal', () => {
describe('Model Parameters', () => {
it('should keep max tokens disabled after its switch is turned off', async () => {
const user = userEvent.setup()
- renderModal({
+ await renderModal({
enabled: true,
model: {
provider: 'openai',
@@ -97,8 +96,8 @@ describe('FollowUpSettingModal', () => {
expect(maxTokensSwitch).toHaveAttribute('aria-checked', 'false')
})
- it('should keep max tokens disabled when saved model parameters omit it', () => {
- renderModal({
+ it('should keep max tokens disabled when saved model parameters omit it', async () => {
+ await renderModal({
enabled: true,
model: {
provider: 'openai',
@@ -120,7 +119,7 @@ describe('FollowUpSettingModal', () => {
describe('Default Prompt', () => {
it('should show the system default prompt and save without a custom prompt when no custom prompt is configured', async () => {
const user = userEvent.setup()
- const { onSave } = renderModal()
+ const { onSave } = await renderModal()
expect(
screen.getByText(
@@ -148,42 +147,34 @@ describe('FollowUpSettingModal', () => {
})
describe('Custom Prompt', () => {
- it('should expose the selected prompt mode through RadioItem state attributes', async () => {
+ it('should expose the selected prompt mode to assistive technology', async () => {
const user = userEvent.setup()
- renderModal()
+ await renderModal()
- const defaultOption = screen
- .getByText('appDebug.feature.suggestedQuestionsAfterAnswer.modal.defaultPromptOption')
- .closest('button')!
- const customOption = screen
- .getByText('appDebug.feature.suggestedQuestionsAfterAnswer.modal.customPromptOption')
- .closest('button')!
+ const defaultOption = screen.getByRole('radio', { name: /modal.defaultPromptOption/ })
+ const customOption = screen.getByRole('radio', { name: /modal.customPromptOption/ })
- expect(defaultOption).toHaveAttribute('data-checked')
- expect(customOption).not.toHaveAttribute('data-checked')
+ expect(defaultOption).toHaveAttribute('aria-checked', 'true')
+ expect(customOption).toHaveAttribute('aria-checked', 'false')
await user.click(customOption)
- expect(defaultOption).not.toHaveAttribute('data-checked')
- expect(customOption).toHaveAttribute('data-checked')
+ expect(defaultOption).toHaveAttribute('aria-checked', 'false')
+ expect(customOption).toHaveAttribute('aria-checked', 'true')
})
it('should enable custom prompt input and save the custom prompt when selected', async () => {
const user = userEvent.setup()
- const { onSave } = renderModal()
+ const { onSave } = await renderModal()
- await user.click(
- screen
- .getByText('appDebug.feature.suggestedQuestionsAfterAnswer.modal.customPromptOption')
- .closest('button')!,
- )
+ await user.click(screen.getByRole('radio', { name: /modal.customPromptOption/ }))
const textarea = screen.getByPlaceholderText(
'appDebug.feature.suggestedQuestionsAfterAnswer.modal.promptPlaceholder',
)
expect(textarea).toHaveAttribute('maxLength', '1000')
- fireEvent.change(textarea, { target: { value: 'Use a custom follow-up prompt.' } })
+ await user.type(textarea, 'Use a custom follow-up prompt.')
await user.click(screen.getByText(/common\.operation\.save/))
@@ -196,13 +187,9 @@ describe('FollowUpSettingModal', () => {
it('should disable save when custom prompt is selected but empty', async () => {
const user = userEvent.setup()
- renderModal()
+ await renderModal()
- await user.click(
- screen
- .getByText('appDebug.feature.suggestedQuestionsAfterAnswer.modal.customPromptOption')
- .closest('button')!,
- )
+ await user.click(screen.getByRole('radio', { name: /modal.customPromptOption/ }))
expect(screen.getByText(/common\.operation\.save/).closest('button')).toBeDisabled()
})
diff --git a/web/app/components/base/features/new-feature-panel/__tests__/follow-up.browser.spec.tsx b/web/app/components/base/features/new-feature-panel/__tests__/follow-up.browser.spec.tsx
new file mode 100644
index 00000000000..b1db917b96a
--- /dev/null
+++ b/web/app/components/base/features/new-feature-panel/__tests__/follow-up.browser.spec.tsx
@@ -0,0 +1,57 @@
+import { Button } from '@langgenius/dify-ui/button'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { FeaturesProvider } from '../../context'
+import { FollowUp } from '../follow-up'
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
+ useModelListAndDefaultModelAndCurrentProviderAndModel: () => ({ defaultModel: undefined }),
+}))
+vi.mock(
+ '@/app/components/header/account-setting/model-provider-page/model-parameter-modal',
+ () => ({
+ default: () => <div>Model selector</div>,
+ }),
+)
+
+describe('Follow-up settings keyboard access', () => {
+ it('reveals the persistent trigger with keyboard focus and restores visible focus after closing', async () => {
+ // Native focus and CSS visibility prove the card remains usable without hovering it.
+ const screen = await render(
+ <FeaturesProvider features={{ suggested: { enabled: true } }}>
+ <Button>Before feature</Button>
+ <FollowUp />
+ </FeaturesProvider>,
+ )
+ await screen.getByRole('button', { name: 'Before feature' }).click()
+ await userEvent.tab()
+ await expect.element(screen.getByRole('switch')).toHaveFocus()
+ await userEvent.tab()
+ const trigger = screen.getByRole('button', { name: 'common.operation.settings' })
+ await expect.element(trigger).toHaveFocus()
+ expect(trigger.element().checkVisibility({ checkOpacity: true })).toBe(true)
+ await userEvent.keyboard('{Enter}')
+ const dialog = screen.getByRole('dialog')
+ await expect.element(dialog).toBeVisible()
+ await dialog.getByRole('radio', { name: /modal.customPromptOption/ }).click()
+ const prompt = dialog.getByRole('textbox', { name: /modal.customPromptOption/ })
+ await prompt.fill('Next question')
+ await userEvent.keyboard('{ArrowLeft}{ArrowUp}')
+ await expect.element(prompt).toHaveFocus()
+ await expect
+ .element(dialog.getByRole('radio', { name: /modal.customPromptOption/ }))
+ .toBeChecked()
+ await userEvent.keyboard('{Escape}')
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(trigger).toHaveFocus()
+ expect(trigger.element().checkVisibility({ checkOpacity: true })).toBe(true)
+ await userEvent.keyboard('{Enter}')
+ await expect
+ .element(dialog.getByRole('radio', { name: /modal.defaultPromptOption/ }))
+ .toBeChecked()
+ await dialog.getByRole('button', { name: 'common.operation.save' }).click()
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(trigger).toHaveFocus()
+ expect(trigger.element().checkVisibility({ checkOpacity: true })).toBe(true)
+ })
+})
diff --git a/web/app/components/base/features/new-feature-panel/__tests__/follow-up.spec.tsx b/web/app/components/base/features/new-feature-panel/__tests__/follow-up.spec.tsx
index df97de19bd3..46f6dca60f4 100644
--- a/web/app/components/base/features/new-feature-panel/__tests__/follow-up.spec.tsx
+++ b/web/app/components/base/features/new-feature-panel/__tests__/follow-up.spec.tsx
@@ -1,147 +1,80 @@
import type { OnFeaturesChange, SuggestedQuestionsAfterAnswer } from '../../types'
-import { fireEvent, render, screen } from '@testing-library/react'
-import * as React from 'react'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { FeaturesProvider } from '../../context'
-import FollowUp from '../follow-up'
+import { FollowUp } from '../follow-up'
-vi.mock('../follow-up-setting-modal', () => ({
- default: ({
- onSave,
- onCancel,
- }: {
- onSave: (newState: unknown) => void
- onCancel: () => void
- }) => (
- <div data-testid="follow-up-setting-modal">
- <button
- type="button"
- onClick={() =>
- onSave({
- enabled: true,
- prompt: 'test prompt',
- model: {
- provider: 'openai',
- name: 'gpt-4o-mini',
- mode: 'chat',
- completion_params: {
- temperature: 0.7,
- max_tokens: 0,
- top_p: 0,
- echo: false,
- stop: [],
- presence_penalty: 0,
- frequency_penalty: 0,
- },
- },
- })
- }
- >
- save-settings
- </button>
- <button type="button" onClick={onCancel}>
- cancel-settings
- </button>
- </div>
- ),
+vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
+ useModelListAndDefaultModelAndCurrentProviderAndModel: () => ({ defaultModel: undefined }),
}))
-
-const renderWithProvider = (
+vi.mock(
+ '@/app/components/header/account-setting/model-provider-page/model-parameter-modal',
+ () => ({
+ default: () => <div>Model selector</div>,
+ }),
+)
+
+function renderWithProvider(
props: {
disabled?: boolean
onChange?: OnFeaturesChange
suggested?: SuggestedQuestionsAfterAnswer
} = {},
-) => {
+) {
return render(
- <FeaturesProvider
- features={{
- suggested: props.suggested || { enabled: false },
- }}
- >
+ <FeaturesProvider features={{ suggested: props.suggested || { enabled: false } }}>
<FollowUp disabled={props.disabled} onChange={props.onChange} />
</FeaturesProvider>,
)
}
describe('FollowUp', () => {
- it('should render the follow-up feature card', () => {
- renderWithProvider()
-
- expect(screen.getByText(/feature\.suggestedQuestionsAfterAnswer\.title/)).toBeInTheDocument()
- })
-
- it('should render description text', () => {
- renderWithProvider()
-
- expect(
- screen.getByText(/feature\.suggestedQuestionsAfterAnswer\.description/),
- ).toBeInTheDocument()
- })
-
- it('should render a switch toggle', () => {
- renderWithProvider()
-
- expect(screen.getByRole('switch')).toBeInTheDocument()
- })
-
- it('should call onChange when toggled', () => {
+ it('enables the feature before exposing its configuration entry', async () => {
+ const user = userEvent.setup()
const onChange = vi.fn()
renderWithProvider({ onChange })
-
- fireEvent.click(screen.getByRole('switch'))
-
- expect(onChange).toHaveBeenCalledTimes(1)
- })
-
- it('should not throw when onChange is not provided', () => {
- renderWithProvider()
-
- expect(() => fireEvent.click(screen.getByRole('switch'))).not.toThrow()
- })
-
- it('should render edit button when enabled and hovering', () => {
- renderWithProvider({
- suggested: {
- enabled: true,
- },
- })
-
- fireEvent.mouseEnter(
- screen.getByText(/feature\.suggestedQuestionsAfterAnswer\.title/).closest('[class]')!,
- )
-
- expect(screen.getByText(/operation\.settings/)).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.settings' }),
+ ).not.toBeInTheDocument()
+ await user.click(screen.getByRole('switch'))
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ suggested: { enabled: true } }))
+ expect(screen.getByRole('button', { name: 'common.operation.settings' })).toBeInTheDocument()
})
- it('should open settings modal and save follow-up config', () => {
+ it('discards cancelled drafts and reopens the saved custom prompt', async () => {
+ const user = userEvent.setup()
const onChange = vi.fn()
- renderWithProvider({
- onChange,
- suggested: {
- enabled: true,
- },
- })
-
- fireEvent.mouseEnter(
- screen.getByText(/feature\.suggestedQuestionsAfterAnswer\.title/).closest('[class]')!,
- )
- fireEvent.click(screen.getByText(/operation\.settings/))
-
- expect(screen.getByTestId('follow-up-setting-modal')).toBeInTheDocument()
-
- fireEvent.click(screen.getByText('save-settings'))
-
+ renderWithProvider({ onChange, suggested: { enabled: true, prompt: 'Saved prompt' } })
+ const trigger = screen.getByRole('button', { name: 'common.operation.settings' })
+ await user.click(trigger)
+ const prompt = screen.getByRole('textbox', { name: /modal.customPromptOption/ })
+ await user.clear(prompt)
+ await user.type(prompt, 'Discard me')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(onChange).not.toHaveBeenCalled()
+ await user.click(trigger)
+ expect(screen.getByRole('textbox')).toHaveValue('Saved prompt')
+ await user.clear(screen.getByRole('textbox'))
+ await user.type(screen.getByRole('textbox'), 'New prompt')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({
- suggested: expect.objectContaining({
- enabled: true,
- prompt: 'test prompt',
- model: expect.objectContaining({
- provider: 'openai',
- name: 'gpt-4o-mini',
- }),
- }),
+ suggested: expect.objectContaining({ enabled: true, prompt: 'New prompt' }),
}),
)
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(trigger)
+ expect(screen.getByRole('textbox')).toHaveValue('New prompt')
+ })
+
+ it('prevents changes when the feature is readonly', async () => {
+ const user = userEvent.setup()
+ renderWithProvider({ disabled: true, suggested: { enabled: true } })
+ expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
+ const trigger = screen.getByRole('button', { name: 'common.operation.settings' })
+ expect(trigger).toBeDisabled()
+ await user.click(trigger)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/base/features/new-feature-panel/follow-up-setting-modal.tsx b/web/app/components/base/features/new-feature-panel/follow-up-setting-modal.tsx
index 40a830a7ebe..a30a5e42ab3 100644
--- a/web/app/components/base/features/new-feature-panel/follow-up-setting-modal.tsx
+++ b/web/app/components/base/features/new-feature-panel/follow-up-setting-modal.tsx
@@ -1,26 +1,34 @@
import type { AppModelSelectionResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
import type { SuggestedQuestionsAfterAnswer } from '@/app/components/base/features/types'
import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { CompletionParams, ModelModeType } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
-import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { cn } from '@langgenius/dify-ui/cn'
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
import { Field, FieldItem } from '@langgenius/dify-ui/field'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { RadioControl, RadioGroup, RadioItem } from '@langgenius/dify-ui/radio-group'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { produce } from 'immer'
-import { useCallback, useMemo, useState } from 'react'
+import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
import { ModelModeType as ModelModeTypeEnum } from '@/types/app'
-type FollowUpSettingModalProps = {
+type FollowUpSettingsDialogProps = {
data: SuggestedQuestionsAfterAnswer
onSave: (newState: SuggestedQuestionsAfterAnswer) => void
- onCancel: () => void
+ disabled?: boolean
}
const DEFAULT_COMPLETION_PARAMS: CompletionParams = {
@@ -52,7 +60,45 @@ const PROMPT_MODE = {
type PromptMode = (typeof PROMPT_MODE)[keyof typeof PROMPT_MODE]
-const FollowUpSettingModal = ({ data, onSave, onCancel }: FollowUpSettingModalProps) => {
+export function FollowUpSettingsDialog({ data, onSave, disabled }: FollowUpSettingsDialogProps) {
+ const { t } = useTranslation(['appDebug', 'common'])
+ const actionsRef = useRef<DialogActions>(null)
+
+ return (
+ <Dialog actionsRef={actionsRef}>
+ <div className="relative min-h-8">
+ <div className="line-clamp-2 min-h-8 system-xs-regular text-text-tertiary group-focus-within/follow-up:invisible group-hover/follow-up:invisible">
+ {data.model?.name ||
+ t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.defaultModel'], {
+ ns: 'appDebug',
+ })}
+ </div>
+ <DialogTrigger
+ render={
+ <Button
+ disabled={disabled}
+ className="absolute inset-0 w-full opacity-0 group-focus-within/follow-up:opacity-100 group-hover/follow-up:opacity-100"
+ />
+ }
+ >
+ <span aria-hidden className="i-ri-equalizer-2-line size-4" />
+ {t(($) => $['operation.settings'], { ns: 'common' })}
+ </DialogTrigger>
+ </div>
+ <DialogContent className="w-160! max-w-none! p-8! pb-6!">
+ <FollowUpSettingsForm
+ data={data}
+ onSave={(value) => {
+ onSave(value)
+ actionsRef.current?.close()
+ }}
+ />
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function FollowUpSettingsForm({ data, onSave }: Omit<FollowUpSettingsDialogProps, 'disabled'>) {
const { t } = useTranslation(['appDebug', 'common'])
const [model, setModel] = useState(() => getInitialModel(data.model))
const [prompt, setPrompt] = useState(data.prompt || '')
@@ -110,157 +156,158 @@ const FollowUpSettingModal = ({ data, onSave, onCancel }: FollowUpSettingModalPr
const isCustomPromptInvalid = promptMode === PROMPT_MODE.custom && !prompt.trim()
return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onCancel()
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (!isCustomPromptInvalid) handleSave()
}}
>
- <DialogContent className="w-160! max-w-none! p-8! pb-6!">
- <DialogClose
- render={
- <IconButton
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- size="lg"
- className="absolute top-8 right-8"
- >
- <span aria-hidden className="i-ri-close-line size-4" />
- </IconButton>
- }
- />
- <DialogTitle className="pr-8 text-xl font-semibold text-text-primary">
- {t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.title'], { ns: 'appDebug' })}
- </DialogTitle>
- <div className="mt-6 space-y-4">
- <div>
- <div className="mb-1.5 system-sm-semibold-uppercase text-text-secondary">
- {t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.modelLabel'], {
+ <DialogClose
+ render={
+ <IconButton
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ size="lg"
+ className="absolute top-8 right-8"
+ >
+ <span aria-hidden className="i-ri-close-line size-4" />
+ </IconButton>
+ }
+ />
+ <DialogTitle className="pr-8 text-xl font-semibold text-text-primary">
+ {t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.title'], { ns: 'appDebug' })}
+ </DialogTitle>
+ <div className="mt-6 space-y-4">
+ <div>
+ <div className="mb-1.5 system-sm-semibold-uppercase text-text-secondary">
+ {t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.modelLabel'], {
+ ns: 'appDebug',
+ })}
+ </div>
+ <ModelParameterModal
+ popupClassName="w-[520px]!"
+ isAdvancedMode
+ provider={selectedModel.provider}
+ completionParams={selectedModel.completion_params}
+ modelId={selectedModel.name}
+ setModel={handleModelChange}
+ onCompletionParamsChange={handleCompletionParamsChange}
+ hideDebugWithMultipleModel
+ />
+ </div>
+ <Field name="follow_up_prompt_mode" className="contents">
+ <Fieldset
+ render={
+ <RadioGroup<PromptMode>
+ className="flex-col items-stretch gap-3"
+ value={promptMode}
+ onValueChange={setPromptMode}
+ />
+ }
+ >
+ <FieldsetLegend className="mb-1.5 py-0 system-sm-semibold-uppercase text-text-secondary">
+ {t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.promptLabel'], {
ns: 'appDebug',
})}
- </div>
- <ModelParameterModal
- popupClassName="w-[520px]!"
- isAdvancedMode
- provider={selectedModel.provider}
- completionParams={selectedModel.completion_params}
- modelId={selectedModel.name}
- setModel={handleModelChange}
- onCompletionParamsChange={handleCompletionParamsChange}
- hideDebugWithMultipleModel
- />
- </div>
- <Field name="follow_up_prompt_mode" className="contents">
- <Fieldset
- render={
- <RadioGroup<PromptMode>
- className="flex-col items-stretch gap-3"
- value={promptMode}
- onValueChange={setPromptMode}
- />
- }
- >
- <FieldsetLegend className="mb-1.5 py-0 system-sm-semibold-uppercase text-text-secondary">
- {t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.promptLabel'], {
- ns: 'appDebug',
- })}
- </FieldsetLegend>
- <FieldItem>
- <RadioItem<PromptMode>
- value={PROMPT_MODE.default}
- nativeButton
- render={<button type="button" />}
- className="w-full rounded-xl border border-components-option-card-option-border bg-components-option-card-option-bg p-4 text-left transition-colors hover:bg-state-base-hover data-checked:border-components-option-card-option-selected-border data-checked:bg-components-option-card-option-selected-bg data-checked:hover:bg-components-option-card-option-selected-bg"
- >
- <div className="flex items-start justify-between gap-3">
- <div>
- <div className="system-sm-semibold text-text-primary">
- {t(
- ($) =>
- $['feature.suggestedQuestionsAfterAnswer.modal.defaultPromptOption'],
- { ns: 'appDebug' },
- )}
- </div>
- <div className="mt-1 system-xs-regular text-text-tertiary">
- {t(
- ($) =>
- $[
- 'feature.suggestedQuestionsAfterAnswer.modal.defaultPromptOptionDescription'
- ],
- { ns: 'appDebug' },
- )}
- </div>
+ </FieldsetLegend>
+ <FieldItem>
+ <RadioItem<PromptMode>
+ value={PROMPT_MODE.default}
+ nativeButton
+ render={<button type="button" />}
+ className="w-full rounded-xl border border-components-option-card-option-border bg-components-option-card-option-bg p-4 text-left transition-colors hover:bg-state-base-hover data-checked:border-components-option-card-option-selected-border data-checked:bg-components-option-card-option-selected-bg data-checked:hover:bg-components-option-card-option-selected-bg"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <div className="system-sm-semibold text-text-primary">
+ {t(
+ ($) => $['feature.suggestedQuestionsAfterAnswer.modal.defaultPromptOption'],
+ { ns: 'appDebug' },
+ )}
</div>
- <RadioControl aria-hidden="true" />
- </div>
- {promptMode === PROMPT_MODE.default && (
- <div className="mt-3 rounded-lg border border-components-input-border-active bg-components-input-bg-normal px-3 py-2">
- <div className="system-sm-regular wrap-break-word whitespace-pre-wrap text-text-secondary">
- {DEFAULT_FOLLOW_UP_PROMPT}
- </div>
+ <div className="mt-1 system-xs-regular text-text-tertiary">
+ {t(
+ ($) =>
+ $[
+ 'feature.suggestedQuestionsAfterAnswer.modal.defaultPromptOptionDescription'
+ ],
+ { ns: 'appDebug' },
+ )}
</div>
- )}
- </RadioItem>
- </FieldItem>
- <FieldItem>
- <RadioItem<PromptMode>
- value={PROMPT_MODE.custom}
- nativeButton
- render={<button type="button" />}
- className="w-full rounded-xl border border-components-option-card-option-border bg-components-option-card-option-bg p-4 text-left transition-colors hover:bg-state-base-hover data-checked:border-components-option-card-option-selected-border data-checked:bg-components-option-card-option-selected-bg data-checked:hover:bg-components-option-card-option-selected-bg"
- >
- <div className="flex items-start justify-between gap-3">
- <div>
- <div className="system-sm-semibold text-text-primary">
- {t(
- ($) =>
- $['feature.suggestedQuestionsAfterAnswer.modal.customPromptOption'],
- { ns: 'appDebug' },
- )}
- </div>
- <div className="mt-1 system-xs-regular text-text-tertiary">
- {t(
- ($) =>
- $[
- 'feature.suggestedQuestionsAfterAnswer.modal.customPromptOptionDescription'
- ],
- { ns: 'appDebug' },
- )}
- </div>
+ </div>
+ <RadioControl aria-hidden="true" />
+ </div>
+ {promptMode === PROMPT_MODE.default && (
+ <div className="mt-3 rounded-lg border border-components-input-border-active bg-components-input-bg-normal px-3 py-2">
+ <div className="system-sm-regular wrap-break-word whitespace-pre-wrap text-text-secondary">
+ {DEFAULT_FOLLOW_UP_PROMPT}
</div>
- <RadioControl aria-hidden="true" />
</div>
- {promptMode === PROMPT_MODE.custom && (
- <Textarea
- aria-label={t(
+ )}
+ </RadioItem>
+ </FieldItem>
+ <FieldItem
+ className={cn(
+ 'rounded-xl border border-components-option-card-option-border bg-components-option-card-option-bg p-4 transition-colors hover:bg-state-base-hover',
+ promptMode === PROMPT_MODE.custom &&
+ 'border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg hover:bg-components-option-card-option-selected-bg',
+ )}
+ >
+ <RadioItem<PromptMode>
+ value={PROMPT_MODE.custom}
+ nativeButton
+ render={<button type="button" />}
+ className="w-full text-left"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <div className="system-sm-semibold text-text-primary">
+ {t(
($) => $['feature.suggestedQuestionsAfterAnswer.modal.customPromptOption'],
{ ns: 'appDebug' },
)}
- className="mt-3 min-h-32 resize-y border-components-input-border-active bg-components-input-bg-normal"
- value={prompt}
- onValueChange={(value) => setPrompt(value)}
- maxLength={CUSTOM_FOLLOW_UP_PROMPT_MAX_LENGTH}
- placeholder={
- t(
- ($) => $['feature.suggestedQuestionsAfterAnswer.modal.promptPlaceholder'],
- { ns: 'appDebug' },
- ) || ''
- }
- />
+ </div>
+ <div className="mt-1 system-xs-regular text-text-tertiary">
+ {t(
+ ($) =>
+ $[
+ 'feature.suggestedQuestionsAfterAnswer.modal.customPromptOptionDescription'
+ ],
+ { ns: 'appDebug' },
+ )}
+ </div>
+ </div>
+ <RadioControl aria-hidden="true" />
+ </div>
+ </RadioItem>
+ {promptMode === PROMPT_MODE.custom && (
+ <Textarea
+ aria-label={t(
+ ($) => $['feature.suggestedQuestionsAfterAnswer.modal.customPromptOption'],
+ { ns: 'appDebug' },
)}
- </RadioItem>
- </FieldItem>
- </Fieldset>
- </Field>
- </div>
- <div className="mt-6 flex items-center justify-end gap-2">
- <Button onClick={onCancel}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
- <Button variant="primary" disabled={isCustomPromptInvalid} onClick={handleSave}>
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
+ className="mt-3 min-h-32 resize-y border-components-input-border-active bg-components-input-bg-normal"
+ value={prompt}
+ onValueChange={(value) => setPrompt(value)}
+ maxLength={CUSTOM_FOLLOW_UP_PROMPT_MAX_LENGTH}
+ placeholder={
+ t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.promptPlaceholder'], {
+ ns: 'appDebug',
+ }) || ''
+ }
+ />
+ )}
+ </FieldItem>
+ </Fieldset>
+ </Field>
+ </div>
+ <div className="mt-6 flex items-center justify-end gap-2">
+ <DialogClose render={<Button />}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </DialogClose>
+ <Button type="submit" variant="primary" disabled={isCustomPromptInvalid}>
+ {t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ </div>
+ </form>
)
}
-
-export default FollowUpSettingModal
diff --git a/web/app/components/base/features/new-feature-panel/follow-up.tsx b/web/app/components/base/features/new-feature-panel/follow-up.tsx
index 16c243be8d8..f0661950938 100644
--- a/web/app/components/base/features/new-feature-panel/follow-up.tsx
+++ b/web/app/components/base/features/new-feature-panel/follow-up.tsx
@@ -2,15 +2,12 @@ import type {
OnFeaturesChange,
SuggestedQuestionsAfterAnswer,
} from '@/app/components/base/features/types'
-import { Button } from '@langgenius/dify-ui/button'
-import { RiEqualizer2Line } from '@remixicon/react'
import { produce } from 'immer'
-import * as React from 'react'
-import { useCallback, useState } from 'react'
+import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'
import FeatureCard from '@/app/components/base/features/new-feature-panel/feature-card'
-import FollowUpSettingModal from '@/app/components/base/features/new-feature-panel/follow-up-setting-modal'
+import { FollowUpSettingsDialog } from '@/app/components/base/features/new-feature-panel/follow-up-setting-modal'
import { FeatureEnum } from '@/app/components/base/features/types'
type Props = Readonly<{
@@ -18,12 +15,10 @@ type Props = Readonly<{
onChange?: OnFeaturesChange
}>
-const FollowUp = ({ disabled, onChange }: Props) => {
+export function FollowUp({ disabled, onChange }: Props) {
const { t } = useTranslation(['appDebug', 'common'])
const suggested = useFeatures((s) => s.features.suggested)
const featuresStore = useFeaturesStore()
- const [isHovering, setIsHovering] = useState(false)
- const [isShowSettingModal, setIsShowSettingModal] = useState(false)
const handleChange = useCallback(
(type: FeatureEnum, enabled: boolean) => {
@@ -52,19 +47,13 @@ const FollowUp = ({ disabled, onChange }: Props) => {
}
})
setFeatures(newFeatures)
- setIsShowSettingModal(false)
if (onChange) onChange(newFeatures)
},
[featuresStore, onChange],
)
- const handleOpenSettingModal = useCallback(() => {
- if (disabled) return
- setIsShowSettingModal(true)
- }, [disabled])
-
return (
- <>
+ <div className="group/follow-up">
<FeatureCard
icon={
<div className="shrink-0 rounded-lg border-[0.5px] border-divider-subtle bg-util-colors-blue-light-blue-light-500 p-1 shadow-xs">
@@ -77,8 +66,6 @@ const FollowUp = ({ disabled, onChange }: Props) => {
title={t(($) => $['feature.suggestedQuestionsAfterAnswer.title'], { ns: 'appDebug' })}
value={!!suggested?.enabled}
onChange={(state) => handleChange(FeatureEnum.suggested, state)}
- onMouseEnter={() => setIsHovering(true)}
- onMouseLeave={() => setIsHovering(false)}
disabled={disabled}
>
<>
@@ -88,34 +75,10 @@ const FollowUp = ({ disabled, onChange }: Props) => {
</div>
)}
{!!suggested?.enabled && (
- <>
- {!isHovering && (
- <div className="line-clamp-2 min-h-8 system-xs-regular text-text-tertiary">
- {suggested.model?.name ||
- t(($) => $['feature.suggestedQuestionsAfterAnswer.modal.defaultModel'], {
- ns: 'appDebug',
- })}
- </div>
- )}
- {isHovering && (
- <Button className="w-full" onClick={handleOpenSettingModal} disabled={disabled}>
- <RiEqualizer2Line className="size-4" />
- {t(($) => $['operation.settings'], { ns: 'common' })}
- </Button>
- )}
- </>
+ <FollowUpSettingsDialog data={suggested} onSave={handleSave} disabled={disabled} />
)}
</>
</FeatureCard>
- {isShowSettingModal && (
- <FollowUpSettingModal
- data={suggested || { enabled: true }}
- onSave={handleSave}
- onCancel={() => setIsShowSettingModal(false)}
- />
- )}
- </>
+ </div>
)
}
-
-export default FollowUp
diff --git a/web/app/components/base/features/new-feature-panel/index.tsx b/web/app/components/base/features/new-feature-panel/index.tsx
index 76cf9fdae5f..6dcc8bad1ee 100644
--- a/web/app/components/base/features/new-feature-panel/index.tsx
+++ b/web/app/components/base/features/new-feature-panel/index.tsx
@@ -11,7 +11,7 @@ import Citation from '@/app/components/base/features/new-feature-panel/citation'
import ConversationOpener from '@/app/components/base/features/new-feature-panel/conversation-opener'
import { FeaturePanelDrawer } from '@/app/components/base/features/new-feature-panel/feature-panel-drawer'
import FileUpload from '@/app/components/base/features/new-feature-panel/file-upload'
-import FollowUp from '@/app/components/base/features/new-feature-panel/follow-up'
+import { FollowUp } from '@/app/components/base/features/new-feature-panel/follow-up'
import ImageUpload from '@/app/components/base/features/new-feature-panel/image-upload'
import Moderation from '@/app/components/base/features/new-feature-panel/moderation'
import MoreLikeThis from '@/app/components/base/features/new-feature-panel/more-like-this'
diff --git a/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/http/__tests__/panel.spec.tsx
index 283abc3f502..f5d3bb677b7 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 mockAuthorizationModal = vi.hoisted(() => vi.fn())
const mockCurlPanel = vi.hoisted(() => vi.fn())
const mockApiInput = vi.hoisted(() => vi.fn())
const mockKeyValue = vi.hoisted(() => vi.fn())
@@ -44,17 +43,8 @@ vi.mock('../use-config', () => ({
default: (...args: unknown[]) => mockUseConfig(...args),
}))
-vi.mock('../components/authorization', () => ({
- __esModule: true,
- default: (props: {
- nodeId: string
- payload: HttpNodeType['authorization']
- onChange: (value: HttpNodeType['authorization']) => void
- onHide: () => void
- }) => {
- mockAuthorizationModal(props)
- return <div data-testid="authorization-modal">{props.nodeId}</div>
- },
+vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
+ default: () => ({ availableVars: [], availableNodesWithParent: [] }),
}))
vi.mock('../components/curl-panel', () => ({
@@ -169,8 +159,6 @@ describe('http/panel', () => {
const setParams = vi.fn()
const addParam = vi.fn()
const setBody = vi.fn()
- const showAuthorization = vi.fn()
- const hideAuthorization = vi.fn()
const setAuthorization = vi.fn()
const setTimeout = vi.fn()
const showCurlPanel = vi.fn()
@@ -192,9 +180,6 @@ describe('http/panel', () => {
setParams,
addParam,
setBody,
- isShowAuthorization: false,
- showAuthorization,
- hideAuthorization,
setAuthorization,
setTimeout,
isShowCurlPanel: false,
@@ -229,9 +214,6 @@ 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.authorization.authorization'),
- )
await user.click(screen.getByText('workflowIntegrations.nodes.http.curl.title'))
expect(handleMethodChange).toHaveBeenCalledWith(Method.post)
@@ -245,7 +227,6 @@ describe('http/panel', () => {
data: [{ type: 'text', value: '{"hello":"world"}' }],
})
expect(setTimeout).toHaveBeenCalledWith(expect.objectContaining({ connect: 9 }))
- expect(showAuthorization).toHaveBeenCalledTimes(1)
expect(showCurlPanel).toHaveBeenCalledTimes(1)
expect(mockApiInput).toHaveBeenCalledWith(
expect.objectContaining({
@@ -265,10 +246,9 @@ describe('http/panel', () => {
expect(container).toBeEmptyDOMElement()
})
- it('renders auth and curl panels only when writable and toggled on', () => {
+ it('disables authorization and hides the curl panel when read-only', () => {
mockUseConfig.mockReturnValueOnce(
createConfigResult({
- isShowAuthorization: true,
isShowCurlPanel: true,
}),
)
@@ -277,20 +257,24 @@ describe('http/panel', () => {
<Panel id="http-node" data={createData()} panelProps={panelProps} />,
)
- expect(screen.getByTestId('authorization-modal')).toHaveTextContent('http-node')
+ expect(screen.getByRole('button', { name: /authorization.authorization/ })).toBeEnabled()
expect(screen.getByTestId('curl-panel')).toHaveTextContent('http-node')
mockUseConfig.mockReturnValueOnce(
createConfigResult({
readOnly: true,
- isShowAuthorization: true,
isShowCurlPanel: true,
}),
)
rerender(<Panel id="http-node" data={createData()} panelProps={panelProps} />)
- expect(screen.queryByTestId('authorization-modal')).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: /authorization.authorization/ }),
+ ).not.toBeInTheDocument()
+ expect(
+ screen.getByText('workflowIntegrations.nodes.http.authorization.authorization'),
+ ).toBeInTheDocument()
expect(screen.queryByTestId('curl-panel')).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.ts
index cf134b7f16e..3df9aae5936 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
@@ -223,13 +223,9 @@ describe('http/use-config', () => {
headerFieldChange?.('x-token:123')
paramFieldChange?.('size:20')
result.current.setBody({ type: BodyType.rawText, data: 'raw payload' })
- result.current.showAuthorization()
})
- expect(result.current.isShowAuthorization).toBe(true)
-
act(() => {
- result.current.hideAuthorization()
result.current.setAuthorization({
type: AuthorizationType.apiKey,
config: {
@@ -260,7 +256,6 @@ describe('http/use-config', () => {
result.current.handleSSLVerifyChange(false)
})
- expect(result.current.isShowAuthorization).toBe(false)
expect(result.current.isShowCurlPanel).toBe(false)
expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ method: Method.delete }))
expect(mockSetInputs).toHaveBeenCalledWith(
diff --git a/web/app/components/workflow/nodes/http/components/authorization/__tests__/authorization.spec.tsx b/web/app/components/workflow/nodes/http/components/authorization/__tests__/authorization.spec.tsx
new file mode 100644
index 00000000000..c65f756b159
--- /dev/null
+++ b/web/app/components/workflow/nodes/http/components/authorization/__tests__/authorization.spec.tsx
@@ -0,0 +1,148 @@
+import type { Authorization } from '../../../types'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { AuthorizationDialog } from '..'
+import { APIType, AuthorizationType } from '../../../types'
+
+vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
+ default: () => ({ availableVars: [], availableNodesWithParent: [] }),
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/components/input-support-select-var', () => ({
+ default: ({ value, onChange }: { value: string; onChange: (value: string) => void }) => (
+ <input aria-label="API key" value={value} onChange={(event) => onChange(event.target.value)} />
+ ),
+}))
+
+const initialAuthorization: Authorization = {
+ type: AuthorizationType.apiKey,
+ config: { type: APIType.custom, header: 'X-Original', api_key: 'original-key' },
+}
+
+function AuthorizationSettings({ onSave }: { onSave: (value: Authorization) => void }) {
+ const [authorization, setAuthorization] = useState(initialAuthorization)
+
+ return (
+ <AuthorizationDialog
+ nodeId="http-node"
+ payload={authorization}
+ readOnly={false}
+ onChange={(value) => {
+ onSave(value)
+ setAuthorization(value)
+ }}
+ />
+ )
+}
+
+const triggerName = /nodes.http.authorization.authorization/
+const headerName = /nodes.http.authorization.header/
+
+async function expectClosed() {
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+}
+
+describe('HTTP authorization dialog', () => {
+ it('discards a cancelled draft and saves only the next confirmed draft', async () => {
+ const user = userEvent.setup()
+ const onSave = vi.fn()
+ render(<AuthorizationSettings onSave={onSave} />)
+
+ await user.click(screen.getByRole('button', { name: triggerName }))
+ await user.clear(screen.getByRole('textbox', { name: headerName }))
+ await user.type(screen.getByRole('textbox', { name: headerName }), 'X-Cancelled')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await expectClosed()
+ expect(onSave).not.toHaveBeenCalled()
+
+ await user.click(screen.getByRole('button', { name: triggerName }))
+ expect(screen.getByRole('textbox', { name: headerName })).toHaveValue('X-Original')
+ await user.clear(screen.getByRole('textbox', { name: headerName }))
+ await user.type(screen.getByRole('textbox', { name: headerName }), 'X-Saved')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ await expectClosed()
+ expect(onSave).toHaveBeenCalledExactlyOnceWith({
+ ...initialAuthorization,
+ config: { ...initialAuthorization.config, header: 'X-Saved' },
+ })
+
+ await user.click(screen.getByRole('button', { name: triggerName }))
+ expect(screen.getByRole('textbox', { name: headerName })).toHaveValue('X-Saved')
+ })
+
+ it('saves a header through the form submit button when Enter is pressed', async () => {
+ const user = userEvent.setup()
+ const onSave = vi.fn()
+ render(<AuthorizationSettings onSave={onSave} />)
+
+ await user.click(screen.getByRole('button', { name: triggerName }))
+ await user.clear(screen.getByRole('textbox', { name: headerName }))
+ await user.type(screen.getByRole('textbox', { name: headerName }), 'X-Enter{Enter}')
+ await expectClosed()
+ expect(onSave).toHaveBeenCalledExactlyOnceWith({
+ ...initialAuthorization,
+ config: { ...initialAuthorization.config, header: 'X-Enter' },
+ })
+ })
+
+ it('ends the editable session when the node becomes read-only', async () => {
+ const user = userEvent.setup()
+ const onSave = vi.fn()
+ const { rerender } = render(
+ <AuthorizationDialog
+ nodeId="http-node"
+ payload={initialAuthorization}
+ readOnly={false}
+ onChange={onSave}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: triggerName }))
+ await user.clear(screen.getByRole('textbox', { name: headerName }))
+ await user.type(screen.getByRole('textbox', { name: headerName }), 'X-Discarded')
+ rerender(
+ <AuthorizationDialog
+ nodeId="http-node"
+ payload={initialAuthorization}
+ readOnly
+ onChange={onSave}
+ />,
+ )
+ await expectClosed()
+ expect(screen.queryByRole('button', { name: triggerName })).not.toBeInTheDocument()
+ expect(onSave).not.toHaveBeenCalled()
+
+ rerender(
+ <AuthorizationDialog
+ nodeId="http-node"
+ payload={initialAuthorization}
+ readOnly={false}
+ onChange={onSave}
+ />,
+ )
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: triggerName }))
+ expect(screen.getByRole('textbox', { name: headerName })).toHaveValue('X-Original')
+ })
+
+ it('does not open for a read-only node', async () => {
+ const user = userEvent.setup()
+ const onSave = vi.fn()
+ render(
+ <AuthorizationDialog
+ nodeId="http-node"
+ payload={initialAuthorization}
+ readOnly
+ onChange={onSave}
+ />,
+ )
+
+ expect(screen.queryByRole('button', { name: triggerName })).not.toBeInTheDocument()
+ await user.click(
+ screen.getByText('workflowIntegrations.nodes.http.authorization.authorization'),
+ )
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(onSave).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/app/components/workflow/nodes/http/components/authorization/index.tsx b/web/app/components/workflow/nodes/http/components/authorization/index.tsx
index 250d4023d79..79336d6f05c 100644
--- a/web/app/components/workflow/nodes/http/components/authorization/index.tsx
+++ b/web/app/components/workflow/nodes/http/components/authorization/index.tsx
@@ -1,14 +1,20 @@
'use client'
-import type { FC } from 'react'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
+import type { ReactElement } from 'react'
import type { Authorization as AuthorizationPayloadType } from '../../types'
import type { Var } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
import { Input } from '@langgenius/dify-ui/input'
import { produce } from 'immer'
-import * as React from 'react'
-import { useCallback, useId, useState } from 'react'
+import { useCallback, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import InputSupportSelectVar from '@/app/components/workflow/nodes/_base/components/input-support-select-var'
import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'
@@ -18,15 +24,14 @@ import RadioGroup from './radio-group'
const i18nPrefix = 'nodes.http.authorization'
-type Props = Readonly<{
+type AuthorizationDialogProps = Readonly<{
nodeId: string
payload: AuthorizationPayloadType
onChange: (payload: AuthorizationPayloadType) => void
- isShow: boolean
- onHide: () => void
+ readOnly: boolean
}>
-const Field = ({
+function Field({
title,
isRequired,
children,
@@ -34,9 +39,9 @@ const Field = ({
}: {
title: string
isRequired?: boolean
- children: React.JSX.Element
+ children: ReactElement
htmlFor?: string
-}) => {
+}) {
return (
<div>
<div className="text-[13px] leading-8 font-medium text-text-secondary">
@@ -48,7 +53,12 @@ const Field = ({
)
}
-const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide }) => {
+function AuthorizationForm({
+ nodeId,
+ payload,
+ onChange,
+ onSaved,
+}: Omit<AuthorizationDialogProps, 'readOnly'> & { onSaved: () => void }) {
const { t } = useTranslation(['common', 'workflowIntegrations'])
const headerId = useId()
@@ -62,7 +72,7 @@ const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide })
},
})
- const [tempPayload, setTempPayload] = React.useState<AuthorizationPayloadType>(payload)
+ const [tempPayload, setTempPayload] = useState<AuthorizationPayloadType>(payload)
const handleAuthTypeChange = useCallback(
(type: string) => {
const newPayload = produce(tempPayload, (draft: AuthorizationPayloadType) => {
@@ -129,122 +139,153 @@ const Authorization: FC<Props> = ({ nodeId, payload, onChange, isShow, onHide })
[tempPayload, setTempPayload],
)
- const handleConfirm = useCallback(() => {
- onChange(tempPayload)
- onHide()
- }, [tempPayload, onChange, onHide])
return (
- <Dialog
- open={isShow}
- onOpenChange={(open) => {
- if (!open) onHide()
- }}
- >
- <DialogContent className="border-none text-left align-middle">
- <DialogTitle className="title-2xl-semi-bold text-text-primary">
- {t(($) => $[`${i18nPrefix}.authorization`], { ns: 'workflowIntegrations' })}
- </DialogTitle>
-
- <form
- onSubmit={(event) => {
- event.preventDefault()
- handleConfirm()
- }}
- >
- <div className="space-y-2">
- <Field
- title={t(($) => $[`${i18nPrefix}.authorizationType`], { ns: 'workflowIntegrations' })}
- >
- <RadioGroup
- options={[
- {
- value: AuthorizationType.none,
- label: t(($) => $[`${i18nPrefix}.no-auth`], { ns: 'workflowIntegrations' }),
- },
- {
- value: AuthorizationType.apiKey,
- label: t(($) => $[`${i18nPrefix}.api-key`], { ns: 'workflowIntegrations' }),
- },
- ]}
- value={tempPayload.type}
- onChange={handleAuthTypeChange}
- />
- </Field>
-
- {tempPayload.type === AuthorizationType.apiKey && (
- <>
- <Field
- title={t(($) => $[`${i18nPrefix}.auth-type`], { ns: 'workflowIntegrations' })}
- >
- <RadioGroup
- options={[
- {
- value: APIType.basic,
- label: t(($) => $[`${i18nPrefix}.basic`], { ns: 'workflowIntegrations' }),
- },
- {
- value: APIType.bearer,
- label: t(($) => $[`${i18nPrefix}.bearer`], { ns: 'workflowIntegrations' }),
- },
- {
- value: APIType.custom,
- label: t(($) => $[`${i18nPrefix}.custom`], { ns: 'workflowIntegrations' }),
- },
- ]}
- value={tempPayload.config?.type || APIType.basic}
- onChange={handleAuthAPITypeChange}
- />
- </Field>
- {tempPayload.config?.type === APIType.custom && (
- <Field
- htmlFor={headerId}
- title={t(($) => $[`${i18nPrefix}.header`], { ns: 'workflowIntegrations' })}
- isRequired
- >
- <Input
- id={headerId}
- name="header"
- value={tempPayload.config?.header || ''}
- onValueChange={handleAPIKeyOrHeaderChange('header')}
- />
- </Field>
- )}
+ <>
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(($) => $[`${i18nPrefix}.authorization`], { ns: 'workflowIntegrations' })}
+ </DialogTitle>
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ onChange(tempPayload)
+ onSaved()
+ }}
+ >
+ <div className="space-y-2">
+ <Field
+ title={t(($) => $[`${i18nPrefix}.authorizationType`], { ns: 'workflowIntegrations' })}
+ >
+ <RadioGroup
+ options={[
+ {
+ value: AuthorizationType.none,
+ label: t(($) => $[`${i18nPrefix}.no-auth`], { ns: 'workflowIntegrations' }),
+ },
+ {
+ value: AuthorizationType.apiKey,
+ label: t(($) => $[`${i18nPrefix}.api-key`], { ns: 'workflowIntegrations' }),
+ },
+ ]}
+ value={tempPayload.type}
+ onChange={handleAuthTypeChange}
+ />
+ </Field>
+
+ {tempPayload.type === AuthorizationType.apiKey && (
+ <>
+ <Field title={t(($) => $[`${i18nPrefix}.auth-type`], { ns: 'workflowIntegrations' })}>
+ <RadioGroup
+ options={[
+ {
+ value: APIType.basic,
+ label: t(($) => $[`${i18nPrefix}.basic`], { ns: 'workflowIntegrations' }),
+ },
+ {
+ value: APIType.bearer,
+ label: t(($) => $[`${i18nPrefix}.bearer`], { ns: 'workflowIntegrations' }),
+ },
+ {
+ value: APIType.custom,
+ label: t(($) => $[`${i18nPrefix}.custom`], { ns: 'workflowIntegrations' }),
+ },
+ ]}
+ value={tempPayload.config?.type || APIType.basic}
+ onChange={handleAuthAPITypeChange}
+ />
+ </Field>
+ {tempPayload.config?.type === APIType.custom && (
<Field
- title={t(($) => $[`${i18nPrefix}.api-key-title`], { ns: 'workflowIntegrations' })}
+ htmlFor={headerId}
+ title={t(($) => $[`${i18nPrefix}.header`], { ns: 'workflowIntegrations' })}
isRequired
>
- <div className="flex">
- <InputSupportSelectVar
- instanceId="http-api-key"
- className={cn(
- isFocus
- ? 'border-components-input-border-active bg-components-input-bg-active shadow-xs'
- : 'border-components-input-border-hover bg-components-input-bg-normal',
- 'w-0 grow rounded-lg border px-3 py-1.5',
- )}
- value={tempPayload.config?.api_key || ''}
- onChange={handleAPIKeyChange}
- nodesOutputVars={availableVars}
- availableNodes={availableNodesWithParent}
- onFocusChange={setIsFocus}
- placeholder={' '}
- placeholderClassName="leading-[21px]!"
- />
- </div>
+ <Input
+ id={headerId}
+ name="header"
+ value={tempPayload.config?.header || ''}
+ onValueChange={handleAPIKeyOrHeaderChange('header')}
+ />
</Field>
- </>
- )}
- </div>
- <div className="mt-6 flex justify-end space-x-2">
- <Button onClick={onHide}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
- <Button variant="primary" type="submit">
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </div>
- </form>
+ )}
+
+ <Field
+ title={t(($) => $[`${i18nPrefix}.api-key-title`], { ns: 'workflowIntegrations' })}
+ isRequired
+ >
+ <div className="flex">
+ <InputSupportSelectVar
+ instanceId="http-api-key"
+ className={cn(
+ isFocus
+ ? 'border-components-input-border-active bg-components-input-bg-active shadow-xs'
+ : 'border-components-input-border-hover bg-components-input-bg-normal',
+ 'w-0 grow rounded-lg border px-3 py-1.5',
+ )}
+ value={tempPayload.config?.api_key || ''}
+ onChange={handleAPIKeyChange}
+ nodesOutputVars={availableVars}
+ availableNodes={availableNodesWithParent}
+ onFocusChange={setIsFocus}
+ placeholder={' '}
+ placeholderClassName="leading-[21px]!"
+ />
+ </div>
+ </Field>
+ </>
+ )}
+ </div>
+ <div className="mt-6 flex justify-end space-x-2">
+ <DialogClose render={<Button />}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </DialogClose>
+ <Button variant="primary" type="submit">
+ {t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ </div>
+ </form>
+ </>
+ )
+}
+
+export function AuthorizationDialog({
+ nodeId,
+ payload,
+ onChange,
+ readOnly,
+}: AuthorizationDialogProps) {
+ const { t } = useTranslation(['workflowIntegrations'])
+ const actionsRef = useRef<DialogActions>(null)
+ const label = (
+ <span className="text-xs font-medium text-text-tertiary">
+ {t(($) => $[`${i18nPrefix}.authorization`])}
+ <span className="ml-1 text-text-secondary">
+ {t(($) => $[`${i18nPrefix}.${payload.type}`])}
+ </span>
+ </span>
+ )
+
+ if (readOnly) {
+ return <div className="flex h-6 items-center rounded-md px-2">{label}</div>
+ }
+
+ 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:outline-2 focus-visible:outline-offset-2 focus-visible:outline-state-accent-solid">
+ <span
+ aria-hidden
+ className="i-custom-vender-line-general-settings-01 size-3 text-text-tertiary"
+ />
+ {label}
+ </DialogTrigger>
+ <DialogContent className="border-none text-left align-middle">
+ <AuthorizationForm
+ nodeId={nodeId}
+ payload={payload}
+ onChange={onChange}
+ onSaved={() => actionsRef.current?.close()}
+ />
</DialogContent>
</Dialog>
)
}
-export default React.memo(Authorization)
diff --git a/web/app/components/workflow/nodes/http/panel.tsx b/web/app/components/workflow/nodes/http/panel.tsx
index 4e3da5f870a..567746d4d6c 100644
--- a/web/app/components/workflow/nodes/http/panel.tsx
+++ b/web/app/components/workflow/nodes/http/panel.tsx
@@ -9,7 +9,7 @@ import Field from '@/app/components/workflow/nodes/_base/components/field'
import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'
import Split from '@/app/components/workflow/nodes/_base/components/split'
import ApiInput from './components/api-input'
-import AuthorizationModal from './components/authorization'
+import { AuthorizationDialog } from './components/authorization'
import CurlPanel from './components/curl-panel'
import EditBody from './components/edit-body'
import KeyValue from './components/key-value'
@@ -34,9 +34,6 @@ const Panel: FC<NodePanelProps<HttpNodeType>> = ({ id, data }) => {
setParams,
addParam,
setBody,
- isShowAuthorization,
- showAuthorization,
- hideAuthorization,
setAuthorization,
setTimeout,
isShowCurlPanel,
@@ -56,30 +53,12 @@ const Panel: FC<NodePanelProps<HttpNodeType>> = ({ id, data }) => {
required
operations={
<div className="flex">
- <div
- onClick={showAuthorization}
- 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-general-settings-01 size-3 text-text-tertiary"
- />
- )}
- <div className="text-xs font-medium text-text-tertiary">
- {t(($) => $[`${i18nPrefix}.authorization.authorization`], {
- ns: 'workflowIntegrations',
- })}
- <span className="ml-1 text-text-secondary">
- {t(($) => $[`${i18nPrefix}.authorization.${inputs.authorization.type}`], {
- ns: 'workflowIntegrations',
- })}
- </span>
- </div>
- </div>
+ <AuthorizationDialog
+ nodeId={id}
+ payload={inputs.authorization}
+ onChange={setAuthorization}
+ readOnly={readOnly}
+ />
<div
onClick={showCurlPanel}
className={cn(
@@ -147,15 +126,6 @@ const Panel: FC<NodePanelProps<HttpNodeType>> = ({ id, data }) => {
</div>
<Split />
<Timeout nodeId={id} readonly={readOnly} payload={inputs.timeout} onChange={setTimeout} />
- {isShowAuthorization && !readOnly && (
- <AuthorizationModal
- nodeId={id}
- isShow
- onHide={hideAuthorization}
- payload={inputs.authorization}
- onChange={setAuthorization}
- />
- )}
<Split />
<div className="">
<OutputVars>
diff --git a/web/app/components/workflow/nodes/http/use-config.ts b/web/app/components/workflow/nodes/http/use-config.ts
index 032267bfe59..61b29bf5c2b 100644
--- a/web/app/components/workflow/nodes/http/use-config.ts
+++ b/web/app/components/workflow/nodes/http/use-config.ts
@@ -111,9 +111,6 @@ const useConfig = (id: string, payload: HttpNodeType) => {
[inputs, setInputs],
)
- // authorization
- const [isShowAuthorization, setIsShowAuthorization] = useState(false)
-
const setAuthorization = useCallback(
(authorization: Authorization) => {
const newInputs = produce(inputs, (draft: HttpNodeType) => {
@@ -193,9 +190,6 @@ const useConfig = (id: string, payload: HttpNodeType) => {
// ssl verify
handleSSLVerifyChange,
// authorization
- isShowAuthorization,
- showAuthorization: () => setIsShowAuthorization(true),
- hideAuthorization: () => setIsShowAuthorization(false),
setAuthorization,
setTimeout,
// curl import
diff --git a/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
index 3d50ac77c8b..2f1079cb31d 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
@@ -2,14 +2,15 @@ import type { ReactNode } from 'react'
import type { Var } from '../../../types'
import type { Param, ParameterExtractorNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
+import { ChangeType } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { AppModeEnum } from '@/types/app'
import { BlockEnum } from '../../../types'
-import ExtractParameter from '../components/extract-parameter/list'
-import AddExtractParameter from '../components/extract-parameter/update'
+import { ExtractParameterList } from '../components/extract-parameter/list'
+import { ParameterDialog } from '../components/extract-parameter/update'
import ReasoningModePicker from '../components/reasoning-mode-picker'
import Node from '../node'
import Panel from '../panel'
@@ -198,18 +199,6 @@ vi.mock('@/app/components/app/configuration/config-var/config-modal/field', () =
),
}))
-vi.mock('@/app/components/app/configuration/config-var/config-select', () => ({
- __esModule: true,
- default: ({ options, onChange }: { options: string[]; onChange: (value: string[]) => void }) => (
- <div>
- <div>{options.join(',')}</div>
- <button type="button" onClick={() => onChange([...options, 'published'])}>
- set-options
- </button>
- </div>
- ),
-}))
-
vi.mock('../use-config', () => ({
__esModule: true,
default: vi.fn(),
@@ -323,7 +312,7 @@ describe('parameter-extractor path', () => {
describe('Tool import and parameter editing', () => {
it('should show the empty state for an empty parameter list', () => {
- render(<ExtractParameter readonly={false} list={[]} onChange={vi.fn()} />)
+ render(<ExtractParameterList readonly={false} list={[]} onChange={vi.fn()} />)
expect(
screen.getByText('workflowModels.nodes.parameterExtractor.extractParametersNotSet'),
@@ -333,12 +322,11 @@ describe('parameter-extractor path', () => {
it('should edit and delete parameters from the list', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
- const { container, rerender } = render(
- <ExtractParameter readonly={false} list={[createParam()]} onChange={onChange} />,
+ const { rerender } = render(
+ <ExtractParameterList readonly={false} list={[createParam()]} onChange={onChange} />,
)
- const editAndDeleteButtons = container.querySelectorAll('.cursor-pointer.rounded-md.p-1')
- fireEvent.click(editAndDeleteButtons[0] as HTMLElement)
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit city' }))
fireEvent.change(screen.getByDisplayValue('city'), { target: { value: 'city_name' } })
fireEvent.change(screen.getByDisplayValue('City name'), {
target: { value: 'Updated city description' },
@@ -354,21 +342,20 @@ describe('parameter-extractor path', () => {
required: false,
},
],
- undefined,
+ { type: ChangeType.changeVarName, payload: { beforeKey: 'city', afterKey: 'city_name' } },
)
onChange.mockClear()
rerender(
- <ExtractParameter
+ <ExtractParameterList
readonly={false}
list={[createParam({ name: 'budget' })]}
onChange={onChange}
/>,
)
- const deleteButtons = container.querySelectorAll('.cursor-pointer.rounded-md.p-1')
- fireEvent.click(deleteButtons[1] as HTMLElement)
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete budget' }))
expect(onChange).toHaveBeenCalledWith([])
})
@@ -378,7 +365,7 @@ describe('parameter-extractor path', () => {
const onSave = vi.fn()
render(
- <AddExtractParameter
+ <ParameterDialog
type="edit"
payload={createParam({
name: '',
@@ -388,6 +375,8 @@ describe('parameter-extractor path', () => {
/>,
)
+ await user.click(screen.getByRole('button', { name: /^common.operation.edit/ }))
+
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(onSave).not.toHaveBeenCalled()
@@ -395,7 +384,7 @@ describe('parameter-extractor path', () => {
})
it('should render the add trigger for new parameters', () => {
- render(<AddExtractParameter type="add" onSave={vi.fn()} />)
+ render(<ParameterDialog type="add" onSave={vi.fn()} />)
expect(
screen.getByRole('button', {
@@ -406,9 +395,8 @@ describe('parameter-extractor path', () => {
it('should reject invalid names and reset add modal fields after canceling', async () => {
const user = userEvent.setup()
- const onCancel = vi.fn()
- render(<AddExtractParameter type="add" onSave={vi.fn()} onCancel={onCancel} />)
+ render(<ParameterDialog type="add" onSave={vi.fn()} />)
await user.click(
screen.getByRole('button', {
@@ -431,8 +419,7 @@ describe('parameter-extractor path', () => {
fireEvent.change(descriptionInput, { target: { value: 'Temporary description' } })
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- expect(onCancel).toHaveBeenCalledTimes(1)
- expect(screen.queryByTestId('base-modal')).not.toBeInTheDocument()
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await user.click(
screen.getByRole('button', {
@@ -456,7 +443,7 @@ describe('parameter-extractor path', () => {
const onSave = vi.fn()
render(
- <AddExtractParameter
+ <ParameterDialog
type="edit"
payload={createParam({
name: 'status',
@@ -468,6 +455,8 @@ describe('parameter-extractor path', () => {
/>,
)
+ await user.click(screen.getByRole('button', { name: /^common.operation.edit/ }))
+
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(onSave).not.toHaveBeenCalled()
@@ -479,7 +468,7 @@ describe('parameter-extractor path', () => {
const onSave = vi.fn()
render(
- <AddExtractParameter
+ <ParameterDialog
type="edit"
payload={createParam({
name: 'status',
@@ -491,10 +480,16 @@ describe('parameter-extractor path', () => {
/>,
)
+ await user.click(screen.getByRole('button', { name: /^common.operation.edit/ }))
+
fireEvent.change(screen.getByDisplayValue('status'), {
target: { value: 'approval_status' },
})
- await user.click(screen.getByRole('button', { name: 'set-options' }))
+ await user.click(screen.getByRole('button', { name: 'appDebug.variableConfig.addOption' }))
+ await user.type(
+ screen.getByRole('textbox', { name: 'appDebug.variableConfig.options 2' }),
+ 'published',
+ )
await user.click(await screen.findByRole('button', { name: 'common.operation.save' }))
expect(onSave).toHaveBeenCalledWith(
@@ -505,7 +500,10 @@ describe('parameter-extractor path', () => {
options: ['draft', 'published'],
required: false,
},
- undefined,
+ {
+ type: ChangeType.changeVarName,
+ payload: { beforeKey: 'status', afterKey: 'approval_status' },
+ },
)
})
@@ -514,7 +512,7 @@ describe('parameter-extractor path', () => {
const onSave = vi.fn()
render(
- <AddExtractParameter
+ <ParameterDialog
type="edit"
payload={createParam({
name: 'status',
@@ -524,6 +522,8 @@ describe('parameter-extractor path', () => {
/>,
)
+ await user.click(screen.getByRole('button', { name: /^common.operation.edit/ }))
+
fireEvent.change(screen.getByDisplayValue('status'), {
target: { value: 'approval_status' },
})
@@ -537,7 +537,10 @@ describe('parameter-extractor path', () => {
description: 'Status description',
required: true,
},
- undefined,
+ {
+ type: ChangeType.changeVarName,
+ payload: { beforeKey: 'status', afterKey: 'approval_status' },
+ },
)
})
})
diff --git a/web/app/components/workflow/nodes/parameter-extractor/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/__tests__/panel.spec.tsx
index 001dc97437e..0ca37bf0d30 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/__tests__/panel.spec.tsx
@@ -1,6 +1,6 @@
import type { ParameterExtractorNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
-import { render, screen } from '@testing-library/react'
+import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BlockEnum } from '@/app/components/workflow/types'
import { AppModeEnum } from '@/types/app'
@@ -97,20 +97,6 @@ vi.mock('../components/extract-parameter/import-from-tool', () => ({
),
}))
-vi.mock('../components/extract-parameter/list', () => ({
- __esModule: true,
- default: () => <div>extract-parameter-list</div>,
-}))
-
-vi.mock('../components/extract-parameter/update', () => ({
- __esModule: true,
- default: ({ onSave }: { onSave: (value: unknown) => void }) => (
- <button type="button" onClick={() => onSave({ name: 'city' })}>
- add-parameter
- </button>
- ),
-}))
-
vi.mock('../components/reasoning-mode-picker', () => ({
__esModule: true,
default: ({ onChange }: { onChange: (value: ReasoningModeType) => void }) => (
@@ -224,7 +210,25 @@ describe('parameter-extractor/panel', () => {
await user.click(screen.getByRole('button', { name: 'vision-toggle' }))
await user.click(screen.getByRole('button', { name: 'vision-config' }))
await user.click(screen.getByRole('button', { name: 'import-from-tool' }))
- await user.click(screen.getByRole('button', { name: 'add-parameter' }))
+ await user.click(
+ screen.getByRole('button', {
+ name: 'workflowModels.nodes.parameterExtractor.addExtractParameter',
+ }),
+ )
+ await user.type(
+ screen.getByRole('textbox', {
+ name: 'workflowModels.nodes.parameterExtractor.addExtractParameterContent.name',
+ }),
+ 'budget',
+ )
+ await user.type(
+ screen.getByRole('textbox', {
+ name: 'workflowModels.nodes.parameterExtractor.addExtractParameterContent.description',
+ }),
+ 'Budget amount',
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await user.click(screen.getByRole('button', { name: 'instruction-editor' }))
await user.click(screen.getByRole('button', { name: 'memory-config' }))
await user.click(screen.getByRole('button', { name: 'set-reasoning-mode' }))
@@ -239,7 +243,15 @@ describe('parameter-extractor/panel', () => {
expect(handleVisionResolutionEnabledChange).toHaveBeenCalledWith(true)
expect(handleVisionResolutionChange).toHaveBeenCalledWith({ detail: 'high' })
expect(handleImportFromTool).toHaveBeenCalledWith([{ name: 'budget' }])
- expect(addExtractParameter).toHaveBeenCalledWith({ name: 'city' })
+ expect(addExtractParameter).toHaveBeenCalledExactlyOnceWith(
+ {
+ name: 'budget',
+ type: ParamType.string,
+ description: 'Budget amount',
+ required: false,
+ },
+ undefined,
+ )
expect(handleInstructionChange).toHaveBeenCalledWith('Updated instruction')
expect(handleMemoryChange).toHaveBeenCalledWith({ enabled: true })
expect(handleReasoningModeChange).toHaveBeenCalledWith(ReasoningModeType.functionCall)
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/focus.browser.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/focus.browser.spec.tsx
new file mode 100644
index 00000000000..81b1fb61457
--- /dev/null
+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/focus.browser.spec.tsx
@@ -0,0 +1,53 @@
+import type { Param } from '../../../types'
+import { useState } from 'react'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { ParamType } from '../../../types'
+import { ExtractParameterList } from '../list'
+
+vi.mock('@/app/notifications', () => ({ toast: { error: vi.fn() } }))
+
+function ParametersFixture() {
+ const [parameters, setParameters] = useState<Param[]>([
+ { name: 'city', type: ParamType.string, description: 'City name', required: false },
+ ])
+ return (
+ <div className="w-96 p-4">
+ <button type="button" className="mb-8">
+ Before parameters
+ </button>
+ <ExtractParameterList readonly={false} list={parameters} onChange={setParameters} />
+ </div>
+ )
+}
+
+it('returns visible keyboard focus to the row action after cancel and after renaming', async () => {
+ // Native focus restoration and focus-within visibility require the real browser and CSS.
+ const screen = await render(<ParametersFixture />)
+ await screen.getByRole('button', { name: 'Before parameters' }).click()
+ await userEvent.tab()
+ const edit = screen.getByRole('button', { name: 'common.operation.edit city' })
+ await expect.element(edit).toHaveFocus()
+ expect(edit.element().checkVisibility({ checkOpacity: true })).toBe(true)
+ await userEvent.keyboard('{Enter}')
+ await expect.element(screen.getByRole('dialog')).toBeVisible()
+ await screen.getByRole('button', { name: 'common.operation.cancel' }).click()
+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()
+ await expect.element(edit).toHaveFocus()
+ expect(edit.element().checkVisibility({ checkOpacity: true })).toBe(true)
+ await userEvent.keyboard('{Enter}')
+ await screen
+ .getByRole('textbox', {
+ name: 'workflowModels.nodes.parameterExtractor.addExtractParameterContent.name',
+ })
+ .fill('country')
+ await userEvent.keyboard('{Enter}')
+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()
+ const renamedEdit = screen.getByRole('button', { name: 'common.operation.edit country' })
+ await expect.element(renamedEdit).toHaveFocus()
+ expect(renamedEdit.element().checkVisibility({ checkOpacity: true })).toBe(true)
+ await userEvent.tab()
+ await expect
+ .element(screen.getByRole('button', { name: 'common.operation.delete country' }))
+ .toHaveFocus()
+})
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/item.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/item.spec.tsx
index 364277de564..9784a0cd58b 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/item.spec.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/item.spec.tsx
@@ -1,38 +1,47 @@
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { ParamType } from '../../../types'
-import Item from '../item'
+import { ExtractParameterList } from '../list'
-describe('parameter-extractor/extract-parameter/item', () => {
- it('renders parameter details and forwards edit and delete actions', () => {
- const handleEdit = vi.fn()
- const handleDelete = vi.fn()
- const { container } = render(
- <Item
- payload={{
- name: 'city',
- type: ParamType.string,
- description: 'City name',
- required: true,
- }}
- onEdit={handleEdit}
- onDelete={handleDelete}
- />,
- )
+const parameter = { name: 'city', type: ParamType.string, description: 'City name', required: true }
- expect(screen.getByText('city')).toBeInTheDocument()
- expect(screen.getByText(ParamType.string)).toBeInTheDocument()
- expect(screen.getByText('City name')).toBeInTheDocument()
- expect(
- screen.getByText(
- 'workflowModels.nodes.parameterExtractor.addExtractParameterContent.required',
- ),
- ).toBeInTheDocument()
+describe('ExtractParameterList', () => {
+ it('exposes named edit and delete actions for each parameter', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ render(<ExtractParameterList readonly={false} list={[parameter]} onChange={onChange} />)
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit city' }))
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete city' }))
+ expect(onChange).toHaveBeenCalledExactlyOnceWith([])
+ })
- const actionButtons = container.querySelectorAll('.cursor-pointer.rounded-md.p-1')
- fireEvent.click(actionButtons[0] as HTMLElement)
- fireEvent.click(actionButtons[1] as HTMLElement)
+ it('opens the remaining parameter without a canceled draft after another row is deleted', async () => {
+ const user = userEvent.setup()
+ const country = { ...parameter, name: 'country', description: 'Country name' }
+ const onChange = vi.fn()
+ const { rerender } = render(
+ <ExtractParameterList readonly={false} list={[parameter, country]} onChange={onChange} />,
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit country' }))
+ await user.type(screen.getByRole('textbox', { name: /Content.name$/ }), '_draft')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete city' }))
+ expect(onChange).toHaveBeenCalledExactlyOnceWith([country])
+ rerender(<ExtractParameterList readonly={false} list={[country]} onChange={onChange} />)
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit country' }))
+ expect(screen.getByRole('textbox', { name: /Content.name$/ })).toHaveValue('country')
+ expect(screen.getByRole('textbox', { name: /Content.description$/ })).toHaveValue(
+ 'Country name',
+ )
+ })
- expect(handleEdit).toHaveBeenCalledTimes(1)
- expect(handleDelete).toHaveBeenCalledTimes(1)
+ it('does not expose editing or deletion in readonly mode', () => {
+ render(<ExtractParameterList readonly list={[parameter]} onChange={vi.fn()} />)
+ expect(screen.getByText('City name')).toBeInTheDocument()
+ expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/update.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/update.spec.tsx
index 7d421551dcc..3da8ca2c4ae 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/update.spec.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/update.spec.tsx
@@ -1,9 +1,10 @@
import type { Param } from '../../../types'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { ChangeType } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { ParamType } from '../../../types'
-import Update from '../update'
+import { ParameterDialog } from '../update'
vi.mock('@/app/notifications', () => ({
toast: {
@@ -32,7 +33,7 @@ describe('parameter-extractor/extract-parameter/update', () => {
it('opens from the add trigger and saves a new parameter', async () => {
const handleSave = vi.fn()
- render(<Update type="add" onSave={handleSave} />)
+ render(<ParameterDialog type="add" onSave={handleSave} />)
const existingDialogs = screen.queryAllByRole('dialog').length
@@ -85,7 +86,7 @@ describe('parameter-extractor/extract-parameter/update', () => {
const user = userEvent.setup()
const handleSave = vi.fn()
- render(<Update type="add" onSave={handleSave} />)
+ render(<ParameterDialog type="add" onSave={handleSave} />)
const existingDialogs = screen.queryAllByRole('dialog').length
@@ -119,12 +120,12 @@ describe('parameter-extractor/extract-parameter/update', () => {
).toHaveValue('')
})
- it('renders the edit modal immediately and validates required fields', async () => {
+ it('validates required fields without closing the edit dialog', async () => {
const user = userEvent.setup()
const handleSave = vi.fn()
render(
- <Update
+ <ParameterDialog
type="edit"
payload={createParam({
name: '',
@@ -134,7 +135,9 @@ describe('parameter-extractor/extract-parameter/update', () => {
/>,
)
+ await user.click(screen.getByRole('button', { name: /^common.operation.edit/ }))
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
expect(handleSave).not.toHaveBeenCalled()
await waitFor(() => {
@@ -147,7 +150,7 @@ describe('parameter-extractor/extract-parameter/update', () => {
const handleSave = vi.fn()
render(
- <Update
+ <ParameterDialog
type="edit"
payload={createParam({
type: ParamType.select,
@@ -158,11 +161,49 @@ describe('parameter-extractor/extract-parameter/update', () => {
/>,
)
+ await user.click(screen.getByRole('button', { name: /^common.operation.edit/ }))
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
expect(handleSave).not.toHaveBeenCalled()
await waitFor(() => {
expect(mockToast.error).toHaveBeenCalled()
})
})
+ it('discards canceled drafts and reopens from the latest committed parameter', async () => {
+ const user = userEvent.setup()
+ const { rerender } = render(
+ <ParameterDialog type="edit" payload={createParam()} onSave={vi.fn()} />,
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit city' }))
+ expect(screen.getByRole('dialog', { name: 'common.operation.edit city' })).toBeInTheDocument()
+ await user.type(screen.getByRole('textbox', { name: /Content.name$/ }), '_draft')
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ rerender(
+ <ParameterDialog type="edit" payload={createParam({ name: 'country' })} onSave={vi.fn()} />,
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit country' }))
+ expect(screen.getByRole('textbox', { name: /Content.name$/ })).toHaveValue('country')
+ })
+
+ it('preserves the original rename source after typing and editing other fields, then submits with Enter', async () => {
+ const user = userEvent.setup()
+ const onSave = vi.fn()
+ render(<ParameterDialog type="edit" payload={createParam()} onSave={onSave} />)
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit city' }))
+ const name = screen.getByRole('textbox', { name: /Content.name$/ })
+ await user.type(name, '_name')
+ await user.type(screen.getByRole('textbox', { name: /Content.description$/ }), ' updated')
+ await user.click(name)
+ await user.keyboard('{Enter}')
+ expect(onSave).toHaveBeenCalledExactlyOnceWith(
+ createParam({ name: 'city_name', description: 'City name updated' }),
+ {
+ type: ChangeType.changeVarName,
+ payload: { beforeKey: 'city', afterKey: 'city_name' },
+ },
+ )
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ })
})
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/item.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/item.tsx
index 3b4f3c0e6b1..7bdddc4f126 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/item.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/item.tsx
@@ -1,20 +1,21 @@
'use client'
-import type { FC } from 'react'
import type { Param } from '../../types'
-import { RiDeleteBinLine, RiEditLine } from '@remixicon/react'
-import * as React from 'react'
+import type { MoreInfo } from '@/app/components/workflow/types'
+import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useTranslation } from 'react-i18next'
+import { ParameterDialog } from './update'
const i18nPrefix = 'nodes.parameterExtractor'
type Props = Readonly<{
payload: Param
- onEdit: () => void
+ readonly: boolean
+ onSave: (payload: Param, moreInfo?: MoreInfo) => void
onDelete: () => void
}>
-const Item: FC<Props> = ({ payload, onEdit, onDelete }) => {
- const { t } = useTranslation(['workflowModels'])
+export function ParameterItem({ payload, readonly, onSave, onDelete }: Props) {
+ const { t } = useTranslation(['common', 'workflowModels'])
return (
<div className="group relative rounded-lg bg-components-input-bg-normal px-2.5 py-2 hover:shadow-xs">
@@ -40,19 +41,18 @@ const Item: FC<Props> = ({ payload, onEdit, onDelete }) => {
<div className="mt-0.5 text-xs leading-4.5 font-normal text-text-tertiary">
{payload.description}
</div>
- <div className="absolute top-0 right-0 hidden h-full w-29.75 items-center justify-end space-x-1 rounded-lg bg-linear-to-l from-components-panel-on-panel-item-bg to-background-gradient-mask-transparent pr-1 group-hover:flex">
- <div className="cursor-pointer rounded-md p-1 hover:bg-state-base-hover" onClick={onEdit}>
- <RiEditLine className="size-4 text-text-tertiary" />
+ {!readonly && (
+ <div className="pointer-events-none absolute top-0 right-0 flex h-full w-29.75 items-center justify-end space-x-1 rounded-lg bg-linear-to-l from-components-panel-on-panel-item-bg to-background-gradient-mask-transparent pr-1 opacity-0 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100">
+ <ParameterDialog type="edit" payload={payload} onSave={onSave} />
+ <IconButton
+ aria-label={`${t(($) => $['operation.delete'], { ns: 'common' })} ${payload.name}`}
+ tone="destructive"
+ onClick={onDelete}
+ >
+ <span aria-hidden="true" className="i-ri-delete-bin-line size-4" />
+ </IconButton>
</div>
-
- <div
- className="group shrink-0 cursor-pointer rounded-md p-1 hover:bg-state-destructive-hover!"
- onClick={onDelete}
- >
- <RiDeleteBinLine className="size-4 text-text-tertiary group-hover:text-text-destructive" />
- </div>
- </div>
+ )}
</div>
)
}
-export default React.memo(Item)
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/list.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/list.tsx
index 70bd9c8d553..532043bf535 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/list.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/list.tsx
@@ -1,13 +1,10 @@
'use client'
-import type { FC } from 'react'
import type { Param } from '../../types'
import type { MoreInfo } from '@/app/components/workflow/types'
-import * as React from 'react'
-import { useCallback, useState } from 'react'
+import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import ListNoDataPlaceholder from '../../../_base/components/list-no-data-placeholder'
-import Item from './item'
-import EditParam from './update'
+import { ParameterItem } from './item'
const i18nPrefix = 'nodes.parameterExtractor'
@@ -17,9 +14,8 @@ type Props = Readonly<{
onChange: (list: Param[], moreInfo?: MoreInfo) => void
}>
-const List: FC<Props> = ({ list, onChange }) => {
+export function ExtractParameterList({ readonly, list, onChange }: Props) {
const { t } = useTranslation(['workflowModels'])
- const [isShowEditModal, setIsShowEditModal] = useState(false)
const handleItemChange = useCallback(
(index: number) => {
@@ -30,21 +26,11 @@ const List: FC<Props> = ({ list, onChange }) => {
return item
})
onChange(newList, moreInfo)
- setIsShowEditModal(false)
}
},
[list, onChange],
)
- const [currEditItemIndex, setCurrEditItemIndex] = useState<number>(-1)
-
- const handleItemEdit = useCallback((index: number) => {
- return () => {
- setCurrEditItemIndex(index)
- setIsShowEditModal(true)
- }
- }, [])
-
const handleItemDelete = useCallback(
(index: number) => {
return () => {
@@ -65,22 +51,14 @@ const List: FC<Props> = ({ list, onChange }) => {
return (
<div className="space-y-1">
{list.map((item, index) => (
- <Item
+ <ParameterItem
key={index}
payload={item}
onDelete={handleItemDelete(index)}
- onEdit={handleItemEdit(index)}
+ readonly={readonly}
+ onSave={handleItemChange(index)}
/>
))}
- {isShowEditModal && (
- <EditParam
- type="edit"
- payload={list[currEditItemIndex]}
- onSave={handleItemChange(currEditItemIndex)}
- onCancel={() => setIsShowEditModal(false)}
- />
- )}
</div>
)
}
-export default React.memo(List)
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx
index d114aaef4c0..2ecbc71b519 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx
@@ -1,9 +1,16 @@
'use client'
-import type { FC } from 'react'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
import type { Param } from '../../types'
import type { MoreInfo } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
-import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
+import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
import {
Select,
@@ -16,8 +23,7 @@ import {
} from '@langgenius/dify-ui/select'
import { Switch } from '@langgenius/dify-ui/switch'
import { Textarea } from '@langgenius/dify-ui/textarea'
-import * as React from 'react'
-import { useCallback, useState } from 'react'
+import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Field from '@/app/components/app/configuration/config-var/config-modal/field'
import ConfigSelect from '@/app/components/app/configuration/config-var/config-select'
@@ -37,11 +43,9 @@ const DEFAULT_PARAM: Param = {
}
type Props = Readonly<{
- type: 'add' | 'edit'
- payload?: Param
onSave: (payload: Param, moreInfo?: MoreInfo) => void
- onCancel?: () => void
-}>
+}> &
+ ({ type: 'add'; payload?: never } | { type: 'edit'; payload: Param })
const TYPES = [
ParamType.string,
@@ -53,60 +57,56 @@ const TYPES = [
ParamType.arrayBool,
]
-const AddExtractParameter: FC<Props> = ({ type, payload, onSave, onCancel }) => {
+export function ParameterDialog(props: Props) {
+ const { t } = useTranslation(['common', 'workflowModels'])
+ const actionsRef = useRef<DialogActions>(null)
+ const isAdd = props.type === 'add'
+ const triggerLabel = isAdd
+ ? t(($) => $[`${i18nPrefix}.addExtractParameter`], { ns: 'workflowModels' })
+ : `${t(($) => $['operation.edit'], { ns: 'common' })} ${props.payload.name}`
+
+ return (
+ <Dialog actionsRef={actionsRef}>
+ <DialogTrigger
+ render={
+ <IconButton aria-label={triggerLabel} className={isAdd ? 'mx-1' : undefined}>
+ <span
+ aria-hidden="true"
+ className={isAdd ? 'i-ri-add-line size-4' : 'i-ri-edit-line size-4'}
+ />
+ </IconButton>
+ }
+ />
+ <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">{triggerLabel}</DialogTitle>
+ <ParameterForm {...props} onSaved={() => actionsRef.current?.close()} />
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function ParameterForm({ type, payload, onSave, onSaved }: Props & { onSaved: () => void }) {
const { t } = useTranslation(['appDebug', 'common', 'workflow', 'workflowModels'])
const nameLabel = t(($) => $[`${i18nPrefix}.addExtractParameterContent.name`], {
ns: 'workflowModels',
})
const isAdd = type === 'add'
- const [param, setParam] = useState<Param>(isAdd ? DEFAULT_PARAM : (payload as Param))
- const [renameInfo, setRenameInfo] = useState<MoreInfo | undefined>(undefined)
- const handleParamChange = useCallback(
- (key: string) => {
- return (value: any) => {
- if (key === 'name') {
- const { isValid, errorKey, errorMessageKey } = checkKeys([value], true)
- if (!isValid) {
- toast.error(
- t(($) => $[`varKeyError.${errorMessageKey}`], { ns: 'appDebug', key: errorKey }),
- )
- return
- }
+ const [initialParam] = useState(isAdd ? DEFAULT_PARAM : payload)
+ const [param, setParam] = useState<Param>(initialParam)
+ const handleParamChange =
+ <K extends keyof Param>(key: K) =>
+ (value: Param[K]) => {
+ if (key === 'name') {
+ const { isValid, errorKey, errorMessageKey } = checkKeys([value as string], true)
+ if (!isValid) {
+ toast.error(
+ t(($) => $[`varKeyError.${errorMessageKey}`], { ns: 'appDebug', key: errorKey }),
+ )
+ return
}
- setRenameInfo(
- key === 'name'
- ? {
- type: ChangeType.changeVarName,
- payload: {
- beforeKey: param.name,
- afterKey: value,
- },
- }
- : undefined,
- )
- setParam((prev) => {
- return {
- ...prev,
- [key]: value,
- }
- })
}
- },
- [param.name, t],
- )
-
- const [isShowModal, setIsShowModal] = useState(!isAdd)
-
- const hideModal = useCallback(() => {
- setIsShowModal(false)
- onCancel?.()
- }, [onCancel])
-
- const showAddModal = useCallback(() => {
- if (isAdd) setParam(DEFAULT_PARAM)
-
- setIsShowModal(true)
- }, [isAdd])
+ setParam((prev) => ({ ...prev, [key]: value }))
+ }
const checkValid = useCallback(() => {
let errMessage = ''
@@ -141,134 +141,119 @@ const AddExtractParameter: FC<Props> = ({ type, payload, onSave, onCancel }) =>
return true
}, [param, t])
- const handleSave = useCallback(() => {
+ const handleSave = () => {
if (!checkValid()) return
-
+ const renameInfo: MoreInfo | undefined =
+ !isAdd && initialParam.name !== param.name
+ ? {
+ type: ChangeType.changeVarName,
+ payload: { beforeKey: initialParam.name, afterKey: param.name },
+ }
+ : undefined
onSave(param, renameInfo)
- hideModal()
- }, [checkValid, onSave, param, hideModal, renameInfo])
+ onSaved()
+ }
return (
- <div>
- {isAdd && (
- <button
- type="button"
- aria-label={t(($) => $[`${i18nPrefix}.addExtractParameter`], { ns: 'workflowModels' })}
- className="mx-1 cursor-pointer rounded-md border-none bg-transparent p-1 select-none hover:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"
- onClick={showAddModal}
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ event.stopPropagation()
+ handleSave()
+ }}
+ >
+ <div className="space-y-2">
+ <Field title={nameLabel}>
+ <Input
+ aria-label={nameLabel}
+ value={param.name}
+ onValueChange={(value) => handleParamChange('name')(value)}
+ placeholder={t(($) => $[`${i18nPrefix}.addExtractParameterContent.namePlaceholder`], {
+ ns: 'workflow',
+ })!}
+ />
+ </Field>
+ <Field
+ title={t(($) => $[`${i18nPrefix}.addExtractParameterContent.type`], {
+ ns: 'workflowModels',
+ })}
>
- <span className="i-ri-add-line size-4 text-text-tertiary" aria-hidden="true" />
- </button>
- )}
- {isShowModal && (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) hideModal()
- }}
+ <Select<ParamType>
+ value={param.type}
+ onValueChange={(value) => value && handleParamChange('type')(value)}
+ >
+ <SelectTrigger
+ aria-label={t(($) => $[`${i18nPrefix}.addExtractParameterContent.type`], {
+ ns: 'workflowModels',
+ })}
+ className="w-full capitalize"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {TYPES.map((type) => (
+ <SelectItem<ParamType> key={type} value={type} className="capitalize">
+ <SelectItemText className="capitalize">{type}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ {param.type === ParamType.select && (
+ <Field title={t(($) => $['variableConfig.options'], { ns: 'appDebug' })}>
+ <ConfigSelect options={param.options || []} onChange={handleParamChange('options')} />
+ </Field>
+ )}
+ <Field
+ title={t(($) => $[`${i18nPrefix}.addExtractParameterContent.description`], {
+ ns: 'workflowModels',
+ })}
>
- <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(($) => $[`${i18nPrefix}.addExtractParameter`], { ns: 'workflowModels' })}
- </DialogTitle>
-
- <div>
- <div className="space-y-2">
- <Field title={nameLabel}>
- <Input
- aria-label={nameLabel}
- value={param.name}
- onValueChange={(value) => handleParamChange('name')(value)}
- placeholder={t(
- ($) => $[`${i18nPrefix}.addExtractParameterContent.namePlaceholder`],
- {
- ns: 'workflow',
- },
- )!}
- />
- </Field>
- <Field
- title={t(($) => $[`${i18nPrefix}.addExtractParameterContent.type`], {
- ns: 'workflowModels',
- })}
- >
- <Select<ParamType>
- value={param.type}
- onValueChange={(value) => value && handleParamChange('type')(value)}
- >
- <SelectTrigger className="w-full capitalize">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {TYPES.map((type) => (
- <SelectItem<ParamType> key={type} value={type} className="capitalize">
- <SelectItemText className="capitalize">{type}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Field>
- {param.type === ParamType.select && (
- <Field title={t(($) => $['variableConfig.options'], { ns: 'appDebug' })}>
- <ConfigSelect
- options={param.options || []}
- onChange={handleParamChange('options')}
- />
- </Field>
- )}
- <Field
- title={t(($) => $[`${i18nPrefix}.addExtractParameterContent.description`], {
- ns: 'workflowModels',
- })}
- >
- <Textarea
- aria-label={t(
- ($) => $[`${i18nPrefix}.addExtractParameterContent.description`],
- { ns: 'workflowModels' },
- )}
- value={param.description}
- onValueChange={(value) => handleParamChange('description')(value)}
- placeholder={t(
- ($) => $[`${i18nPrefix}.addExtractParameterContent.descriptionPlaceholder`],
- { ns: 'workflow' },
- )!}
- />
- </Field>
- <Field
- title={t(($) => $[`${i18nPrefix}.addExtractParameterContent.required`], {
- ns: 'workflowModels',
- })}
- >
- <>
- <div className="mb-1.5 text-xs leading-4.5 font-normal text-text-tertiary">
- {t(($) => $[`${i18nPrefix}.addExtractParameterContent.requiredContent`], {
- ns: 'workflowModels',
- })}
- </div>
- <Switch
- size="lg"
- checked={param.required ?? false}
- onCheckedChange={handleParamChange('required')}
- />
- </>
- </Field>
- </div>
- <div className="mt-4 flex justify-end space-x-2">
- <Button className="w-23.75!" onClick={hideModal}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button className="w-23.75!" variant="primary" onClick={handleSave}>
- {isAdd
- ? t(($) => $['operation.add'], { ns: 'common' })
- : t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </div>
+ <Textarea
+ aria-label={t(($) => $[`${i18nPrefix}.addExtractParameterContent.description`], {
+ ns: 'workflowModels',
+ })}
+ value={param.description}
+ onValueChange={(value) => handleParamChange('description')(value)}
+ placeholder={t(
+ ($) => $[`${i18nPrefix}.addExtractParameterContent.descriptionPlaceholder`],
+ { ns: 'workflow' },
+ )!}
+ />
+ </Field>
+ <Field
+ title={t(($) => $[`${i18nPrefix}.addExtractParameterContent.required`], {
+ ns: 'workflowModels',
+ })}
+ >
+ <>
+ <div className="mb-1.5 text-xs leading-4.5 font-normal text-text-tertiary">
+ {t(($) => $[`${i18nPrefix}.addExtractParameterContent.requiredContent`], {
+ ns: 'workflowModels',
+ })}
</div>
- </DialogContent>
- </Dialog>
- )}
- </div>
+ <Switch
+ size="lg"
+ aria-label={t(($) => $[`${i18nPrefix}.addExtractParameterContent.required`], {
+ ns: 'workflowModels',
+ })}
+ checked={param.required ?? false}
+ onCheckedChange={handleParamChange('required')}
+ />
+ </>
+ </Field>
+ </div>
+ <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">
+ {isAdd
+ ? t(($) => $['operation.add'], { ns: 'common' })
+ : t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ </div>
+ </form>
)
}
-export default React.memo(AddExtractParameter)
diff --git a/web/app/components/workflow/nodes/parameter-extractor/panel.tsx b/web/app/components/workflow/nodes/parameter-extractor/panel.tsx
index af1997595a0..92a1f4cd04a 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/panel.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/panel.tsx
@@ -15,8 +15,8 @@ import MemoryConfig from '../_base/components/memory-config'
import Editor from '../_base/components/prompt/editor'
import VarReferencePicker from '../_base/components/variable/var-reference-picker'
import ImportFromTool from './components/extract-parameter/import-from-tool'
-import ExtractParameter from './components/extract-parameter/list'
-import AddExtractParameter from './components/extract-parameter/update'
+import { ExtractParameterList } from './components/extract-parameter/list'
+import { ParameterDialog } from './components/extract-parameter/update'
import ReasoningModePicker from './components/reasoning-mode-picker'
import useConfig from './use-config'
@@ -105,12 +105,12 @@ const Panel: FC<NodePanelProps<ParameterExtractorNodeType>> = ({ id, data }) =>
<div className="flex items-center space-x-1">
{!readOnly && <ImportFromTool onImport={handleImportFromTool} />}
{!readOnly && <div className="h-3 w-px bg-divider-regular"></div>}
- <AddExtractParameter type="add" onSave={addExtractParameter} />
+ <ParameterDialog type="add" onSave={addExtractParameter} />
</div>
) : undefined
}
>
- <ExtractParameter
+ <ExtractParameterList
readonly={readOnly}
list={inputs.parameters || []}
onChange={handleExactParamsChange}