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(workflow): preserve LLM prompts and model changes in collaboration (#42124)

非法操作ecadd45886f1
diff --git a/web/app/components/workflow/collaboration/core/__tests__/collaboration-manager.test.ts b/web/app/components/workflow/collaboration/core/__tests__/collaboration-manager.test.ts
index 4a957c9d1a6..49151ca556e 100644
--- a/web/app/components/workflow/collaboration/core/__tests__/collaboration-manager.test.ts
+++ b/web/app/components/workflow/collaboration/core/__tests__/collaboration-manager.test.ts
@@ -3,11 +3,11 @@ import type {
NodePanelPresenceMap,
NodePanelPresenceUser,
} from '@/app/components/workflow/collaboration/types/collaboration'
-import type { CommonNodeType, Edge, Node } from '@/app/components/workflow/types'
+import type { CommonNodeType, Edge, Node, PromptItem } from '@/app/components/workflow/types'
import { LoroDoc } from 'loro-crdt/base64'
import { Position } from 'reactflow'
import { CollaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'
-import { BlockEnum } from '@/app/components/workflow/types'
+import { BlockEnum, EditionType } from '@/app/components/workflow/types'
import { attachCrdtRuntime } from './test-crdt-runtime'
const NODE_ID = '1760342909316'
@@ -85,10 +85,6 @@ type ParameterExtractorNodeData = {
}
}
-type LLMNodeDataWithUnknownTemplate = Omit<LLMNodeData, 'prompt_template'> & {
- prompt_template: unknown
-}
-
type ManagerDoc = LoroDoc | { commit: () => void }
type CollaborationManagerInternals = {
@@ -566,22 +562,57 @@ describe('CollaborationManager syncNodes', () => {
expect(storedData.variables).toBeUndefined()
})
- it('treats non-array list inputs as empty lists during synchronization', () => {
- const { manager: promptManager, internals: promptInternals } = setupManager()
+ it('preserves completion prompt objects when adding, editing, and reloading nodes', () => {
+ const { manager: promptManager } = setupManager()
+ const prompt: PromptItem = { text: '测试指令', edition_type: EditionType.basic }
+ const baseNode = createLLMNodeSnapshot([])
+ const completionNode = {
+ ...baseNode,
+ data: {
+ ...baseNode.data,
+ model: { ...baseNode.data.model, mode: 'completion' },
+ prompt_template: prompt,
+ },
+ }
- const nodeWithInvalidTemplate = createLLMNodeSnapshot([])
- promptInternals.syncNodes([], [deepClone(nodeWithInvalidTemplate)])
+ promptManager.setNodes([], [completionNode])
+ expect(promptManager.getNodes()[0]).toHaveProperty('data.prompt_template', prompt)
- const mutated = deepClone(nodeWithInvalidTemplate) as Node<LLMNodeDataWithUnknownTemplate>
- mutated.data.prompt_template = 'not-an-array'
+ const updatedPrompt: PromptItem = { ...prompt, text: '修改后的测试指令' }
+ const updatedNode = {
+ ...completionNode,
+ data: { ...completionNode.data, prompt_template: updatedPrompt },
+ }
+ promptManager.setNodes([completionNode], [updatedNode])
+ expect(promptManager.getNodes()[0]).toHaveProperty('data.prompt_template', updatedPrompt)
- promptInternals.syncNodes([deepClone(nodeWithInvalidTemplate)], [mutated])
+ const { manager: reloadedManager } = setupManager()
+ reloadedManager.setNodes([], deepClone(promptManager.getNodes()))
+ expect(reloadedManager.getNodes()[0]).toHaveProperty('data.prompt_template', updatedPrompt)
+ })
- const stored = promptManager
- .getNodes()
- .find((node) => node.id === LLM_NODE_ID) as Node<LLMNodeData>
- expect(Array.isArray(stored.data.prompt_template)).toBe(true)
- expect(stored.data.prompt_template).toHaveLength(0)
+ it('preserves prompt shape when switching between chat and completion models', () => {
+ const { manager: promptManager } = setupManager()
+ const chatNode = createLLMNodeSnapshot([{ id: 'system', role: 'system', text: 'Chat prompt' }])
+ promptManager.setNodes([], [chatNode])
+
+ const completionPrompt: PromptItem = { text: '测试指令', edition_type: EditionType.basic }
+ const completionNode = {
+ ...chatNode,
+ data: {
+ ...chatNode.data,
+ model: { ...chatNode.data.model, mode: 'completion' },
+ prompt_template: completionPrompt,
+ },
+ }
+ promptManager.setNodes([chatNode], [completionNode])
+ expect(promptManager.getNodes()[0]).toHaveProperty('data.prompt_template', completionPrompt)
+
+ promptManager.setNodes([completionNode], [chatNode])
+ expect(promptManager.getNodes()[0]).toHaveProperty(
+ 'data.prompt_template',
+ chatNode.data.prompt_template,
+ )
})
it('updates edges map when edges are added, modified, and removed', () => {
diff --git a/web/app/components/workflow/collaboration/core/collaboration-manager.ts b/web/app/components/workflow/collaboration/core/collaboration-manager.ts
index 016741b4962..dc8c7f6854d 100644
--- a/web/app/components/workflow/collaboration/core/collaboration-manager.ts
+++ b/web/app/components/workflow/collaboration/core/collaboration-manager.ts
@@ -343,7 +343,7 @@ export class CollaborationManager {
}
private populateNodeContainer(container: LoroMap<Record<string, Value>>, node: Node): void {
- const listFields = new Set(['variables', 'prompt_template', 'parameters'])
+ const listFields = new Set(['variables', 'parameters'])
container.set('id', node.id)
container.set('type', node.type)
container.set('position', toLoroValue(node.position))
@@ -392,7 +392,8 @@ export class CollaborationManager {
if (!this.shouldSyncDataKey(key)) return
handledKeys.add(key)
- if (listFields.has(key)) this.syncList(container, key, Array.isArray(value) ? value : [])
+ if (listFields.has(key) || (key === 'prompt_template' && Array.isArray(value)))
+ this.syncList(container, key, Array.isArray(value) ? value : [])
else dataContainer.set(key, toLoroValue(value))
})
diff --git a/web/app/components/workflow/nodes/llm/components/__tests__/config-prompt.spec.tsx b/web/app/components/workflow/nodes/llm/components/__tests__/config-prompt.spec.tsx
index ae68df2dba4..16532c96e5d 100644
--- a/web/app/components/workflow/nodes/llm/components/__tests__/config-prompt.spec.tsx
+++ b/web/app/components/workflow/nodes/llm/components/__tests__/config-prompt.spec.tsx
@@ -1,9 +1,12 @@
import type { PromptItem } from '../../../../types'
+import type { LLMNodeType } from '../../types'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
-import { PromptRole } from '../../../../types'
+import { BlockEnum, EditionType, PromptRole } from '../../../../types'
+import useLLMInputManager from '../../hooks/use-llm-input-manager'
+import useLLMPromptConfig from '../../hooks/use-llm-prompt-config'
import ConfigPrompt from '../config-prompt'
vi.mock('../../../_base/hooks/use-available-var-list', () => ({
@@ -62,6 +65,83 @@ function Fixture({
)
}
+function RemoteModelChangeFixture({ onChange }: { onChange: (inputs: LLMNodeType) => void }) {
+ const [inputs, setInputs] = useState<LLMNodeType>({
+ type: BlockEnum.LLM,
+ title: 'LLM',
+ desc: '',
+ model: {
+ provider: 'openai',
+ name: 'completion-model',
+ mode: 'completion',
+ completion_params: {},
+ },
+ prompt_template: { text: 'Completion instruction', edition_type: EditionType.basic },
+ context: { enabled: false, variable_selector: [] },
+ vision: { enabled: false },
+ })
+ const isChatModel = inputs.model.mode === 'chat'
+ const inputManager = useLLMInputManager({
+ inputs,
+ isChatModel,
+ doSetInputs: (nextInputs) => {
+ onChange(nextInputs)
+ setInputs(nextInputs)
+ },
+ })
+ const promptConfig = useLLMPromptConfig({
+ inputs,
+ inputRef: inputManager.inputRef,
+ setInputs: inputManager.setInputs,
+ isChatModel,
+ isChatMode: true,
+ })
+
+ return (
+ <>
+ <button
+ onClick={() =>
+ setInputs({
+ ...inputs,
+ model: { ...inputs.model, name: 'chat-model', mode: 'chat' },
+ prompt_template: initialPrompts.map(({ role, text }) => ({ role, text })),
+ })
+ }
+ >
+ Receive remote Chat model
+ </button>
+ <output aria-label="Model mode">{inputs.model.mode}</output>
+ <ConfigPrompt
+ readOnly={false}
+ nodeId="llm"
+ filterVar={promptConfig.filterVar}
+ isChatModel={isChatModel}
+ isChatApp
+ payload={inputs.prompt_template}
+ onChange={promptConfig.handlePromptChange}
+ isShowContext={false}
+ hasSetBlockStatus={promptConfig.hasSetBlockStatus}
+ handleAddVariable={promptConfig.handleAddVariable}
+ modelConfig={inputs.model}
+ />
+ </>
+ )
+}
+
+it('retains a remote model change without writing back its default prompts', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn<(inputs: LLMNodeType) => void>()
+ renderWorkflowComponent(<RemoteModelChangeFixture onChange={onChange} />)
+
+ await user.click(screen.getByRole('button', { name: 'Receive remote Chat model' }))
+
+ expect(screen.getByRole('status', { name: 'Model mode' })).toHaveTextContent('chat')
+ expect(onChange).not.toHaveBeenCalled()
+ expect(
+ screen.getAllByRole('textbox').map((editor) => (editor as HTMLTextAreaElement).value),
+ ).toEqual(initialPrompts.map((prompt) => prompt.text))
+})
+
it('reorders messages without moving past the leading system prompt', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
@@ -89,22 +169,28 @@ it('reorders messages without moving past the leading system prompt', async () =
expect(screen.getAllByRole('button', { pressed: false })[1]).toHaveFocus()
})
-it('persists unique IDs for default prompts once and retains them when sorting', async () => {
+it('only writes default prompts without IDs after completing a reorder', async () => {
const user = userEvent.setup()
const onChange = vi.fn<(items: PromptItem | PromptItem[]) => void>()
const initial = initialPrompts.map((item) => ({ role: item.role, text: item.text }))
renderWorkflowComponent(<Fixture onChange={onChange} initial={initial} />)
- expect(onChange).toHaveBeenCalledTimes(1)
- const initialized = onChange.mock.calls[0]![0] as PromptItem[]
- expect(initialized).toEqual(initial.map((item) => ({ ...item, id: expect.any(String) })))
- expect(new Set(initialized.map((item) => item.id)).size).toBe(initial.length)
+ expect(onChange).not.toHaveBeenCalled()
const handle = screen.getAllByRole('button', { pressed: false })[0]!
for (let index = 0; index < 10 && document.activeElement !== handle; index++) await user.tab()
expect(handle).toHaveFocus()
await user.keyboard('{Enter}{ArrowDown}{Escape}')
- expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange).not.toHaveBeenCalled()
await user.keyboard('{Enter}{ArrowDown}{Enter}')
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(
+ [initial[0], initial[2], initial[1]].map((prompt) => ({ ...prompt, id: expect.any(String) })),
+ )
+ const reordered = onChange.mock.lastCall![0] as PromptItem[]
+ expect(new Set(reordered.map((prompt) => prompt.id)).size).toBe(initial.length)
+ expect(
+ screen.getAllByRole('textbox').map((editor) => (editor as HTMLTextAreaElement).value),
+ ).toEqual(['System instruction', 'Assistant answer', 'User question'])
+ await user.keyboard('{Enter}{ArrowUp}{Enter}')
expect(onChange).toHaveBeenCalledTimes(2)
- expect(onChange).toHaveBeenLastCalledWith([initialized[0], initialized[2], initialized[1]])
+ expect(onChange).toHaveBeenLastCalledWith([reordered[0], reordered[2], reordered[1]])
})
diff --git a/web/app/components/workflow/nodes/llm/components/config-prompt.tsx b/web/app/components/workflow/nodes/llm/components/config-prompt.tsx
index 4ed7dff1e5d..d9553a02528 100644
--- a/web/app/components/workflow/nodes/llm/components/config-prompt.tsx
+++ b/web/app/components/workflow/nodes/llm/components/config-prompt.tsx
@@ -56,7 +56,10 @@ const ConfigPrompt: FC<Props> = ({
const workflowStore = useWorkflowStore()
const { setControlPromptEditorRerenderKey } = workflowStore.getState()
const prompts = useMemo(
- () => (isChatModel && Array.isArray(payload) ? payload : []),
+ () =>
+ isChatModel && Array.isArray(payload)
+ ? payload.map((item) => ({ ...item, id: item.id || uuid4() }))
+ : [],
[isChatModel, payload],
)
const keyboardSort = useKeyboardSortable({
@@ -67,11 +70,7 @@ const ConfigPrompt: FC<Props> = ({
getItemLabel: (item) => item.role || '',
})
const payloadWithIds = useMemo(
- () =>
- keyboardSort.items.map((item) => {
- const id = item.id || uuid4()
- return { id, p: { ...item, id } }
- }),
+ () => keyboardSort.items.map((item) => ({ id: item.id, p: item })),
[keyboardSort.items],
)
const { availableVars, availableNodesWithParent } = useAvailableVarList(nodeId, {
@@ -82,7 +81,7 @@ const ConfigPrompt: FC<Props> = ({
const handleChatModePromptChange = useCallback(
(index: number) => {
return (prompt: string) => {
- const newPrompt = produce(payload as PromptItem[], (draft) => {
+ const newPrompt = produce(prompts, (draft) => {
draft[index]![
draft[index]!.edition_type === EditionType.jinja2 ? 'jinja2_text' : 'text'
] = prompt
@@ -90,35 +89,35 @@ const ConfigPrompt: FC<Props> = ({
onChange(newPrompt)
}
},
- [onChange, payload],
+ [onChange, prompts],
)
const handleChatModeEditionTypeChange = useCallback(
(index: number) => {
return (editionType: EditionType) => {
- const newPrompt = produce(payload as PromptItem[], (draft) => {
+ const newPrompt = produce(prompts, (draft) => {
draft[index]!.edition_type = editionType
})
onChange(newPrompt)
}
},
- [onChange, payload],
+ [onChange, prompts],
)
const handleChatModeMessageRoleChange = useCallback(
(index: number) => {
return (role: PromptRole) => {
- const newPrompt = produce(payload as PromptItem[], (draft) => {
+ const newPrompt = produce(prompts, (draft) => {
draft[index]!.role = role
})
onChange(newPrompt)
}
},
- [onChange, payload],
+ [onChange, prompts],
)
const handleAddPrompt = useCallback(() => {
- const newPrompt = produce(payload as PromptItem[], (draft) => {
+ const newPrompt = produce(prompts, (draft) => {
if (draft.length === 0) {
draft.push({ role: PromptRole.system, text: '', id: uuid4() })
@@ -132,18 +131,18 @@ const ConfigPrompt: FC<Props> = ({
})
})
onChange(newPrompt)
- }, [onChange, payload])
+ }, [onChange, prompts])
const handleRemove = useCallback(
(index: number) => {
return () => {
- const newPrompt = produce(payload as PromptItem[], (draft) => {
+ const newPrompt = produce(prompts, (draft) => {
draft.splice(index, 1)
})
onChange(newPrompt)
}
},
- [onChange, payload],
+ [onChange, prompts],
)
const handleCompletionPromptChange = useCallback(
@@ -193,7 +192,7 @@ const ConfigPrompt: FC<Props> = ({
setList={(list) => {
if (
keyboardSort.isSorting ||
- (prompts.every((item) => !!item.id) &&
+ (list.length === payloadWithIds.length &&
list.every((item, index) => item.id === payloadWithIds[index]?.id))
)
return