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): clear conversation memory when pasting into Workflow (#43597)

非法操作f4a4e15a0be1
diff --git a/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts b/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts
index 5f1c24262b7..c8a4e756a8e 100644
--- a/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts
+++ b/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts
@@ -30,6 +30,7 @@ const runtimeNodesMetaDataMap = vi.hoisted(() => ({
}))
const runtimeState = vi.hoisted(() => ({
+ isChatMode: false,
nodesReadOnly: false,
workflowReadOnly: false,
}))
@@ -42,6 +43,7 @@ vi.mock('reactflow', async () =>
)
vi.mock('../use-workflow', () => ({
+ useIsChatMode: () => runtimeState.isChatMode,
useWorkflow: () => ({
getAfterNodesInSameBranch: () => [],
}),
@@ -117,6 +119,7 @@ describe('useNodesInteractions', () => {
beforeEach(() => {
vi.clearAllMocks()
resetReactFlowMockState()
+ runtimeState.isChatMode = false
runtimeState.nodesReadOnly = false
runtimeState.workflowReadOnly = false
mockCreateInlineAgentBinding.mockImplementation(
@@ -957,6 +960,86 @@ describe('useNodesInteractions', () => {
expect(rfState.setNodes).toHaveBeenCalled()
})
+ describe('pasted conversation memory', () => {
+ const memory = {
+ window: { enabled: false, size: 50 },
+ query_prompt_template: '{{#sys.query#}}\n\n{{#sys.files#}}',
+ }
+ const promptTemplate = [{ role: 'user', text: '{{#start.query#}}' }]
+
+ it.each(
+ [
+ BlockEnum.LLM,
+ BlockEnum.QuestionClassifier,
+ BlockEnum.ParameterExtractor,
+ BlockEnum.Agent,
+ ].flatMap((type) => [
+ { type, isChatMode: false },
+ { type, isChatMode: true },
+ ]),
+ )(
+ 'pastes $type with conversation memory only when isChatMode=$isChatMode',
+ async ({ type, isChatMode }) => {
+ runtimeState.isChatMode = isChatMode
+ runtimeNodesMetaDataMap.value = {
+ [type]: { defaultValue: { type, title: type, desc: '' } },
+ }
+ const sourceNode = createNode({
+ id: 'source-node',
+ data: { type, memory, prompt_template: promptTemplate },
+ })
+ const { result, store } = renderWorkflowHook(() => useNodesInteractions())
+ store.setState({ clipboardElements: [sourceNode], clipboardEdges: [] })
+
+ await act(async () => {
+ await result.current.handleNodesPaste()
+ })
+
+ const pastedNodes = rfState.setNodes.mock.calls.at(-1)?.[0] as Node[]
+ const pastedNode = pastedNodes.find((node) => node.data.type === type)!
+ if (isChatMode) expect(pastedNode.data).toHaveProperty('memory', memory)
+ else expect(pastedNode.data).not.toHaveProperty('memory')
+ expect(pastedNode.data).toHaveProperty('prompt_template', promptTemplate)
+ expect(store.getState().clipboardElements[0]?.data).toHaveProperty('memory', memory)
+ },
+ )
+
+ it.each([BlockEnum.Iteration, BlockEnum.Loop])(
+ 'clears memory from LLM children when pasting a %s into Workflow',
+ async (containerType) => {
+ runtimeNodesMetaDataMap.value = {
+ [containerType]: {
+ defaultValue: { type: containerType, title: containerType, desc: '' },
+ },
+ [BlockEnum.LLM]: { defaultValue: { type: BlockEnum.LLM, title: 'LLM', desc: '' } },
+ }
+ const sourceContainer = createNode({
+ id: 'source-container',
+ data: { type: containerType },
+ })
+ const sourceChild = createNode({
+ id: 'source-child',
+ parentId: sourceContainer.id,
+ data: { type: BlockEnum.LLM, memory, prompt_template: promptTemplate },
+ })
+ const { result, store } = renderWorkflowHook(() => useNodesInteractions())
+ store.setState({ clipboardElements: [sourceContainer, sourceChild], clipboardEdges: [] })
+
+ await act(async () => {
+ await result.current.handleNodesPaste()
+ })
+
+ const pastedNodes = rfState.setNodes.mock.calls.at(-1)?.[0] as Node[]
+ const pastedChild = pastedNodes.find((node) => node.data.type === BlockEnum.LLM)!
+ expect(pastedChild.parentId).toBe(
+ pastedNodes.find((node) => node.data.type === containerType)?.id,
+ )
+ expect(pastedChild.data).not.toHaveProperty('memory')
+ expect(sourceChild.data).toHaveProperty('memory', memory)
+ },
+ )
+ })
+
// Paste title handling should preserve original names until the destination canvas conflicts.
describe('paste title handling', () => {
beforeEach(() => {
diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts b/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts
index ff8e76eb963..b53a9fd7640 100644
--- a/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts
+++ b/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts
@@ -1,5 +1,9 @@
import type { NodeDefault } from '../../types'
-import { act, renderHook } from '@testing-library/react'
+import { act } from '@testing-library/react'
+import { consoleQuery } from '@/service/console'
+import { createAppDetailFixture } from '@/test/fixtures/app'
+import { createTestQueryClient } from '@/test/query-client'
+import { AppModeEnum } from '@/types/app'
import { createNode } from '../../__tests__/fixtures'
import {
baseRunningData,
@@ -18,15 +22,8 @@ import {
useWorkflowReadOnly,
} from '../use-workflow'
-let mockAppMode = 'workflow'
-vi.mock('@/app/components/app/store', () => ({
- useStore: (selector: (state: { appDetail: { mode: string } }) => unknown) =>
- selector({ appDetail: { mode: mockAppMode } }),
-}))
-
beforeEach(() => {
vi.clearAllMocks()
- mockAppMode = 'workflow'
})
function createNodeDefault(type: BlockEnum): NodeDefault {
@@ -48,27 +45,67 @@ function createNodeDefault(type: BlockEnum): NodeDefault {
// ---------------------------------------------------------------------------
describe('useIsChatMode', () => {
- it('should return true when app mode is advanced-chat', () => {
- mockAppMode = 'advanced-chat'
- const { result } = renderHook(() => useIsChatMode())
- expect(result.current).toBe(true)
+ let queryClient: ReturnType<typeof createTestQueryClient>
+
+ beforeEach(() => {
+ queryClient = createTestQueryClient()
})
- it('should return false when app mode is workflow', () => {
- mockAppMode = 'workflow'
- const { result } = renderHook(() => useIsChatMode())
- expect(result.current).toBe(false)
+ afterEach(() => {
+ queryClient.clear()
+ })
+
+ it.each([
+ { mode: AppModeEnum.ADVANCED_CHAT, expected: true },
+ { mode: AppModeEnum.WORKFLOW, expected: false },
+ ])('should return $expected for the current $mode app', ({ mode, expected }) => {
+ queryClient.setQueryData(
+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),
+ createAppDetailFixture({ id: 'app-1', mode }),
+ )
+
+ const { result } = renderWorkflowHook(() => useIsChatMode(), {
+ initialStoreState: { appId: 'app-1' },
+ queryClient,
+ })
+
+ expect(result.current).toBe(expected)
})
- it('should return false when app mode is chat', () => {
- mockAppMode = 'chat'
- const { result } = renderHook(() => useIsChatMode())
+ it('should return false without an app id even when another chatflow is cached', () => {
+ queryClient.setQueryData(
+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'chatflow-app' } } }),
+ createAppDetailFixture({ id: 'chatflow-app', mode: AppModeEnum.ADVANCED_CHAT }),
+ )
+
+ const { result } = renderWorkflowHook(() => useIsChatMode(), { queryClient })
+
expect(result.current).toBe(false)
+ expect(globalThis.fetch).not.toHaveBeenCalled()
})
- it('should return false when app mode is completion', () => {
- mockAppMode = 'completion'
- const { result } = renderHook(() => useIsChatMode())
+ it('should follow the current app id when switching between cached workflow and chatflow apps', () => {
+ for (const [appId, mode] of [
+ ['workflow-app', AppModeEnum.WORKFLOW],
+ ['chatflow-app', AppModeEnum.ADVANCED_CHAT],
+ ] as const) {
+ queryClient.setQueryData(
+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: appId } } }),
+ createAppDetailFixture({ id: appId, mode }),
+ )
+ }
+
+ const { result, store } = renderWorkflowHook(() => useIsChatMode(), {
+ initialStoreState: { appId: 'workflow-app' },
+ queryClient,
+ })
+
+ expect(result.current).toBe(false)
+
+ act(() => store.setState({ appId: 'chatflow-app' }))
+ expect(result.current).toBe(true)
+
+ act(() => store.setState({ appId: 'workflow-app' }))
expect(result.current).toBe(false)
})
})
diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.ts
index 59e4784e108..a30d3c877ac 100644
--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts
+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts
@@ -67,7 +67,7 @@ import { useHelpline } from './use-helpline'
import useInspectVarsCrud from './use-inspect-vars-crud'
import { useNodesMetaData } from './use-nodes-meta-data'
import { useNodesSyncDraft } from './use-nodes-sync-draft'
-import { useNodesReadOnly, useWorkflow, useWorkflowReadOnly } from './use-workflow'
+import { useIsChatMode, useNodesReadOnly, useWorkflow, useWorkflowReadOnly } from './use-workflow'
import { useWorkflowHistory, WorkflowHistoryEvent } from './use-workflow-history'
// Entry node deletion restriction has been removed to allow empty workflows
@@ -164,6 +164,7 @@ const isNoteLinkClickTarget = (target: EventTarget | null, node: Node) => {
export const useNodesInteractions = () => {
const { t } = useTranslation(['workflow'])
+ const isChatMode = useIsChatMode()
const { data: appDslVersion = '' } = useQuery(
consoleQuery.appDslVersion.get.queryOptions({
staleTime: Infinity,
@@ -2127,6 +2128,19 @@ export const useNodesInteractions = () => {
}
})
+ if (!isChatMode) {
+ const memoryNodeTypes: BlockEnum[] = [
+ BlockEnum.LLM,
+ BlockEnum.QuestionClassifier,
+ BlockEnum.ParameterExtractor,
+ BlockEnum.Agent,
+ ]
+ nodesToPaste.forEach((node) => {
+ if (memoryNodeTypes.includes(getNodeCatalogType(node.data)) && 'memory' in node.data)
+ delete node.data.memory
+ })
+ }
+
const newNodes = produce(nodes, (draft: Node[]) => {
parentChildrenToAppend.forEach(({ parentId, childId, childType }) => {
const p = draft.find((n) => n.id === parentId)
@@ -2153,6 +2167,7 @@ export const useNodesInteractions = () => {
handleNodeLoopChildrenCopy,
getNodeDefaultValueForPaste,
appDslVersion,
+ isChatMode,
])
const handleNodesDuplicate = useCallback(
diff --git a/web/app/components/workflow/hooks/use-workflow.ts b/web/app/components/workflow/hooks/use-workflow.ts
index dd4127f8472..29e63cd2fa9 100644
--- a/web/app/components/workflow/hooks/use-workflow.ts
+++ b/web/app/components/workflow/hooks/use-workflow.ts
@@ -2,12 +2,13 @@ import type { Connection } from 'reactflow'
import type { IterationNodeType } from '../nodes/iteration/types'
import type { LoopNodeType } from '../nodes/loop/types'
import type { BlockEnum, Edge, Node, ValueSelector } from '../types'
+import { skipToken, useQuery } from '@tanstack/react-query'
import { uniqBy } from 'es-toolkit/compat'
import { useCallback } from 'react'
import { getIncomers, getOutgoers } from 'reactflow'
-import { useStore as useAppStore } from '@/app/components/app/store'
import { CUSTOM_ITERATION_START_NODE } from '@/app/components/workflow/nodes/iteration-start/constants'
import { CUSTOM_LOOP_START_NODE } from '@/app/components/workflow/nodes/loop-start/constants'
+import { consoleQuery } from '@/service/console'
import { AppModeEnum } from '@/types/app'
import { SUPPORT_OUTPUT_VARS_NODE } from '../constants'
import { useHooksStore } from '../hooks-store'
@@ -26,9 +27,15 @@ import { useCollaborativeWorkflow } from './use-collaborative-workflow'
import { useNodesMetaData } from './use-nodes-meta-data'
export const useIsChatMode = () => {
- const appDetail = useAppStore((s) => s.appDetail)
+ const appId = useStore((state) => state.appId)
+ const { data: isChatMode } = useQuery(
+ consoleQuery.apps.byAppId.get.queryOptions({
+ input: appId ? { params: { app_id: appId } } : skipToken,
+ select: (app) => app.mode === AppModeEnum.ADVANCED_CHAT,
+ }),
+ )
- return appDetail?.mode === AppModeEnum.ADVANCED_CHAT
+ return isChatMode ?? false
}
export const useWorkflow = () => {
diff --git a/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx
index b1d59a556fa..912cd0334a7 100644
--- a/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx
@@ -4,6 +4,7 @@ import type { PanelProps } from '@/types/workflow'
import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
import { BlockEnum, VarType } from '../../../types'
import ConditionAdd from '../components/condition-add'
import ConditionFilesListValue from '../components/condition-files-list-value'
@@ -269,7 +270,7 @@ describe('if-else path', () => {
const user = userEvent.setup()
const onToggleConditionLogicalOperator = vi.fn()
- render(
+ renderWithConsoleQuery(
<ConditionList
caseId="case-1"
caseItem={{