From 65ffbdceaf68bde197611cfb10a2ba97a803ccb2 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 5 Nov 2026 07:20:27 +0000 Subject: [PATCH 1/2] fix(workflow): load a tab before saving it instead of failing (#22971) Saving a tab whose content was not loaded failed with "Cannot save workflow '' before it is loaded". That is the guard from #21326, which stops the save from writing `null` over the file. On cloud production (1.59.5) it fires from the close dialog's **Save** on a saved file that was unloaded but still marked modified (Sentry `CLOUD-FRONTEND-PROD-394`, 12 events / 11 users), and from saves of unsaved tabs a reload restored without opening (`CLOUD-FRONTEND-PROD-393`, 34 / 32; the agent-picker part of that is [FRONT-3837](https://linear.app/comfyorg/issue/FRONT-3837). Changes: - `saveWorkflow` / `saveWorkflowAs` load an unloaded tab in the background first (the serialized load queue, as #22648 does for the picker), which applies its draft. This covers every caller: close dialog, Ctrl+S, autosave, workspace switch, picker. The guard in `ComfyWorkflow.save` stays as the backstop. - If loading finds no usable draft for a saved file marked modified, its edits were already gone: nothing is written, the modified mark is cleared, the user gets a warning toast ("Unsaved changes were not saved"), and it is reported (`Modified saved workflow lost its edits before saving`, static message, no path) so any remaining source stays visible. Before, the save failed; a plain write would have reported Save as done. - An **active** tab with no loaded content still hits the guard: a background copy is not what is on the canvas. - Root cause fixed for one path: workflow sync no longer unloads (or re-stamps) a **modified background tab** whose file changed remotely. Unloading made its draft older than the file, so the next load dropped the edits and left the modified mark, which is the state the close-dialog Save then failed on. The tab is now treated like the active one: its in-memory edits win until the user saves or discards them. - The guard's error message no longer contains the workflow path (alerts showed user file names in their titles). Design notes: - Sync keeping local edits means a remote change to a modified background tab (another device, the agent writing the file) is not shown until the user saves or discards. Saving then overwrites it, as it already does for the active tab. Before, the remote copy silently replaced the edits. - `discardSupersededLoad` is unchanged: it restores the pre-open state, and saving that state now loads first. - Red first: on `main` the new service tests failed with the exact production message ("Cannot save workflow 'workflows/background.json' before it is loaded"), and the sync test failed with the tab unloaded. - `workflowService.test.ts` "saving a tab that is not loaded": close-dialog Save writes the draft; direct save writes the draft; no usable draft writes nothing, warns and reports; an active unloaded tab still refuses; a restored unsaved tab closes through Save As and is written. - `workflowStore.test.ts`: a modified background tab keeps its edits and metadata through a sync with a changed file; an unmodified one is still unloaded; guard message is static. - Local: all `src/platform/workflow` tests and `useAgentWorkflowSelection.test.ts` pass (2360), `typecheck:app`, `oxlint --type-aware`, `oxfmt`. - Adversarial review (fresh reviewer): its majors are fixed in the second commit (no write when edits are gone, active tab keeps the guard, kept tab's draft stays usable, Save As loads after the prompt). - After release: `CLOUD-FRONTEND-PROD-394` and `-393` should stop on the release carrying this; any `Modified saved workflow lost its edits before saving` events show what else still drops edits. --------- Co-authored-by: GitHub Action (cherry picked from commit 03bbb78ba20f4377b90d44e2fc5725fe839a3842) --- src/locales/en/main.json | 4 +- .../core/services/workflowService.test.ts | 169 ++++++++++++++++++ .../workflow/core/services/workflowService.ts | 30 +++- .../management/stores/comfyWorkflow.ts | 2 +- .../management/stores/workflowStore.test.ts | 57 +++++- .../management/stores/workflowStore.ts | 4 +- .../agent/useAgentWorkflowSelection.test.ts | 8 +- 7 files changed, 262 insertions(+), 12 deletions(-) diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 9c88ba23d30..85b692a1098 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -1355,7 +1355,9 @@ "enterFilenamePrompt": "Enter the filename:", "saveWorkflow": "Save workflow", "savedAsApp": "Converted to app workflow", - "savedAsWorkflow": "Converted to node graph only workflow" + "savedAsWorkflow": "Converted to node graph only workflow", + "unsavedChangesLostTitle": "Unsaved changes were not saved", + "unsavedChangesLost": "The unsaved changes to {name} were no longer available, so the saved file was left as it was." }, "subgraphStore": { "confirmDeleteTitle": "Delete blueprint?", diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 9d8c1456646..9405ab9ffed 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -44,6 +44,7 @@ import type { AppMode } from '@/utils/appMode' import { isValidUuid } from '@/utils/formatUtil' import { zeroUuid } from '@/utils/uuid' import { t } from '@/i18n' +import { api } from '@/scripts/api' import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth'), { spy: true }) @@ -3894,6 +3895,174 @@ describe('useWorkflowService', () => { expect(workflowStore.saveWorkflow).toHaveBeenCalledWith(workflow) }) }) + + describe('saving a tab that is not loaded', () => { + let workflowStore: ReturnType + let service: ReturnType + + beforeEach(() => { + workflowStore = useWorkflowStore() + service = useWorkflowService() + vi.spyOn(api, 'getUserData').mockImplementation( + async () => new Response(JSON.stringify(defaultGraph)) + ) + vi.spyOn(api, 'storeUserData').mockImplementation( + async (path) => + new Response(JSON.stringify({ path, modified: 300, size: 2 })) + ) + vi.mocked(useDialogService().confirm).mockResolvedValue(true) + resetReportedWorkflowStateAnomaliesForTests() + mockAssert.mockClear() + }) + + function unloadedModifiedTab(path: string): ComfyWorkflow { + const tab = new ComfyWorkflowClass({ path, modified: 100, size: 1 }) + workflowStore.attachWorkflow(tab) + workflowStore.openWorkflowsInBackground({ right: [tab.path] }) + tab.isModified = true + return tab + } + + function storedContent(path: string): ComfyWorkflowJSON { + const call = vi + .mocked(api.storeUserData) + .mock.calls.find(([stored]) => stored === path) + assert(call, `nothing was stored at ${path}`) + return JSON.parse(call[1] as string) as ComfyWorkflowJSON + } + + function enableDrafts() { + useSettingStore().settingsById['Comfy.Workflow.Persist'] = { + id: 'Comfy.Workflow.Persist', + name: 'Persist workflow state', + type: 'boolean', + defaultValue: true + } + } + + function draftOf(extra: Record, updatedAt: number) { + vi.mocked(useWorkflowDraftStoreV2().getDraft).mockImplementation((path) => + path === 'workflows/background.json' + ? { + data: JSON.stringify({ ...defaultGraph, extra }), + name: 'background.json', + isTemporary: false, + updatedAt + } + : null + ) + } + + it('loads its draft and saves it when Save is chosen in the close dialog', async () => { + enableDrafts() + draftOf({ editedInDraft: true }, 200) + const tab = unloadedModifiedTab('workflows/background.json') + + expect(await service.closeWorkflow(tab)).toBe(true) + + expect(storedContent('workflows/background.json').extra).toEqual({ + editedInDraft: true + }) + expect(workflowStore.openWorkflows).not.toContain(tab) + expect(mockAssert).not.toHaveBeenCalledWith( + false, + 'Modified saved workflow lost its edits before saving', + expect.anything() + ) + }) + + it('writes nothing and says so when the edits are no longer available', async () => { + enableDrafts() + draftOf({ editedInDraft: true }, 50) + const tab = unloadedModifiedTab('workflows/background.json') + + expect(await service.closeWorkflow(tab)).toBe(true) + + expect(api.storeUserData).not.toHaveBeenCalled() + expect(tab.isModified).toBe(false) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'Unsaved changes were not saved' + }) + ]) + expect(mockAssert).toHaveBeenCalledWith( + false, + 'Modified saved workflow lost its edits before saving', + expect.objectContaining({ + method: 'workflowService.loadForSave', + isPersisted: true + }) + ) + }) + + it('keeps refusing to save an active tab that has no loaded content', async () => { + const tab = unloadedModifiedTab('workflows/active.json') + workflowStore.activeWorkflow = fromAny(tab) + const load = vi.spyOn(tab, 'load') + + await expect(service.saveWorkflow(tab)).rejects.toThrow( + 'Cannot save a workflow before it is loaded' + ) + + expect(load).not.toHaveBeenCalled() + expect(api.storeUserData).not.toHaveBeenCalled() + }) + + it('saves the draft the user edited when saved directly', async () => { + enableDrafts() + draftOf({ editedInDraft: true }, 200) + const tab = unloadedModifiedTab('workflows/background.json') + + expect(await service.saveWorkflow(tab)).toBe(true) + + expect(storedContent('workflows/background.json').extra).toEqual({ + editedInDraft: true + }) + expect(tab.isModified).toBe(false) + }) + + it('saves the draft of an unloaded saved tab under a new name', async () => { + enableDrafts() + draftOf({ editedInDraft: true }, 200) + const tab = unloadedModifiedTab('workflows/background.json') + + expect( + await service.saveWorkflowAs(tab, { filename: 'background copy' }) + ).toBe(true) + + expect(storedContent('workflows/background copy.json').extra).toEqual({ + editedInDraft: true + }) + expect( + vi + .mocked(api.storeUserData) + .mock.calls.some(([path]) => path === 'workflows/background.json') + ).toBe(false) + }) + + it('saves an unsaved tab that a reload restored without opening it', async () => { + const restored = workflowStore.createTemporary('Restored.json', { + ...blankGraph, + id: '7b1e2c3d-4f5a-4b6c-8d7e-9f0a1b2c3d4e' + }) + workflowStore.openWorkflowsInBackground({ right: [restored.path] }) + restored.isModified = true + expect(restored.isLoaded).toBe(false) + vi.mocked(useDialogService().prompt).mockResolvedValue('Restored') + + expect(await service.closeWorkflow(restored)).toBe(true) + + expect(storedContent('workflows/Restored.json').id).toBe( + '7b1e2c3d-4f5a-4b6c-8d7e-9f0a1b2c3d4e' + ) + expect(mockAssert).not.toHaveBeenCalledWith( + false, + 'Modified saved workflow lost its edits before saving', + expect.anything() + ) + }) + }) }) vi.mock(import('@vueuse/router'), async () => { diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index b3cb1e8e1a7..2e2e9579767 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -323,6 +323,33 @@ export const useWorkflowService = () => { if (!file) return downloadBlob(file, blob) } + + function lostUnsavedEdits(workflow: ComfyWorkflow): boolean { + return ( + workflow.isPersisted && + workflow.isModified && + workflow.content === workflow.originalContent + ) + } + + async function loadForSave(workflow: ComfyWorkflow): Promise { + if (workflow.isLoaded || workflowStore.isActive(workflow)) return true + await loadWorkflowInBackground(workflow) + if (!lostUnsavedEdits(workflow)) return true + reportWorkflowStateAnomaly( + 'Modified saved workflow lost its edits before saving', + 'workflowService.loadForSave', + workflow + ) + workflow.isModified = false + toast.warning(t('workflowService.unsavedChangesLostTitle'), { + description: t('workflowService.unsavedChangesLost', { + name: workflow.filename + }) + }) + return false + } + /** * Save a workflow as a new file * @param workflow The workflow to save @@ -334,6 +361,7 @@ export const useWorkflowService = () => { ): Promise => { const newFilename = options.filename ?? (await workflow.promptSave()) if (!newFilename) return false + if (!(await loadForSave(workflow))) return false const isApp = options.isApp ?? workflow.initialMode === 'app' const newPath = @@ -354,7 +382,6 @@ export const useWorkflowService = () => { if (isSelfOverwrite) { workflow.changeTracker?.prepareForSave() - // Call workflowStore.saveWorkflow directly: saveWorkflowAs emits its own is_new:true event below, so delegating to saveWorkflow() would also fire is_new:false and run prepareForSave a second time. await workflowStore.saveWorkflow(workflow) } else { let target: ComfyWorkflow @@ -387,6 +414,7 @@ export const useWorkflowService = () => { return await saveWorkflowAs(workflow) } + if (!(await loadForSave(workflow))) return true workflow.changeTracker?.prepareForSave() const isApp = workflow.initialMode === 'app' const expectedPath = diff --git a/src/platform/workflow/management/stores/comfyWorkflow.ts b/src/platform/workflow/management/stores/comfyWorkflow.ts index 2962b1fe961..d0dc10e50ae 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.ts @@ -279,7 +279,7 @@ function requireActiveStateForSave( method, workflow ) - throw new Error(`Cannot save workflow '${workflow.path}' before it is loaded`) + throw new Error('Cannot save a workflow before it is loaded') } export class ComfyWorkflow extends UserFile { diff --git a/src/platform/workflow/management/stores/workflowStore.test.ts b/src/platform/workflow/management/stores/workflowStore.test.ts index 2659e08f470..2a67f1a4546 100644 --- a/src/platform/workflow/management/stores/workflowStore.test.ts +++ b/src/platform/workflow/management/stores/workflowStore.test.ts @@ -157,6 +157,59 @@ describe('useWorkflowStore', () => { expect(workflow.size).toBe(2) }) + it('keeps the unsaved edits of a background tab whose file changed remotely', async () => { + await syncRemoteWorkflowsWithMeta([ + { path: 'edited.json', modified: 100, size: 1 }, + { path: 'active.json', modified: 100, size: 1 } + ]) + const edited = store.getWorkflowByPath('workflows/edited.json')! + vi.mocked(api.getUserData).mockImplementation( + async () => new Response(defaultGraphJSON, { status: 200 }) + ) + await store.openWorkflow(edited) + edited.changeTracker!.activeState = { + ...edited.changeTracker!.activeState, + extra: { unsaved: true } + } + edited.isModified = true + await store.openWorkflow( + store.getWorkflowByPath('workflows/active.json')! + ) + + await syncRemoteWorkflowsWithMeta([ + { path: 'edited.json', modified: 200, size: 2 }, + { path: 'active.json', modified: 100, size: 1 } + ]) + + expect(edited.isLoaded).toBe(true) + expect(edited.isModified).toBe(true) + expect(edited.activeState?.extra).toEqual({ unsaved: true }) + expect(edited.lastModified).toBe(100) + }) + + it('still drops the cached content of an unmodified background tab whose file changed', async () => { + await syncRemoteWorkflowsWithMeta([ + { path: 'clean.json', modified: 100, size: 1 }, + { path: 'active.json', modified: 100, size: 1 } + ]) + const clean = store.getWorkflowByPath('workflows/clean.json')! + vi.mocked(api.getUserData).mockImplementation( + async () => new Response(defaultGraphJSON, { status: 200 }) + ) + await store.openWorkflow(clean) + await store.openWorkflow( + store.getWorkflowByPath('workflows/active.json')! + ) + + await syncRemoteWorkflowsWithMeta([ + { path: 'clean.json', modified: 200, size: 2 }, + { path: 'active.json', modified: 100, size: 1 } + ]) + + expect(clean.isLoaded).toBe(false) + expect(clean.isModified).toBe(false) + }) + describe('node widget histories', () => { const rootGraphId = '00000000-0000-4000-8000-0000000000a1' @@ -1627,7 +1680,9 @@ describe('useWorkflowStore', () => { ? workflow.save() : workflow.saveAs('workflows/copy.json') - await expect(attempt).rejects.toThrow('before it is loaded') + await expect(attempt).rejects.toThrow( + /^Cannot save a workflow before it is loaded$/ + ) expect(api.storeUserData).not.toHaveBeenCalled() expect(workflow.content).toBe(contentBefore) expectReported('Workflow saved without an active state', { diff --git a/src/platform/workflow/management/stores/workflowStore.ts b/src/platform/workflow/management/stores/workflowStore.ts index 6e18ce70640..3da568e2b54 100644 --- a/src/platform/workflow/management/stores/workflowStore.ts +++ b/src/platform/workflow/management/stores/workflowStore.ts @@ -432,6 +432,8 @@ export const useWorkflowStore = defineStore('workflow', () => { const isActiveWorkflow = activeWorkflow.value?.path === existingWorkflow.path + if (!isActiveWorkflow && existingWorkflow.isModified) return + const nextLastModified = Math.max( existingWorkflow.lastModified, file.modified @@ -446,12 +448,10 @@ export const useWorkflowStore = defineStore('workflow', () => { existingWorkflow.size = file.size } - // Never unload the active workflow - it may contain unsaved in-memory edits. if (isActiveWorkflow) { return } - // If nothing changed, keep any loaded content cached. if (isMetadataUnchanged) { return } diff --git a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.test.ts index 8c9d85c7df5..9d7a33556f6 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.test.ts @@ -882,9 +882,7 @@ describe('picking a target tab', () => { vi.mocked(useWorkflowService().saveWorkflowAs).mockImplementationOnce( async (tab) => { if (!tab.isLoaded) - throw new Error( - `Cannot save workflow '${tab.path}' before it is loaded` - ) + throw new Error('Cannot save a workflow before it is loaded') saved = true return true } @@ -948,9 +946,7 @@ describe('picking a target tab', () => { vi.mocked(useWorkflowService().saveWorkflowAs).mockImplementationOnce( async (tab) => { if (!tab.isLoaded) - throw new Error( - `Cannot save workflow '${tab.path}' before it is loaded` - ) + throw new Error('Cannot save a workflow before it is loaded') saved = true return true } From e2491c728d41a8d92de60ceb1cf9048e2995f40d Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Thu, 5 Nov 2026 08:04:35 +0000 Subject: [PATCH 2/2] [automated] Apply ESLint and Oxfmt fixes --- .../core/services/workflowService.test.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 9405ab9ffed..f415f262794 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -3941,15 +3941,16 @@ describe('useWorkflowService', () => { } function draftOf(extra: Record, updatedAt: number) { - vi.mocked(useWorkflowDraftStoreV2().getDraft).mockImplementation((path) => - path === 'workflows/background.json' - ? { - data: JSON.stringify({ ...defaultGraph, extra }), - name: 'background.json', - isTemporary: false, - updatedAt - } - : null + vi.mocked(useWorkflowDraftStoreV2().getDraft).mockImplementation( + (path) => + path === 'workflows/background.json' + ? { + data: JSON.stringify({ ...defaultGraph, extra }), + name: 'background.json', + isTemporary: false, + updatedAt + } + : null ) }