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.

fix(web): preserve prompt editor focus during variable transform refresh (#44791)

Wu Tianwei34d9694351c6
diff --git a/web/app/components/base/prompt-editor/__tests__/focus.browser.spec.tsx b/web/app/components/base/prompt-editor/__tests__/focus.browser.spec.tsx
new file mode 100644
index 00000000000..eb9ca6dcee6
--- /dev/null
+++ b/web/app/components/base/prompt-editor/__tests__/focus.browser.spec.tsx
@@ -0,0 +1,284 @@
+import type { NodeOutPutVar } from '@/app/components/workflow/types'
+import { QueryClientProvider } from '@tanstack/react-query'
+import { useState } from 'react'
+import { ReactFlowProvider } from 'reactflow'
+import { page, server, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { BlockEnum, VarType } from '@/app/components/workflow/types'
+import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createTestQueryClient } from '@/test/query-client'
+import PromptEditor from '../index'
+
+const initialPrompts = {
+ System: 'System instruction',
+ User: 'User question',
+ Assistant: '',
+}
+const availableVariables: NodeOutPutVar[] = [
+ {
+ nodeId: 'source',
+ title: 'Source',
+ vars: [
+ { variable: 'answer', type: VarType.string },
+ { variable: 'result', type: VarType.string },
+ ],
+ },
+]
+const modifier = server.platform === 'darwin' ? 'Meta' : 'Control'
+
+function PromptFields({
+ values = initialPrompts,
+ clipboardText = '',
+ sourceTitle = 'Source',
+ variablesInitiallyEnabled = true,
+}: {
+ values?: typeof initialPrompts
+ clipboardText?: string
+ sourceTitle?: string
+ variablesInitiallyEnabled?: boolean
+}) {
+ const [queryClient] = useState(() => {
+ const client = createTestQueryClient()
+ seedModelProviderQueries(client)
+ return client
+ })
+ const [prompts, setPrompts] = useState(values)
+ const [focusedPrompt, setFocusedPrompt] = useState<string | null>(null)
+ const [variablesEnabled, setVariablesEnabled] = useState(variablesInitiallyEnabled)
+
+ return (
+ <QueryClientProvider client={queryClient}>
+ <ReactFlowProvider>
+ <EventEmitterContextProvider>
+ {Object.entries(prompts).map(([role, value]) => (
+ <div key={role}>
+ <PromptEditor
+ aria-label={`${role} prompt`}
+ value={value}
+ onChange={(text) => setPrompts((current) => ({ ...current, [role]: text }))}
+ onFocus={() => setFocusedPrompt(role)}
+ onBlur={() => setFocusedPrompt(null)}
+ workflowVariableBlock={{
+ show: variablesEnabled,
+ variables: availableVariables,
+ workflowNodesMap: { source: { title: sourceTitle, type: BlockEnum.Start } },
+ }}
+ />
+ <output aria-label={`${role} value`}>{value}</output>
+ </div>
+ ))}
+ <div>
+ <output aria-label="Focused prompt">{focusedPrompt ?? 'None'}</output>
+ </div>
+ <button type="button">Outside action</button>
+ {!variablesInitiallyEnabled && (
+ <button
+ type="button"
+ aria-pressed={variablesEnabled}
+ onClick={() => setVariablesEnabled(true)}
+ >
+ Enable variables
+ </button>
+ )}
+ <textarea aria-label="Clipboard source" value={clipboardText} readOnly />
+ </EventEmitterContextProvider>
+ </ReactFlowProvider>
+ </QueryClientProvider>
+ )
+}
+
+async function copyPlainText() {
+ await page.getByRole('textbox', { name: 'Clipboard source' }).click()
+ await userEvent.keyboard(`{${modifier}>}a{/${modifier}}`)
+ await userEvent.copy()
+}
+
+async function expectPromptValue(role: keyof typeof initialPrompts, text: string) {
+ const value = page.getByRole('status', { name: `${role} value` })
+ await expect.element(value).toBeInTheDocument()
+ await expect.poll(() => value.element().textContent).toBe(text)
+}
+
+// Native contenteditable selection and blur ordering determine whether Lexical steals focus back.
+it('moves focus from the system prompt to other prompts and outside controls', async () => {
+ await render(<PromptFields />)
+ const system = page.getByRole('textbox', { name: 'System prompt' })
+ const user = page.getByRole('textbox', { name: 'User prompt' })
+ const assistant = page.getByRole('textbox', { name: 'Assistant prompt' })
+ const outside = page.getByRole('button', { name: 'Outside action' })
+
+ await system.click()
+ await userEvent.keyboard('{End}')
+ await user.click()
+ await expect.element(user).toHaveFocus()
+ await userEvent.keyboard('{End} updated')
+ await expect.element(user).toHaveTextContent('User question updated')
+ await expect.element(system).toHaveTextContent('System instruction')
+
+ await assistant.click()
+ await expect.element(assistant).toHaveFocus()
+ await userEvent.keyboard('Assistant answer')
+ await expect.element(assistant).toHaveTextContent('Assistant answer')
+
+ await system.click()
+ await expect.element(system).toHaveFocus()
+ await outside.click()
+ await expect.element(outside).toHaveFocus()
+})
+
+// These scenarios exercise native selection, clipboard events, and history through the real editor.
+it('inserts a workflow variable from the picker and continues typing at the insertion point', async () => {
+ await render(<PromptFields />)
+ const user = page.getByRole('textbox', { name: 'User prompt' })
+
+ await page.getByRole('textbox', { name: 'System prompt' }).click()
+ await user.click()
+ await expect.element(user).toHaveFocus()
+ await userEvent.keyboard('{Home}{ArrowRight>5/}/')
+ await expect.element(page.getByText('answer', { exact: true })).toBeVisible()
+ await userEvent.keyboard('{Enter}')
+
+ await expect.element(user.getByText('answer', { exact: true })).toBeVisible()
+ await expectPromptValue('User', 'User {{#source.answer#}}question')
+ await expect.element(user).toHaveFocus()
+ await userEvent.keyboard('next ')
+ await expectPromptValue('User', 'User {{#source.answer#}}next question')
+ await expectPromptValue('System', 'System instruction')
+
+ await page.getByRole('button', { name: 'Outside action' }).click()
+ await expect.element(page.getByRole('button', { name: 'Outside action' })).toHaveFocus()
+})
+
+it('pastes multiline text with variables over the selection and preserves the typing position', async () => {
+ const pastedText = 'Before {{#source.answer#}} and {{#source.result#}}\nAfter'
+ await render(<PromptFields clipboardText={pastedText} />)
+ const user = page.getByRole('textbox', { name: 'User prompt' })
+
+ await copyPlainText()
+ await user.click()
+ await userEvent.keyboard(`{${modifier}>}a{/${modifier}}`)
+ await userEvent.paste()
+
+ await expect.element(user.getByText('answer', { exact: true })).toBeVisible()
+ await expect.element(user.getByText('result', { exact: true })).toBeVisible()
+ await expectPromptValue('User', pastedText)
+ await expect.element(user).toHaveFocus()
+ await userEvent.keyboard(' continued')
+ await expectPromptValue('User', `${pastedText} continued`)
+ await expectPromptValue('System', 'System instruction')
+})
+
+it('copies rendered workflow variables between prompts without changing their serialized values', async () => {
+ const sourceText = 'Before {{#source.answer#}} and {{#source.result#}} after'
+ await render(<PromptFields values={{ ...initialPrompts, System: sourceText }} />)
+ const system = page.getByRole('textbox', { name: 'System prompt' })
+ const assistant = page.getByRole('textbox', { name: 'Assistant prompt' })
+
+ await expect.element(system.getByText('answer', { exact: true })).toBeVisible()
+ await system.click()
+ await userEvent.keyboard(`{${modifier}>}a{/${modifier}}`)
+ await userEvent.copy()
+ await assistant.click()
+ await expect.element(assistant).toHaveFocus()
+ await userEvent.paste()
+
+ await expect.element(assistant.getByText('answer', { exact: true })).toBeVisible()
+ await expect.element(assistant.getByText('result', { exact: true })).toBeVisible()
+ await expectPromptValue('Assistant', sourceText)
+ await expectPromptValue('System', sourceText)
+ await expect.element(assistant).toHaveFocus()
+ await userEvent.keyboard(' continued')
+ await expectPromptValue('Assistant', `${sourceText} continued`)
+})
+
+it('undoes and redoes variable insertion within the active prompt', async () => {
+ const insertedText = '{{#source.answer#}}'
+ await render(<PromptFields />)
+ const assistant = page.getByRole('textbox', { name: 'Assistant prompt' })
+
+ await assistant.click()
+ await userEvent.keyboard('/')
+ await expect.element(page.getByText('answer', { exact: true })).toBeVisible()
+ await userEvent.keyboard('{Enter}')
+ await expectPromptValue('Assistant', insertedText)
+
+ await userEvent.keyboard(`{${modifier}>}z{/${modifier}}`)
+ await expectPromptValue('Assistant', '/')
+ await expect.element(assistant.getByText('answer', { exact: true })).not.toBeInTheDocument()
+ await expect.element(assistant).toHaveFocus()
+ await userEvent.keyboard(`{${modifier}>}{Shift>}z{/Shift}{/${modifier}}`)
+ await expectPromptValue('Assistant', insertedText)
+ await expect.element(assistant.getByText('answer', { exact: true })).toBeVisible()
+ await expect.element(assistant).toHaveFocus()
+ await expectPromptValue('System', 'System instruction')
+ await expectPromptValue('User', 'User question')
+})
+
+it('uses updated configuration for paste without stealing focus or adding undo steps', async () => {
+ const pastedText = ' {{#source.result#}}'
+ const screen = await render(<PromptFields clipboardText=" updated" />)
+ const user = page.getByRole('textbox', { name: 'User prompt' })
+ const outside = page.getByRole('button', { name: 'Outside action' })
+
+ await copyPlainText()
+ await user.click()
+ await userEvent.keyboard('{End}')
+ // Pasting gives each edit an explicit undo boundary independent of typing coalescence.
+ await userEvent.paste()
+ await expectPromptValue('User', 'User question updated')
+ await outside.click()
+ await expect.element(outside).toHaveFocus()
+
+ await screen.rerender(<PromptFields clipboardText={pastedText} sourceTitle="Renamed source" />)
+ await expect.element(outside).toHaveFocus()
+ await expectPromptValue('User', 'User question updated')
+
+ await copyPlainText()
+ await user.click()
+ await expect.element(user).toHaveFocus()
+ await userEvent.keyboard('{End}')
+ await userEvent.paste()
+ await expect.element(user.getByText('Renamed source', { exact: true })).toBeVisible()
+ await expect.element(user.getByText('result', { exact: true })).toBeVisible()
+ await expectPromptValue('User', `User question updated${pastedText}`)
+ await expect.element(user).toHaveFocus()
+
+ await userEvent.keyboard(`{${modifier}>}z{/${modifier}}`)
+ await expectPromptValue('User', 'User question updated')
+ await userEvent.keyboard(`{${modifier}>}z{/${modifier}}`)
+ await expectPromptValue('User', 'User question')
+ await userEvent.keyboard(`{${modifier}>}{Shift>}z{/Shift}{/${modifier}}`)
+ await expectPromptValue('User', 'User question updated')
+ await userEvent.keyboard(`{${modifier}>}{Shift>}z{/Shift}{/${modifier}}`)
+ await expectPromptValue('User', `User question updated${pastedText}`)
+ await expect.element(user.getByText('Renamed source', { exact: true })).toBeVisible()
+ await expect.element(user).toHaveFocus()
+})
+
+// Registering the plugin after editing must convert existing tokens without restoring its old selection.
+it('enables workflow variables on an existing editor without taking focus from the activating control', async () => {
+ const text = 'User {{#source.answer#}} prompt'
+ await render(
+ <PromptFields values={{ ...initialPrompts, User: text }} variablesInitiallyEnabled={false} />,
+ )
+ const user = page.getByRole('textbox', { name: 'User prompt' })
+ const enable = page.getByRole('button', { name: 'Enable variables' })
+
+ await expect.element(user.getByText('answer', { exact: true })).not.toBeInTheDocument()
+ await user.click()
+ await userEvent.keyboard('{End}')
+ await expect.element(user).toHaveFocus()
+ await enable.click()
+ await expect.element(enable).toHaveAttribute('aria-pressed', 'true')
+
+ await expect.element(user.getByText('answer', { exact: true })).toBeVisible()
+ await expect.element(enable).toHaveFocus()
+ await expectPromptValue('User', text)
+
+ await user.click()
+ await expect.element(user).toHaveFocus()
+ await userEvent.keyboard('{End} continued')
+ await expectPromptValue('User', `${text} continued`)
+ await expectPromptValue('System', 'System instruction')
+})
diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/workflow-variable-block-replacement-block.spec.tsx b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/workflow-variable-block-replacement-block.spec.tsx
index 66e0b2ea187..fad262691b3 100644
--- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/workflow-variable-block-replacement-block.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/__tests__/workflow-variable-block-replacement-block.spec.tsx
@@ -94,12 +94,21 @@ it('replaces multiple variables while retaining surrounding text and variable me
it('uses updated callbacks and node metadata for subsequent replacements and unregisters on unmount', async () => {
const first = vi.fn()
const latest = vi.fn()
+ const firstVarType = () => Type.string
+ const latestVarType = () => Type.number
let update: (value: boolean) => void
let show: (value: boolean) => void
const renamedMap = {
...workflowNodesMap,
'node-1': { ...workflowNodesMap['node-1']!, title: 'Renamed' },
}
+ const renamedVariables: NodeOutPutVar[] = [
+ {
+ nodeId: 'node-1',
+ title: 'Renamed',
+ vars: [{ variable: 'output', type: VarType.number }],
+ },
+ ]
function Fixture() {
const [updated, setUpdated] = useState(false)
const [visible, setVisible] = useState(true)
@@ -108,6 +117,8 @@ it('uses updated callbacks and node metadata for subsequent replacements and unr
return visible ? (
<WorkflowVariableBlockReplacementBlock
workflowNodesMap={updated ? renamedMap : workflowNodesMap}
+ variables={updated ? renamedVariables : variables}
+ getVarType={updated ? latestVarType : firstVarType}
onInsert={updated ? latest : first}
/>
) : null
@@ -122,10 +133,15 @@ it('uses updated callbacks and node metadata for subsequent replacements and unr
setEditorRootText(editor, '{{#node-1.output#}}', (value) => new CustomTextNode(value))
await waitFor(() => expect(getNodeCount(editor, WorkflowVariableBlockNode)).toBe(1))
expect(
- readEditorStateValue(editor, () =>
- $nodesOfType(WorkflowVariableBlockNode)[0]!.getWorkflowNodesMap(),
- ),
- ).toEqual(renamedMap)
+ readEditorStateValue(editor, () => {
+ const node = $nodesOfType(WorkflowVariableBlockNode)[0]!
+ return {
+ map: node.getWorkflowNodesMap(),
+ variables: node.getAvailableVariables(),
+ type: node.getVarType()?.({ nodeId: 'node-1', valueSelector: ['node-1', 'output'] }),
+ }
+ }),
+ ).toEqual({ map: renamedMap, variables: renamedVariables, type: Type.number })
expect(latest).toHaveBeenCalledOnce()
expect(first).not.toHaveBeenCalled()
act(() => show(false))
diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/workflow-variable-block-replacement-block.tsx b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/workflow-variable-block-replacement-block.tsx
index 9d5b2e7321f..54bd8694b21 100644
--- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/workflow-variable-block-replacement-block.tsx
+++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/workflow-variable-block-replacement-block.tsx
@@ -2,7 +2,7 @@ import type { TextNode } from 'lexical'
import type { WorkflowVariableBlockType } from '../../types'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { mergeRegister } from '@lexical/utils'
-import { $applyNodeReplacement } from 'lexical'
+import { $addUpdateTag, $applyNodeReplacement, SKIP_DOM_SELECTION_TAG } from 'lexical'
import { memo, useCallback, useEffect } from 'react'
import { VAR_REGEX as REGEX, resetReg } from '@/config'
import { decoratorTransform } from '../../utils'
@@ -65,7 +65,12 @@ const WorkflowVariableBlockReplacementBlock = ({
useEffect(() => {
resetReg()
- return mergeRegister(editor.registerNodeTransform(CustomTextNode, transformListener))
+ const unregister = mergeRegister(
+ editor.registerNodeTransform(CustomTextNode, transformListener),
+ )
+ // Registering a transform dirties existing text; refreshing variable metadata must preserve focus.
+ editor.update(() => $addUpdateTag(SKIP_DOM_SELECTION_TAG))
+ return unregister
}, [editor, transformListener])
return null