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): prevent workflow errors after app deletion (#40977)

yyh8e1c259a66cd
diff --git a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts
index 31c9bfbc679..bef3bcc1e7d 100644
--- a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts
+++ b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts
@@ -27,6 +27,9 @@ const mockExportWorkflowAppDsl = vi.fn()
const mockWorkflowExportState = { isExporting: false }
const mockDeleteApp = vi.fn()
const mockFetchAppDetail = vi.fn()
+const mockMarkAppDeletionStarted = vi.fn()
+const mockMarkAppDeletionSucceeded = vi.fn()
+const mockMarkAppDeletionFailed = vi.fn()
const mockGetSocket = vi.fn()
const mockOnAppMetaUpdate = vi.fn()
const mockSetQueryData = vi.fn()
@@ -97,6 +100,12 @@ vi.mock('@/service/apps', () => ({
fetchAppDetail: (...args: unknown[]) => mockFetchAppDetail(...args),
}))
+vi.mock('@/service/app-deletion', () => ({
+ markAppDeletionStarted: (...args: unknown[]) => mockMarkAppDeletionStarted(...args),
+ markAppDeletionSucceeded: (...args: unknown[]) => mockMarkAppDeletionSucceeded(...args),
+ markAppDeletionFailed: (...args: unknown[]) => mockMarkAppDeletionFailed(...args),
+}))
+
vi.mock('@/utils/app-redirection', () => ({
getRedirection: vi.fn(),
}))
@@ -499,6 +508,9 @@ describe('useAppInfoActions', () => {
})
expect(mockDeleteApp).toHaveBeenCalledWith('app-1')
+ expect(mockMarkAppDeletionStarted).toHaveBeenCalledWith('app-1')
+ expect(mockMarkAppDeletionSucceeded).toHaveBeenCalledWith('app-1')
+ expect(mockMarkAppDeletionFailed).not.toHaveBeenCalled()
expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'app.appDeleted' })
expect(mockInvalidateQueries).toHaveBeenCalledTimes(3)
expect(mockReplace).toHaveBeenCalledWith('/apps')
@@ -526,6 +538,9 @@ describe('useAppInfoActions', () => {
await result.current.onConfirmDelete()
})
+ expect(mockMarkAppDeletionStarted).toHaveBeenCalledWith('app-1')
+ expect(mockMarkAppDeletionFailed).toHaveBeenCalledWith('app-1')
+ expect(mockMarkAppDeletionSucceeded).not.toHaveBeenCalled()
expect(toastMocks.call).toHaveBeenCalledWith({
type: 'error',
message: expect.stringContaining('app.appDeleteFailed'),
diff --git a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts
index b1c0ee9f9e9..f0dabb42820 100644
--- a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts
+++ b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts
@@ -15,6 +15,11 @@ import { useExportAppDsl, useExportWorkflowAppDsl } from '@/app/components/app/u
import { useProviderContext } from '@/context/provider-context'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useRouter } from '@/next/navigation'
+import {
+ markAppDeletionFailed,
+ markAppDeletionStarted,
+ markAppDeletionSucceeded,
+} from '@/service/app-deletion'
import { copyApp, deleteApp, fetchAppDetail, updateAppInfo } from '@/service/apps'
import { consoleQuery } from '@/service/client'
import { AppModeEnum } from '@/types/app'
@@ -306,8 +311,10 @@ export function useAppInfoActions({ resetKey }: UseAppInfoActionsParams) {
const onConfirmDelete = useCallback(async () => {
if (!appDetail) return
+ markAppDeletionStarted(appDetail.id)
try {
await deleteApp(appDetail.id)
+ markAppDeletionSucceeded(appDetail.id)
toast(
t(($) => $.appDeleted, { ns: 'app' }),
{ type: 'success' },
@@ -319,6 +326,7 @@ export function useAppInfoActions({ resetKey }: UseAppInfoActionsParams) {
setAppDetail()
replace('/apps')
} catch (e: unknown) {
+ markAppDeletionFailed(appDetail.id)
toast(
`${t(($) => $.appDeleteFailed, { ns: 'app' })}${e instanceof Error && e.message ? `: ${e.message}` : ''}`,
{ type: 'error' },
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.ts
index 1b60fa9b742..91cc23437bc 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
@@ -2,6 +2,7 @@ import type { EnvironmentVariablePatch } from '@/service/workflow'
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 { useNodesSyncDraft } from '../use-nodes-sync-draft'
@@ -544,6 +545,69 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
)
})
+ it('should skip draft persistence without reporting an error while the app is being deleted', async () => {
+ const callbacks = {
+ onError: vi.fn(),
+ onSettled: vi.fn(),
+ }
+ markAppDeletionStarted('app-1')
+
+ try {
+ const { result } = renderUseNodesSyncDraft()
+
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false, callbacks)
+ result.current.syncWorkflowDraftWhenPageClose()
+ })
+
+ expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()
+ expect(mockPostWithKeepalive).not.toHaveBeenCalled()
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
+ } finally {
+ markAppDeletionFailed('app-1')
+ }
+ })
+
+ it('should not report an in-flight draft failure after app deletion starts', async () => {
+ let rejectSync!: (reason?: unknown) => void
+ let resolveStarted!: () => void
+ const started = new Promise<void>((resolve) => {
+ resolveStarted = resolve
+ })
+ mockSyncWorkflowDraft.mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ rejectSync = reject
+ resolveStarted()
+ }),
+ )
+ const callbacks = {
+ onError: vi.fn(),
+ onSettled: vi.fn(),
+ }
+ const { result } = renderUseNodesSyncDraft()
+ let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>
+
+ act(() => {
+ syncPromise = result.current.doSyncWorkflowDraft(false, callbacks)
+ })
+ await started
+ markAppDeletionStarted('app-1')
+
+ try {
+ await act(async () => {
+ rejectSync(new Error('App not found'))
+ await syncPromise
+ })
+
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ expect(callbacks.onSettled).toHaveBeenCalledOnce()
+ } finally {
+ markAppDeletionFailed('app-1')
+ }
+ })
+
it('should not post the local start placeholder when the page closes', () => {
reactFlowState = {
...reactFlowState,
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.ts
index b36a969481a..1a1f2953050 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
@@ -23,10 +23,14 @@ import { useWorkflowStore } from '@/app/components/workflow/store'
import { BlockEnum } from '@/app/components/workflow/types'
import { API_PREFIX } from '@/config'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { isAppDeletingOrDeleted } from '@/service/app-deletion'
import { postWithKeepalive } from '@/service/fetch'
import { syncWorkflowDraft } from '@/service/workflow'
import { useWorkflowRefreshDraft } from './use-workflow-refresh-draft'
+const shouldSkipDraftSync = (appId: string | undefined, isWorkflowDataLoaded: boolean) =>
+ !appId || !isWorkflowDataLoaded || isAppDeletingOrDeleted(appId)
+
const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
const store = useStoreApi()
const workflowStore = useWorkflowStore()
@@ -62,7 +66,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
const { appId, conversationVariables, syncWorkflowDraftHash, isWorkflowDataLoaded } =
workflowStore.getState()
- if (!appId || !isWorkflowDataLoaded) return null
+ if (shouldSkipDraftSync(appId, isWorkflowDataLoaded)) return null
const features = featuresStore!.getState().features
const producedNodes = produce(nodes, (draft) => {
@@ -142,6 +146,11 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
options?: SyncDraftOptions,
): Promise<SyncDraftResult | null> => {
if (getNodesReadOnly()) return null
+ const { appId, isWorkflowDataLoaded } = workflowStore.getState()
+ if (shouldSkipDraftSync(appId, isWorkflowDataLoaded)) {
+ callback?.onSettled?.()
+ return null
+ }
if (isCollaborationEnabled && !collaborationManager.canPersistLocalGraph()) {
callback?.onSettled?.()
@@ -176,6 +185,9 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
callback?.onSuccess?.()
return { hash: res.hash, updatedAt: res.updated_at }
} catch (error: unknown) {
+ const { appId, isWorkflowDataLoaded } = workflowStore.getState()
+ if (shouldSkipDraftSync(appId, isWorkflowDataLoaded)) return null
+
const responseError = error as {
bodyUsed?: boolean
json?: () => Promise<{ code?: string }>
@@ -206,6 +218,11 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
options?: SyncDraftOptions,
): Promise<SyncDraftResult | null> => {
if (getNodesReadOnly()) return null
+ const { appId, isWorkflowDataLoaded } = workflowStore.getState()
+ if (shouldSkipDraftSync(appId, isWorkflowDataLoaded)) {
+ callback?.onSettled?.()
+ return null
+ }
const shouldRequestLeader =
isCollaborationEnabled &&
@@ -232,7 +249,8 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
callback?.onSuccess?.()
return result
} catch {
- callback?.onError?.()
+ const { appId, isWorkflowDataLoaded } = workflowStore.getState()
+ if (!shouldSkipDraftSync(appId, isWorkflowDataLoaded)) callback?.onError?.()
return null
} finally {
callback?.onSettled?.()
diff --git a/web/service/app-deletion.ts b/web/service/app-deletion.ts
new file mode 100644
index 00000000000..0549a9bc446
--- /dev/null
+++ b/web/service/app-deletion.ts
@@ -0,0 +1,49 @@
+type AppDeletionState = {
+ pendingCount: number
+ deleted: boolean
+}
+
+// Successful IDs stay as session tombstones for requests that settle after navigation.
+const appDeletionStates = new Map<string, AppDeletionState>()
+
+export const markAppDeletionStarted = (appId: string) => {
+ const state = appDeletionStates.get(appId)
+ appDeletionStates.set(appId, {
+ pendingCount: (state?.pendingCount ?? 0) + 1,
+ deleted: state?.deleted ?? false,
+ })
+}
+
+export const markAppDeletionSucceeded = (appId: string) => {
+ const state = appDeletionStates.get(appId)
+ appDeletionStates.set(appId, {
+ pendingCount: Math.max((state?.pendingCount ?? 1) - 1, 0),
+ deleted: true,
+ })
+}
+
+export const markAppDeletionFailed = (appId: string) => {
+ const state = appDeletionStates.get(appId)
+ if (!state) return
+
+ const pendingCount = Math.max(state.pendingCount - 1, 0)
+ if (!pendingCount && !state.deleted) {
+ appDeletionStates.delete(appId)
+ return
+ }
+
+ appDeletionStates.set(appId, { ...state, pendingCount })
+}
+
+export const isAppDeletingOrDeleted = (appId: string) => appDeletionStates.has(appId)
+
+export const shouldSuppressAppDeletionErrorToast = (requestUrl: string, status: number) => {
+ if (status !== 404) return false
+
+ const match = new URL(requestUrl, globalThis.location?.origin).pathname.match(
+ /\/apps\/([^/]+)\/workflows(?:\/|$)/,
+ )
+ if (!match?.[1]) return false
+
+ return isAppDeletingOrDeleted(decodeURIComponent(match[1]))
+}
diff --git a/web/service/fetch.spec.ts b/web/service/fetch.spec.ts
index 57d5040ec0e..9e9d1c832c3 100644
--- a/web/service/fetch.spec.ts
+++ b/web/service/fetch.spec.ts
@@ -1,5 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { PUBLIC_API_PREFIX } from '@/config'
+import {
+ markAppDeletionFailed,
+ markAppDeletionStarted,
+ markAppDeletionSucceeded,
+} from './app-deletion'
// oxlint-disable-next-line no-restricted-imports
import { base } from './fetch'
@@ -167,5 +172,121 @@ describe('base', () => {
expect(toast.error).not.toHaveBeenCalled()
})
+
+ it('should suppress a late workflow 404 for the app being deleted', async () => {
+ const appId = 'deleting-app'
+ markAppDeletionStarted(appId)
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ code: 'not_found',
+ message: 'App not found',
+ status: 404,
+ }),
+ {
+ status: 404,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
+ )
+
+ try {
+ await expect(
+ base(`/apps/${appId}/workflows/draft/system-variables`),
+ ).rejects.toBeInstanceOf(Response)
+ expect(toast.error).not.toHaveBeenCalled()
+ } finally {
+ markAppDeletionFailed(appId)
+ }
+ })
+
+ it('should suppress a workflow 404 that settles after app deletion succeeds', async () => {
+ const appId = 'deleted-app'
+ markAppDeletionStarted(appId)
+ markAppDeletionSucceeded(appId)
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ code: 'not_found',
+ message: 'App not found',
+ status: 404,
+ }),
+ {
+ status: 404,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
+ )
+
+ await expect(
+ base(`/apps/${appId}/workflows/draft/conversation-variables`),
+ ).rejects.toBeInstanceOf(Response)
+ expect(toast.error).not.toHaveBeenCalled()
+ })
+
+ it('should restore workflow 404 notifications when app deletion fails', async () => {
+ const appId = 'failed-deletion-app'
+ markAppDeletionStarted(appId)
+ markAppDeletionFailed(appId)
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ code: 'not_found',
+ message: 'Visible error',
+ status: 404,
+ }),
+ {
+ status: 404,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
+ )
+
+ await expect(base(`/apps/${appId}/workflows/draft/variables`)).rejects.toBeInstanceOf(
+ Response,
+ )
+ expect(toast.error).toHaveBeenCalledWith('Visible error')
+ })
+
+ it.each([
+ {
+ title: 'another app workflow 404',
+ path: '/apps/another-app/workflows/draft/system-variables',
+ status: 404,
+ },
+ {
+ title: 'a non-workflow 404',
+ path: '/apps/deleting-app',
+ status: 404,
+ },
+ {
+ title: 'a workflow 500',
+ path: '/apps/deleting-app/workflows/draft/system-variables',
+ status: 500,
+ },
+ ])('should still display $title while an app is being deleted', async ({ path, status }) => {
+ const appId = 'deleting-app'
+ markAppDeletionStarted(appId)
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ code: 'request_failed',
+ message: 'Visible error',
+ status,
+ }),
+ {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ),
+ )
+
+ try {
+ await expect(base(path)).rejects.toBeInstanceOf(Response)
+ expect(toast.error).toHaveBeenCalledWith('Visible error')
+ } finally {
+ markAppDeletionFailed(appId)
+ }
+ })
})
})
diff --git a/web/service/fetch.ts b/web/service/fetch.ts
index 958431408d7..d84a3064fab 100644
--- a/web/service/fetch.ts
+++ b/web/service/fetch.ts
@@ -14,6 +14,7 @@ import {
PUBLIC_API_PREFIX,
WEB_APP_SHARE_CODE_HEADER_NAME,
} from '@/config'
+import { shouldSuppressAppDeletionErrorToast } from './app-deletion'
import { getWebAppPublicApiPath, resolveWebAppAddress } from './webapp-address'
import { getWebAppAccessToken, getWebAppPassport } from './webapp-auth'
@@ -68,14 +69,18 @@ const createResponseFromHTTPError = (error: HTTPError): Response => {
}
const afterResponseErrorCode = (otherOptions: IOtherOptions): AfterResponseHook => {
- return async ({ response }) => {
+ return async ({ request, response }) => {
if (!/^[23]\d{2}$/.test(String(response.status))) {
let errorData: ResponseError | null = null
try {
const data: unknown = await response.clone().json()
errorData = data as ResponseError
} catch {}
- const shouldNotifyError = response.status !== 401 && errorData && !otherOptions.silent
+ const shouldNotifyError =
+ response.status !== 401 &&
+ errorData &&
+ !otherOptions.silent &&
+ !shouldSuppressAppDeletionErrorToast(request.url, response.status)
const errorMessage = errorData?.message || errorData?.error
if (shouldNotifyError && errorMessage) toast.error(errorMessage)