Skip to content
Merged
4 changes: 3 additions & 1 deletion src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -1366,7 +1366,9 @@
"savedAsApp": "Converted to app workflow",
"savedAsWorkflow": "Converted to node graph only workflow",
"unreadableWorkflowTitle": "Can't open this workflow",
"unreadableWorkflowMessage": "The saved file for {name} is empty or damaged, so it can't be opened. You can delete it from your workflows."
"unreadableWorkflowMessage": "The saved file for {name} is empty or damaged, so it can't be opened. You can delete it from your workflows.",
"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?",
Expand Down
169 changes: 169 additions & 0 deletions src/platform/workflow/core/services/workflowService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import type { AppMode } from '@comfyorg/graph-model/appMode'
import { isValidUuid } from '@/utils/formatUtil'
import { zeroUuid } from '@comfyorg/graph-model/uuid'
import { t } from '@/i18n'
import { api } from '@/scripts/api'
import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort'

vi.mock(import('firebase/auth'), { spy: true })
Expand Down Expand Up @@ -4250,6 +4251,174 @@ describe('useWorkflowService', () => {
expect(workflowStore.saveWorkflow).toHaveBeenCalledWith(workflow)
})
})

describe('saving a tab that is not loaded', () => {
let workflowStore: ReturnType<typeof useWorkflowStore>
let service: ReturnType<typeof useWorkflowService>

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<string, unknown>, 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)
})
Comment thread
christian-byrne marked this conversation as resolved.
Resolved

it('saves the draft of an unloaded saved tab under a new name', async () => {
enableDrafts()
draftOf({ editedInDraft: true }, 200)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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 () => {
Expand Down
30 changes: 29 additions & 1 deletion src/platform/workflow/core/services/workflowService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,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<boolean> {
if (workflow.isLoaded || workflowStore.isActive(workflow)) return true
await loadWorkflowInBackground(workflow)
if (!lostUnsavedEdits(workflow)) return true
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
Expand All @@ -356,6 +383,7 @@ export const useWorkflowService = () => {
): Promise<boolean> => {
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 =
Expand All @@ -376,7 +404,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
Expand Down Expand Up @@ -409,6 +436,7 @@ export const useWorkflowService = () => {
return await saveWorkflowAs(workflow)
}

if (!(await loadForSave(workflow))) return true
workflow.changeTracker?.prepareForSave()
const isApp = workflow.initialMode === 'app'
const expectedPath =
Expand Down
2 changes: 1 addition & 1 deletion src/platform/workflow/management/stores/comfyWorkflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,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 {
Expand Down
57 changes: 56 additions & 1 deletion src/platform/workflow/management/stores/workflowStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,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'

Expand Down Expand Up @@ -1725,7 +1778,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', {
Expand Down
4 changes: 2 additions & 2 deletions src/platform/workflow/management/stores/workflowStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,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
Expand All @@ -457,12 +459,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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -899,9 +899,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
}
Expand Down Expand Up @@ -965,9 +963,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
}
Expand Down
Loading