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): constrain slash picker triggers (#39768)

yyha21d2b1201cc
diff --git a/web/app/components/base/prompt-editor/__tests__/hooks.spec.tsx b/web/app/components/base/prompt-editor/__tests__/hooks.spec.tsx
index 5a519a5fbaa..31cdf1196eb 100644
--- a/web/app/components/base/prompt-editor/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/prompt-editor/__tests__/hooks.spec.tsx
@@ -452,5 +452,67 @@ describe('prompt-editor/hooks', () => {
)
expect(result.current('no trigger here', {} as LexicalEditor)).toBeNull()
})
+
+ it('should match a trigger at the start of the text', () => {
+ const { result } = renderHook(() =>
+ useBasicTypeaheadTriggerMatch('/', {
+ minLength: 0,
+ maxLength: 75,
+ requireTriggerBoundary: true,
+ }),
+ )
+
+ expect(result.current('/query', {} as LexicalEditor)).toEqual({
+ leadOffset: 0,
+ matchingString: 'query',
+ replaceableString: '/query',
+ })
+ })
+
+ it('should match a trigger preceded by whitespace', () => {
+ const { result } = renderHook(() =>
+ useBasicTypeaheadTriggerMatch('/', {
+ minLength: 0,
+ maxLength: 75,
+ requireTriggerBoundary: true,
+ }),
+ )
+
+ expect(result.current('prefix /query', {} as LexicalEditor)).toEqual({
+ leadOffset: 7,
+ matchingString: 'query',
+ replaceableString: '/query',
+ })
+ })
+
+ it.each(['https://dict.youdao.com/dictvoice', 'path/to/file'])(
+ 'should not match a trigger preceded by a non-whitespace character in %s',
+ (text) => {
+ const { result } = renderHook(() =>
+ useBasicTypeaheadTriggerMatch('/', {
+ minLength: 0,
+ maxLength: 75,
+ requireTriggerBoundary: true,
+ }),
+ )
+
+ expect(result.current(text, {} as LexicalEditor)).toBeNull()
+ },
+ )
+
+ it('should preserve triggers without a required boundary', () => {
+ const { result } = renderHook(() =>
+ useBasicTypeaheadTriggerMatch('{', {
+ minLength: 0,
+ maxLength: 75,
+ }),
+ )
+
+ expect(result.current('prefix{query', {} as LexicalEditor)).toEqual({
+ leadOffset: 6,
+ matchingString: 'query',
+ replaceableString: '{query',
+ })
+ })
})
})
diff --git a/web/app/components/base/prompt-editor/hooks.ts b/web/app/components/base/prompt-editor/hooks.ts
index d4d2922dccb..f0611c24c28 100644
--- a/web/app/components/base/prompt-editor/hooks.ts
+++ b/web/app/components/base/prompt-editor/hooks.ts
@@ -140,14 +140,19 @@ type TriggerFn = (text: string, editor: LexicalEditor) => MenuTextMatch | null
const escapeForCharacterClass = (value: string) => value.replace(/[[\]\\^-]/g, '\\$&')
export function useBasicTypeaheadTriggerMatch(
trigger: string,
- { minLength = 1, maxLength = 75 }: { minLength?: number; maxLength?: number },
+ {
+ minLength = 1,
+ maxLength = 75,
+ requireTriggerBoundary = false,
+ }: { minLength?: number; maxLength?: number; requireTriggerBoundary?: boolean },
): TriggerFn {
return useCallback(
(text: string) => {
const escapedTrigger = escapeForCharacterClass(trigger)
const validChars = `[^${escapedTrigger}\\n\\r]`
+ const triggerPrefix = requireTriggerBoundary ? '(^|\\s)' : '(.*)'
const TypeaheadTriggerRegex = new RegExp(
- '(.*)(' + `[${escapedTrigger}]` + `((?:${validChars}){0,${maxLength}})` + ')$',
+ `${triggerPrefix}([${escapedTrigger}]((?:${validChars}){0,${maxLength}}))$`,
)
const match = TypeaheadTriggerRegex.exec(text)
if (match !== null) {
@@ -163,6 +168,6 @@ export function useBasicTypeaheadTriggerMatch(
}
return null
},
- [maxLength, minLength, trigger],
+ [maxLength, minLength, requireTriggerBoundary, trigger],
)
}
diff --git a/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx b/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
index 929a0f012be..97d4184f8ee 100644
--- a/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
+++ b/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
@@ -86,6 +86,7 @@ const ComponentPicker = ({
const baseCheckForTriggerMatch = useBasicTypeaheadTriggerMatch(triggerString, {
minLength: 0,
maxLength: 75,
+ requireTriggerBoundary: triggerString === '/',
})
const checkForTriggerMatch = useCallback(
(text: string, editor: LexicalEditor) => {
diff --git a/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
index b5db3f0c203..957befb15a8 100644
--- a/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
@@ -246,6 +246,12 @@ const openSlashMenuFromEditor = async (textbox = screen.getByRole('textbox')) =>
return screen.findByRole('dialog', { name: /agentDetail\.configure\.prompt\.insert\.label/i })
}
+const flushAnimationFrame = async () => {
+ await act(async () => {
+ await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()))
+ })
+}
+
describe('AgentPromptEditor', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -446,6 +452,62 @@ describe('AgentPromptEditor', () => {
// Prompt slash commands should use the Agent Roster category menu and replace it with submenus.
describe('Slash Commands', () => {
+ it('should open the slash menu at the start of the prompt', async () => {
+ renderAgentPromptEditor('/')
+
+ await openSlashMenuFromEditor()
+
+ expect(
+ screen.getByRole('button', { name: /agentDetail\.configure\.skills\.label/i }),
+ ).toBeInTheDocument()
+ })
+
+ it.each(['Review/', 'Use https:/', 'path/to/'])(
+ 'should not open the slash menu when slash follows a non-whitespace character in %s',
+ async (value) => {
+ renderAgentPromptEditor(value)
+
+ syncSlashMenuFromEditor()
+ await flushAnimationFrame()
+
+ expect(
+ screen.queryByRole('dialog', {
+ name: /agentDetail\.configure\.prompt\.insert\.label/i,
+ }),
+ ).not.toBeInTheDocument()
+ },
+ )
+
+ it.each([
+ ['protocol separator', 'Use https://dict.youdao.com/dictvoice', 'Use https:/'.length],
+ [
+ 'path separator',
+ 'Use https://dict.youdao.com/dictvoice',
+ 'Use https://dict.youdao.com/'.length,
+ ],
+ ] as const)('should not open from an existing URL %s', async (_, value, selectionOffset) => {
+ renderAgentPromptEditor(value)
+ const textbox = screen.getByRole('textbox')
+ const textNode = textbox.firstChild
+ expect(textNode).not.toBeNull()
+
+ const range = document.createRange()
+ range.setStart(textNode!, selectionOffset)
+ range.setEnd(textNode!, selectionOffset)
+ const selection = window.getSelection()
+ selection?.removeAllRanges()
+ selection?.addRange(range)
+
+ fireEvent.pointerUp(textbox)
+ await flushAnimationFrame()
+
+ expect(
+ screen.queryByRole('dialog', {
+ name: /agentDetail\.configure\.prompt\.insert\.label/i,
+ }),
+ ).not.toBeInTheDocument()
+ })
+
it('should open category menu, show skill submenu, and append the selected reference', async () => {
const { store, setPromptValue, container } = renderAgentPromptEditor('Review these tenders')
@@ -459,7 +521,7 @@ describe('AgentPromptEditor', () => {
}),
)
- setPromptValue('Review these tenders/')
+ setPromptValue('Review these tenders /')
await openSlashMenuFromEditor()
expect(container).toContainElement(
screen.getByRole('dialog', { name: /agentDetail\.configure\.prompt\.insert\.label/i }),
@@ -478,7 +540,7 @@ describe('AgentPromptEditor', () => {
fireEvent.click(screen.getByRole('button', { name: /Playwright/i }))
expect(store.get(agentComposerPromptAtom)).toBe(
- 'Review these tenders [§skill:playwright:Playwright§]',
+ 'Review these tenders [§skill:playwright:Playwright§] ',
)
await waitFor(() => {
expect(screen.queryByRole('button', { name: /Playwright/i })).not.toBeInTheDocument()
@@ -487,7 +549,7 @@ describe('AgentPromptEditor', () => {
it('should support keyboard navigation and selection in the slash menu', async () => {
const user = userEvent.setup()
- const { store } = renderAgentPromptEditor('Review these tenders/')
+ const { store } = renderAgentPromptEditor('Review these tenders /')
const textbox = screen.getByRole('textbox')
textbox.focus()
@@ -557,7 +619,7 @@ describe('AgentPromptEditor', () => {
await user.keyboard('{Enter}')
expect(store.get(agentComposerPromptAtom)).toBe(
- 'Review these tenders [§skill:playwright:Playwright§]',
+ 'Review these tenders [§skill:playwright:Playwright§] ',
)
await waitFor(() => {
expect(
@@ -568,7 +630,7 @@ describe('AgentPromptEditor', () => {
it('should keep editor focus when selecting slash menu items with a pointer', async () => {
const user = userEvent.setup()
- const { store } = renderAgentPromptEditor('Review these tenders/')
+ const { store } = renderAgentPromptEditor('Review these tenders /')
const textbox = screen.getByRole('textbox')
textbox.focus()
@@ -585,7 +647,7 @@ describe('AgentPromptEditor', () => {
await user.click(screen.getByRole('button', { name: /Playwright/i }))
expect(store.get(agentComposerPromptAtom)).toBe(
- 'Review these tenders [§skill:playwright:Playwright§]',
+ 'Review these tenders [§skill:playwright:Playwright§] ',
)
await waitFor(() => {
expect(
@@ -595,7 +657,7 @@ describe('AgentPromptEditor', () => {
})
it('should close the slash menu with Escape and restore focus to the editor', async () => {
- renderAgentPromptEditor('Review/')
+ renderAgentPromptEditor('Review /')
const textbox = screen.getByRole('textbox')
textbox.focus()
@@ -631,14 +693,14 @@ describe('AgentPromptEditor', () => {
.mockImplementation(() => DOMRect.fromRect({ x: 10, y: 50, width: 500, height: 240 }))
try {
- renderAgentPromptEditor('Review/')
+ renderAgentPromptEditor('Review /')
const textbox = screen.getByRole('textbox')
const textNode = textbox.firstChild
expect(textNode).not.toBeNull()
const range = document.createRange()
- range.setStart(textNode!, 'Review/'.length)
- range.setEnd(textNode!, 'Review/'.length)
+ range.setStart(textNode!, 'Review /'.length)
+ range.setEnd(textNode!, 'Review /'.length)
const selection = window.getSelection()
selection?.removeAllRanges()
selection?.addRange(range)
@@ -815,7 +877,7 @@ describe('AgentPromptEditor', () => {
})
it('should append available provider tool references and add missing tools to the configuration', async () => {
- const { store, setPromptValue } = renderAgentPromptEditor('Research/', { tools: [] })
+ const { store, setPromptValue } = renderAgentPromptEditor('Research /', { tools: [] })
const expectedProviderIcon = `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=workspace-123&filename=duckduckgo.svg`
await openSlashMenuFromEditor()
@@ -831,7 +893,7 @@ describe('AgentPromptEditor', () => {
fireEvent.click(screen.getByRole('button', { name: /DuckDuckGo Search/i }))
expect(store.get(agentComposerPromptAtom)).toBe(
- 'Research [§tool:duckduckgo/ddg_search:DuckDuckGo Search§]',
+ 'Research [§tool:duckduckgo/ddg_search:DuckDuckGo Search§] ',
)
expect(store.get(agentComposerDraftAtom).tools).toEqual([
expect.objectContaining({
@@ -846,7 +908,7 @@ describe('AgentPromptEditor', () => {
}),
])
- setPromptValue('Research/')
+ setPromptValue('Research /')
await openSlashMenuFromEditor()
fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.tools\.label/i }))
fireEvent.click(
@@ -855,7 +917,7 @@ describe('AgentPromptEditor', () => {
}),
)
- expect(store.get(agentComposerPromptAtom)).toBe('Research [§tool:duckduckgo/*:DuckDuckGo§]')
+ expect(store.get(agentComposerPromptAtom)).toBe('Research [§tool:duckduckgo/*:DuckDuckGo§] ')
expect(store.get(agentComposerDraftAtom).tools).toEqual([
expect.objectContaining({
id: 'duckduckgo',
@@ -868,7 +930,7 @@ describe('AgentPromptEditor', () => {
})
it('should close the slash menu when the trailing slash is deleted', async () => {
- const { setPromptValue } = renderAgentPromptEditor('Review/')
+ const { setPromptValue } = renderAgentPromptEditor('Review /')
await openSlashMenuFromEditor()
@@ -891,7 +953,7 @@ describe('AgentPromptEditor', () => {
document.body.append(outsideButton)
try {
- renderAgentPromptEditor('Review/')
+ renderAgentPromptEditor('Review /')
await openSlashMenuFromEditor()
await user.click(outsideButton)
@@ -913,7 +975,7 @@ describe('AgentPromptEditor', () => {
document.body.append(outsideButton)
try {
- renderAgentPromptEditor('Review/')
+ renderAgentPromptEditor('Review /')
await openSlashMenuFromEditor()
expect(
@@ -935,7 +997,7 @@ describe('AgentPromptEditor', () => {
})
it('should reopen slash menu when the cursor is positioned after slash', async () => {
- renderAgentPromptEditor('Review/')
+ renderAgentPromptEditor('Review /')
fireEvent.keyUp(screen.getByRole('textbox'), { key: 'ArrowRight' })
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/options.spec.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/options.spec.ts
index 22640e37de5..efe85d64b77 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/options.spec.ts
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/__tests__/options.spec.ts
@@ -4,7 +4,7 @@ import { insertTokenAtTextRange, replaceTrailingSlashWithToken } from '../option
describe('prompt editor token replacement', () => {
// Replacing the tracked slash range keeps insertion at the user's caret instead of appending.
describe('insertTokenAtTextRange', () => {
- it('should replace a slash in the middle of the prompt and place the cursor after the token', () => {
+ it('should replace a slash in the middle of the prompt and place the cursor after the separator', () => {
expect(
insertTokenAtTextRange(
'Review / before replying',
@@ -13,7 +13,7 @@ describe('prompt editor token replacement', () => {
),
).toEqual({
value: 'Review [§file:file-1:Spec§] before replying',
- cursorOffset: 'Review [§file:file-1:Spec§]'.length,
+ cursorOffset: 'Review [§file:file-1:Spec§] '.length,
})
})
@@ -30,8 +30,8 @@ describe('prompt editor token replacement', () => {
expect(
insertTokenAtTextRange('Review/', { start: 6, end: 99 }, '[§knowledge:kb-1:KB§]'),
).toEqual({
- value: 'Review [§knowledge:kb-1:KB§]',
- cursorOffset: 'Review [§knowledge:kb-1:KB§]'.length,
+ value: 'Review [§knowledge:kb-1:KB§] ',
+ cursorOffset: 'Review [§knowledge:kb-1:KB§] '.length,
})
})
})
@@ -40,13 +40,13 @@ describe('prompt editor token replacement', () => {
describe('replaceTrailingSlashWithToken', () => {
it('should replace a trailing slash', () => {
expect(replaceTrailingSlashWithToken('Review /', '[§file:file-1:Spec§]')).toBe(
- 'Review [§file:file-1:Spec§]',
+ 'Review [§file:file-1:Spec§] ',
)
})
it('should append when no trailing slash exists', () => {
expect(replaceTrailingSlashWithToken('Review', '[§file:file-1:Spec§]')).toBe(
- 'Review [§file:file-1:Spec§]',
+ 'Review [§file:file-1:Spec§] ',
)
})
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
index 6fcbf6322ad..c3cffe9dc49 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
@@ -125,22 +125,29 @@ const getLastTextContent = (node: Node): string => {
return textParts.join('')
}
+const hasSlashTriggerBoundary = (text: string) => {
+ if (!text.endsWith('/')) return false
+
+ const previousCharacter = text.at(-2)
+ return previousCharacter === undefined || /\s/.test(previousCharacter)
+}
+
const isSelectionAfterSlash = (rootElement: HTMLElement | null, fallbackValue: string) => {
- if (!rootElement) return fallbackValue.endsWith('/')
+ if (!rootElement) return hasSlashTriggerBoundary(fallbackValue)
const selection = rootElement.ownerDocument.getSelection()
if (!selection || !selection.isCollapsed || selection.rangeCount === 0)
- return fallbackValue.endsWith('/')
+ return hasSlashTriggerBoundary(fallbackValue)
const anchorNode = selection.anchorNode
if (!anchorNode || !rootElement.contains(anchorNode)) return false
if (anchorNode.nodeType === Node.TEXT_NODE)
- return (anchorNode.textContent ?? '').slice(0, selection.anchorOffset).endsWith('/')
+ return hasSlashTriggerBoundary((anchorNode.textContent ?? '').slice(0, selection.anchorOffset))
const element = anchorNode as Element
const previousChild = element.childNodes.item(selection.anchorOffset - 1)
- return previousChild ? getLastTextContent(previousChild).endsWith('/') : false
+ return previousChild ? hasSlashTriggerBoundary(getLastTextContent(previousChild)) : false
}
/* v8 ignore start -- Lexical selection offsets and DOM range geometry are browser-editor integration glue; user-visible slash insertion behavior is covered by AgentPromptEditor tests. @preserve */
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/options.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/options.ts
index 39a849e1814..c0c7d2dc94b 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/options.ts
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/options.ts
@@ -65,9 +65,9 @@ export const mentionOptions: InsertOption[] = [
]
const appendToken = (value: string, token: string) => {
- if (!value) return token
+ if (!value) return `${token} `
- return `${value}${value.endsWith(' ') || value.endsWith('\n') ? '' : ' '}${token}`
+ return `${value}${value.endsWith(' ') || value.endsWith('\n') ? '' : ' '}${token} `
}
export type TextRange = {
@@ -88,9 +88,9 @@ export const replaceTrailingSlashWithToken = (value: string, token: string) => {
if (!value.endsWith('/')) return appendToken(value, token)
const valueWithoutSlash = value.slice(0, -1)
- if (!valueWithoutSlash) return token
+ if (!valueWithoutSlash) return `${token} `
- return `${valueWithoutSlash}${hasTrailingSpace(valueWithoutSlash) ? '' : ' '}${token}`
+ return `${valueWithoutSlash}${hasTrailingSpace(valueWithoutSlash) ? '' : ' '}${token} `
}
export const insertTokenAtTextRange = (
@@ -103,10 +103,10 @@ export const insertTokenAtTextRange = (
const prefix = value.slice(0, start)
const suffix = value.slice(end)
const beforeToken = prefix && !hasTrailingSpace(prefix) ? ' ' : ''
- const afterToken = suffix && !hasLeadingSpace(suffix) ? ' ' : ''
+ const afterToken = hasLeadingSpace(suffix) ? '' : ' '
return {
value: `${prefix}${beforeToken}${token}${afterToken}${suffix}`,
- cursorOffset: prefix.length + beforeToken.length + token.length + afterToken.length,
+ cursorOffset: prefix.length + beforeToken.length + token.length + 1,
}
}