diff --git a/src/locales/en/main.json b/src/locales/en/main.json index ae62f6ae5d5..55595a14c7e 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -1364,7 +1364,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 b97ba364386..eb2ce8e4840 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -45,6 +45,7 @@ import type { AppMode } from '@comfyorg/graph-model/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 }) @@ -3899,6 +3900,175 @@ 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 9e5ec8926d8..4a4b416d46a 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -326,6 +326,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 @@ -337,6 +364,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 = @@ -357,7 +385,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 @@ -390,6 +417,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 b8145067d9e..0b2cbdbc808 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.ts @@ -280,7 +280,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 8eccba45f99..cf77b200072 100644 --- a/src/platform/workflow/management/stores/workflowStore.test.ts +++ b/src/platform/workflow/management/stores/workflowStore.test.ts @@ -169,6 +169,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' @@ -1664,7 +1717,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 a1d636ed939..e4e164b2918 100644 --- a/src/platform/workflow/management/stores/workflowStore.ts +++ b/src/platform/workflow/management/stores/workflowStore.ts @@ -437,6 +437,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 @@ -451,12 +453,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 46727cc19be..60693311530 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.test.ts @@ -900,9 +900,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 } @@ -966,9 +964,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 }