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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix: clear unsupported LLM memory on Workflow load and save (#43752)
Joel84b1848c9ad6
diff --git a/packages/dify-ui/src/dropdown-menu/index.stories.tsx b/packages/dify-ui/src/dropdown-menu/index.stories.tsxindex adb5246f02f..5053a84e00f 100644--- a/packages/dify-ui/src/dropdown-menu/index.stories.tsx+++ b/packages/dify-ui/src/dropdown-menu/index.stories.tsx@@ -1,6 +1,6 @@import type { Meta, StoryObj } from '@storybook/react-vite'import * as React from 'react'-import { expect, userEvent, within } from 'storybook/test'+import { expect, userEvent, waitFor, within } from 'storybook/test'import {createDropdownMenuHandle,DropdownMenu,@@ -389,12 +389,16 @@ export const DetachedTrigger: Story = {trigger.focus()await userEvent.keyboard('{ArrowDown}')const archive = await body.findByRole('menuitem', { name: 'Archive' })- await expect(archive).toHaveFocus()+ await waitFor(async () => {+ await expect(archive).toHaveFocus()+ })await userEvent.keyboard('{Enter}')await expect(canvas.getByRole('status', { name: 'Archived document' })).toHaveTextContent('Report',)await expect(trigger).toHaveAttribute('aria-expanded', 'false')- await expect(trigger).toHaveFocus()+ await waitFor(async () => {+ await expect(trigger).toHaveFocus()+ })},}diff --git a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.tsindex fd4d78a6606..a1fc11ae607 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts@@ -1,10 +1,14 @@import type { WorkflowSliceShape } from '@/app/components/workflow/store/workflow/workflow-slice'import type { EnvironmentVariablePatch } from '@/service/workflow'+import { noop } from '@tanstack/react-query'import { act } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { BlockEnum } from '@/app/components/workflow/types'import { markAppDeletionFailed, markAppDeletionStarted } from '@/service/app-deletion'-import { renderHookWithConsoleQuery } from '@/test/console/query-data'+import { consoleQuery } from '@/service/console'+import { createConsoleQueryClient, renderHookWithConsoleQuery } from '@/test/console/query-data'+import { createAppDetailFixture } from '@/test/fixtures/app'+import { AppModeEnum } from '@/types/app'import { useNodesSyncDraft } from '../use-nodes-sync-draft'const mockGetNodes = vi.fn()@@ -20,6 +24,7 @@ const mockCollaborationCanFlushGraphOnPageClose = vi.fn()const mockCollaborationCanUseLocalDraftFallback = vi.fn()const mockSetShowConfirm = vi.fn<(confirmation: WorkflowSliceShape['showConfirm']) => void>()let isCollaborationEnabled = false+let appMode: AppModeEnum | undefinedlet reactFlowState: {getNodes: typeof mockGetNodes@@ -55,6 +60,8 @@ vi.mock('reactflow', () => ({}))vi.mock('@/app/components/workflow/store', () => ({+ useStore: (selector: (state: typeof workflowStoreState) => unknown) =>+ selector(workflowStoreState),useWorkflowStore: () => ({getState: () => workflowStoreState,}),@@ -105,10 +112,27 @@ vi.mock('../use-workflow-refresh-draft', () => ({useWorkflowRefreshDraft: () => ({ handleRefreshWorkflowDraft: mockHandleRefreshWorkflowDraft }),}))-const renderUseNodesSyncDraft = () =>- renderHookWithConsoleQuery(() => useNodesSyncDraft(), {+const renderUseNodesSyncDraft = () => {+ const queryClient = createConsoleQueryClient()+ const appId = workflowStoreState.appId+ const appQueryKey = consoleQuery.apps.byAppId.get.queryKey({+ input: { params: { app_id: appId } },+ })+ if (appMode)+ queryClient.setQueryData(appQueryKey, createAppDetailFixture({ id: appId, mode: appMode }))+ else+ void queryClient+ .query({+ queryKey: appQueryKey,+ queryFn: () => new Promise<ReturnType<typeof createAppDetailFixture>>(() => {}),+ })+ .catch(noop)++ return renderHookWithConsoleQuery(() => useNodesSyncDraft(), {+ queryClient,systemFeatures: { enable_collaboration_mode: isCollaborationEnabled },})+}describe('useNodesSyncDraft', () => {beforeEach(() => {@@ -157,8 +181,105 @@ describe('useNodesSyncDraft', () => {updatedAt: 2,})isCollaborationEnabled = false+ appMode = AppModeEnum.WORKFLOW})+ it.each(['draft sync', 'page close'] as const)(+ 'should remove Workflow LLM memory from %s without changing the canvas nodes',+ async (savePath) => {+ const memory = {+ enabled: false,+ role_prefix: { user: '', assistant: '' },+ window: { enabled: false, size: 10 },+ }+ const canvasNodes = [+ {+ id: 'llm',+ position: { x: 0, y: 0 },+ data: { type: BlockEnum.LLM, title: 'LLM', memory },+ },+ {+ id: 'iteration-llm',+ parentId: 'iteration',+ position: { x: 0, y: 0 },+ data: { type: BlockEnum.LLM, title: 'Iteration LLM', memory },+ },+ {+ id: 'loop-llm',+ parentId: 'loop',+ position: { x: 0, y: 0 },+ data: { type: BlockEnum.LLM, title: 'Loop LLM', memory },+ },+ ]+ mockGetNodes.mockReturnValue(canvasNodes)+ const { result } = renderUseNodesSyncDraft()++ await act(async () => {+ if (savePath === 'draft sync') await result.current.doSyncWorkflowDraft()+ else result.current.syncWorkflowDraftWhenPageClose()+ })++ const expectedPayload = expect.objectContaining({+ graph: expect.objectContaining({+ nodes: canvasNodes.map((node) => ({+ ...node,+ data: { type: BlockEnum.LLM, title: node.data.title },+ })),+ }),+ })+ if (savePath === 'draft sync')+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith({+ url: '/apps/app-1/workflows/draft',+ params: expectedPayload,+ })+ else+ expect(mockPostWithKeepalive).toHaveBeenCalledWith(+ '/api/apps/app-1/workflows/draft',+ expectedPayload,+ )+ canvasNodes.forEach((node) => expect(node.data.memory).toEqual(memory))+ },+ )++ it.each([AppModeEnum.ADVANCED_CHAT, undefined])(+ 'should preserve LLM memory when app mode is %s',+ async (mode) => {+ appMode = mode+ const canvasNodes = [+ {+ id: 'llm',+ position: { x: 0, y: 0 },+ data: {+ type: BlockEnum.LLM,+ memory: {+ role_prefix: { user: 'Human', assistant: 'Assistant' },+ window: { enabled: true, size: 10 },+ },+ },+ },+ ]+ mockGetNodes.mockReturnValue(canvasNodes)+ const { result } = renderUseNodesSyncDraft()++ await act(async () => {+ await result.current.doSyncWorkflowDraft()+ result.current.syncWorkflowDraftWhenPageClose()+ })++ const expectedPayload = expect.objectContaining({+ graph: expect.objectContaining({ nodes: canvasNodes }),+ })+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith({+ url: '/apps/app-1/workflows/draft',+ params: expectedPayload,+ })+ expect(mockPostWithKeepalive).toHaveBeenCalledWith(+ '/api/apps/app-1/workflows/draft',+ expectedPayload,+ )+ },+ )+it('should wait for confirmation before saving an empty graph with force', async () => {mockGetNodes.mockReturnValue([])const callbacks = {diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-draft-graph-for-canvas.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-draft-graph-for-canvas.spec.tsindex ac2110429f5..3d5c8a4cf97 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-draft-graph-for-canvas.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-draft-graph-for-canvas.spec.ts@@ -1,3 +1,4 @@+import type { Node } from '@/app/components/workflow/types'import { renderHook } from '@testing-library/react'import { BlockEnum } from '@/app/components/workflow/types'import { AppModeEnum } from '@/types/app'@@ -109,4 +110,75 @@ describe('useWorkflowDraftGraphForCanvas', () => {expect(graph.viewport).toEqual({ x: 1, y: 2, zoom: 0.5 })expect(generateNewNodeCalls).toHaveLength(0)})++ it('removes residual LLM memory from workflow drafts, including container children', () => {+ const memory = {+ enabled: false,+ role_prefix: { user: '', assistant: '' },+ window: { enabled: false, size: 10 },+ }+ const nodes: Node<{ memory?: typeof memory }>[] = [+ {+ id: 'start',+ position: { x: 0, y: 0 },+ data: { type: BlockEnum.Start, title: 'Start', desc: '' },+ },+ ...[undefined, 'iteration', 'loop'].map((parentId, index) => ({+ id: `llm-${index}`,+ parentId,+ position: { x: 100, y: index * 100 },+ data: { type: BlockEnum.LLM, title: 'LLM', desc: '', memory },+ })),+ ...[BlockEnum.Iteration, BlockEnum.Loop].map((type) => ({+ id: type,+ position: { x: 200, y: 0 },+ data: { type, title: type, desc: '' },+ })),+ {+ id: 'classifier',+ position: { x: 300, y: 0 },+ data: { type: BlockEnum.QuestionClassifier, title: 'Classifier', desc: '', memory },+ },+ ]+ const originalNodes = structuredClone(nodes)+ const { result } = renderHook(() => useWorkflowDraftGraphForCanvas(AppModeEnum.WORKFLOW))++ const graph = result.current.getWorkflowDraftGraphForCanvas({ nodes, edges: [] })++ expect(graph.nodes).toHaveLength(nodes.length)+ const llmNodes = graph.nodes.filter((node) => node.data.type === BlockEnum.LLM)+ expect(llmNodes).toHaveLength(3)+ llmNodes.forEach((node) => {+ expect(node.data).not.toHaveProperty('memory')+ expect(node).toMatchObject({+ parentId: originalNodes.find((original) => original.id === node.id)?.parentId,+ data: { type: BlockEnum.LLM, title: 'LLM', desc: '' },+ })+ })+ expect(graph.nodes.find((node) => node.id === 'classifier')).toEqual(originalNodes.at(-1))+ expect(nodes).toEqual(originalNodes)+ })++ it.each([AppModeEnum.ADVANCED_CHAT, undefined])(+ 'preserves memory when app mode is %s',+ (appMode) => {+ const nodes: Node<{ memory: { window: { enabled: boolean; size: number } } }>[] = [+ {+ id: 'llm',+ position: { x: 0, y: 0 },+ data: {+ type: BlockEnum.LLM,+ title: 'LLM',+ desc: '',+ memory: { window: { enabled: false, size: 10 } },+ },+ },+ ]+ const { result } = renderHook(() => useWorkflowDraftGraphForCanvas(appMode))++ const graph = result.current.getWorkflowDraftGraphForCanvas({ nodes, edges: [] })++ expect(graph.nodes).toEqual(nodes)+ },+ )})diff --git a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.tsindex 4e9e2123ac6..05984fee362 100644--- a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts+++ b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts@@ -4,7 +4,7 @@ import type {SyncDraftResult,} from '@/app/components/workflow/hooks-store'import type { WorkflowDraftFeaturesPayload } from '@/service/workflow'-import { useSuspenseQuery } from '@tanstack/react-query'+import { skipToken, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { produce } from 'immer'import { useCallback, useEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'@@ -20,11 +20,13 @@ import {isAgentV2NodeData,needsInlineAgentBindingCreation,} from '@/app/components/workflow/nodes/agent-v2/types'-import { useWorkflowStore } from '@/app/components/workflow/store'+import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'+import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'import { API_PREFIX } from '@/config'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { isAppDeletingOrDeleted } from '@/service/app-deletion'+import { consoleQuery } from '@/service/console'import { postWithKeepalive } from '@/service/fetch'import { syncWorkflowDraft } from '@/service/workflow'import { useWorkflowRefreshDraft } from './use-workflow-refresh-draft'@@ -40,6 +42,13 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {const store = useStoreApi()const workflowStore = useWorkflowStore()const featuresStore = useFeaturesStore()+ const appId = useStore((state) => state.appId)+ const { data: appMode } = useQuery(+ consoleQuery.apps.byAppId.get.queryOptions({+ input: appId ? { params: { app_id: appId } } : skipToken,+ select: (app) => app.mode,+ }),+ )const { handleRefreshWorkflowDraft } = useWorkflowRefreshDraft()const { data: isCollaborationEnabled } = useSuspenseQuery({...systemFeaturesQueryOptions(),@@ -123,7 +132,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {url: `/apps/${appId}/workflows/draft`,params: {graph: {- nodes: producedNodes,+ nodes: normalizeWorkflowNodes(producedNodes, appMode),edges: producedEdges,viewport: {x,@@ -137,7 +146,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {...(isCollaborationEnabled ? { _is_collaborative: true } : {}),},}- }, [store, featuresStore, workflowStore, isCollaborationEnabled])+ }, [store, featuresStore, workflowStore, isCollaborationEnabled, appMode])const syncWorkflowDraftWhenPageClose = useCallback(() => {if (getNodesReadOnly()) returndiff --git a/web/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas.ts b/web/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas.tsindex c3e539cda5d..5612ec240d3 100644--- a/web/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas.ts@@ -5,6 +5,7 @@ import { START_INITIAL_POSITION } from '@/app/components/workflow/constants'import startPlaceholderDefault from '@/app/components/workflow/nodes/start-placeholder/default'import { BlockEnum } from '@/app/components/workflow/types'import { generateNewNode } from '@/app/components/workflow/utils'+import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'import { AppModeEnum } from '@/types/app'type HydrateWorkflowDraftGraphOptions = {@@ -61,7 +62,7 @@ export const useWorkflowDraftGraphForCanvas = (appMode?: AppModeEnum | string) =options?: HydrateWorkflowDraftGraphOptions,): WorkflowDataUpdater => {const nodes = getNodesWithLocalStartPlaceholder(- graph?.nodes || [],+ normalizeWorkflowNodes(graph?.nodes || [], appMode),options?.localStartPlaceholderNodes,)@@ -71,7 +72,7 @@ export const useWorkflowDraftGraphForCanvas = (appMode?: AppModeEnum | string) =viewport: graph?.viewport || { x: 0, y: 0, zoom: 1 },}},- [getNodesWithLocalStartPlaceholder],+ [appMode, getNodesWithLocalStartPlaceholder],)return {diff --git a/web/app/components/workflow/utils/normalize-workflow-nodes.ts b/web/app/components/workflow/utils/normalize-workflow-nodes.tsnew file mode 100644index 00000000000..bf06065b834--- /dev/null+++ b/web/app/components/workflow/utils/normalize-workflow-nodes.ts@@ -0,0 +1,18 @@+import { AppModeEnum } from '@/types/app'+import { BlockEnum } from '../types'++export const normalizeWorkflowNodes = <T extends { data: Record<string, unknown> }>(+ nodes: T[],+ appMode?: string,+): T[] => {+ if (appMode !== AppModeEnum.WORKFLOW) return nodes++ return nodes.map((node) => {+ if (node.data.type !== BlockEnum.LLM || !('memory' in node.data)) return node++ // A memory object implicitly requires sys.query, which plain Workflows do not provide.+ const data = { ...node.data }+ delete data.memory+ return { ...node, data }+ })+}diff --git a/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts b/web/app/components/workflow/workflow-generator/__tests__/apply.spec.tsindex c52c53c267e..e4f8499fff0 100644--- a/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts+++ b/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts@@ -1,4 +1,5 @@import type { GeneratedGraph } from '../types'+import { BlockEnum } from '@/app/components/workflow/types'import { createAppDetailFixture } from '@/test/fixtures/app'import { AppModeEnum } from '@/types/app'import {@@ -43,6 +44,26 @@ const makeGraph = (): GeneratedGraph => ({viewport: { x: 0, y: 0, zoom: 0.7 },})+const makeGraphWithMemory = (): GeneratedGraph => {+ const graph = makeGraph()+ const llmNode = {+ id: 'llm-1',+ type: 'custom',+ position: { x: 300, y: 0 },+ data: {+ type: BlockEnum.LLM,+ title: 'LLM',+ desc: '',+ memory: {+ role_prefix: { user: '', assistant: '' },+ window: { enabled: false, size: 10 },+ },+ },+ }+ graph.nodes.push(llmNode)+ return graph+}+describe('applyToNewApp', () => {beforeEach(() => {vi.clearAllMocks()@@ -98,6 +119,31 @@ describe('applyToNewApp', () => {expect(result.appMode).toBe(AppModeEnum.ADVANCED_CHAT)})+ it('should remove LLM memory before saving a generated Workflow draft', async () => {+ await applyToNewApp({+ mode: 'workflow',+ graph: makeGraphWithMemory(),+ instruction: 'Summarize a URL',+ })++ const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].params.graph+ expect(savedGraph.nodes[1].data).not.toHaveProperty('memory')+ })++ it('should preserve LLM memory when saving a generated Chatflow draft', async () => {+ const graph = makeGraphWithMemory()++ await applyToNewApp({+ mode: 'advanced-chat',+ graph,+ instruction: 'Answer questions in a conversation',+ })++ const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].params.graph+ expect(savedGraph.nodes[1].data).toHaveProperty('memory')+ expect(savedGraph).toEqual(graph)+ })+// The derived name keeps the user instruction recognisable in the apps list// — strip trailing punctuation and never produce an empty string.it('should derive a sensible app name from the instruction', async () => {@@ -212,6 +258,30 @@ describe('applyToCurrentApp', () => {mockSyncWorkflowDraft.mockResolvedValue({})})+ it('should remove LLM memory before replacing the current Workflow draft', async () => {+ await applyToCurrentApp({+ appId: 'app-42',+ appMode: AppModeEnum.WORKFLOW,+ graph: makeGraphWithMemory(),+ })++ const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].params.graph+ expect(savedGraph.nodes[1].data).not.toHaveProperty('memory')+ })++ it.each([AppModeEnum.ADVANCED_CHAT, undefined])(+ 'should preserve LLM memory when the current app mode is %s',+ async (appMode) => {+ const graph = makeGraphWithMemory()++ await applyToCurrentApp({ appId: 'app-42', appMode, graph })++ const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].params.graph+ expect(savedGraph.nodes[1].data).toHaveProperty('memory')+ expect(savedGraph).toEqual(graph)+ },+ )+// Happy path: the fetch yields an existing draft so the sync MUST include// its hash. Without this, the backend rejects the write with// WorkflowHashNotEqualError (the original bug behind the manual fix).diff --git a/web/app/components/workflow/workflow-generator/apply.ts b/web/app/components/workflow/workflow-generator/apply.tsindex f2bed015bc3..3b2059aa8b3 100644--- a/web/app/components/workflow/workflow-generator/apply.ts+++ b/web/app/components/workflow/workflow-generator/apply.ts@@ -1,5 +1,6 @@import type { GeneratedGraph, WorkflowGeneratorMode } from './types'import type { AppModeEnum } from '@/types/app'+import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'import { consoleClient } from '@/service/console'import { fetchWorkflowDraft, syncWorkflowDraft } from '@/service/workflow'@@ -121,7 +122,7 @@ export const applyToNewApp = async ({await syncWorkflowDraft({url: `apps/${app.id}/workflows/draft`,params: {- graph,+ graph: { ...graph, nodes: normalizeWorkflowNodes(graph.nodes, appMode) },features: {},conversation_variables: [],},@@ -140,6 +141,7 @@ export const applyToNewApp = async ({type ApplyToCurrentAppParams = {appId: string+ appMode?: AppModeEnumgraph: GeneratedGraph}@@ -158,6 +160,7 @@ type ApplyToCurrentAppParams = {*/export const applyToCurrentApp = async ({appId,+ appMode,graph,}: ApplyToCurrentAppParams): Promise<void> => {const url = `apps/${appId}/workflows/draft`@@ -177,7 +180,7 @@ export const applyToCurrentApp = async ({await syncWorkflowDraft({url,params: {- graph,+ graph: { ...graph, nodes: normalizeWorkflowNodes(graph.nodes, appMode) },features: existing?.features ?? {},conversation_variables: existing?.conversation_variables ?? [],// Field is accepted by the backend but not typed in the Pick<> shape ofdiff --git a/web/app/components/workflow/workflow-generator/index.tsx b/web/app/components/workflow/workflow-generator/index.tsxindex 552990b6cf2..a779d41a1a9 100644--- a/web/app/components/workflow/workflow-generator/index.tsx+++ b/web/app/components/workflow/workflow-generator/index.tsx@@ -517,7 +517,11 @@ function WorkflowGeneratorModal() {hideConfirmOverwrite()setApplyingTrue()try {- await applyToCurrentApp({ appId: currentAppId, graph: current.graph as GeneratedGraph })+ await applyToCurrentApp({+ appId: currentAppId,+ appMode: currentAppMode ?? undefined,+ graph: current.graph as GeneratedGraph,+ })toast.success(t(($) => $['workflowGenerator.applied'], { ns: 'workflowGenerator' }))closeGenerator()// Hard reload the workflow page so the canvas picks up the new draft —@@ -544,6 +548,7 @@ function WorkflowGeneratorModal() {}, [current,currentAppId,+ currentAppMode,hideConfirmOverwrite,closeGenerator,t,