From 49b829c6343853c2048203600449e915d604589f Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 15:22:47 -0700 Subject: [PATCH 01/52] test: cover storage scope resolution --- .../persistence/base/storageKeys.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/platform/workflow/persistence/base/storageKeys.test.ts b/src/platform/workflow/persistence/base/storageKeys.test.ts index d6c28c3631d..5e99dd0543e 100644 --- a/src/platform/workflow/persistence/base/storageKeys.test.ts +++ b/src/platform/workflow/persistence/base/storageKeys.test.ts @@ -85,6 +85,25 @@ describe('storageKeys', () => { }) }) + describe('resolveStorageScope', () => { + it('combines user and workspace in cloud', async () => { + const { resolveStorageScope } = await import('./storageKeys') + expect(resolveStorageScope('user-a', 'ws-1')).toBe('user-a:ws-1') + }) + + it('returns null in cloud until the user is resolved', async () => { + const { resolveStorageScope } = await import('./storageKeys') + expect(resolveStorageScope(null, 'ws-1')).toBeNull() + }) + + it('ignores identity outside cloud', async () => { + mockDistributionTypes.isCloud = false + const { resolveStorageScope } = await import('./storageKeys') + expect(resolveStorageScope(null, 'ws-1')).toBe('personal') + expect(resolveStorageScope('user-a', 'ws-1')).toBe('personal') + }) + }) + describe('StorageKeys', () => { it('generates draftIndex key with workspace scope', async () => { const { StorageKeys } = await import('./storageKeys') From 078e3c30c866c19dc641518b33ed5364fd67fe5d Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 15:23:13 -0700 Subject: [PATCH 02/52] fix: resolve workflow storage scope from user and workspace --- .../workflow/persistence/base/storageKeys.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/platform/workflow/persistence/base/storageKeys.ts b/src/platform/workflow/persistence/base/storageKeys.ts index 83f9deca776..c5b7e01fb4f 100644 --- a/src/platform/workflow/persistence/base/storageKeys.ts +++ b/src/platform/workflow/persistence/base/storageKeys.ts @@ -28,6 +28,19 @@ export function getWorkspaceId(): string { } } +/** + * Resolves the localStorage scope for workflow drafts. + * Cloud drafts belong to one user in one workspace, so the scope is + * `${userId}:${workspaceId}` and unresolvable until the user is known. + */ +export function resolveStorageScope( + userId: string | null, + workspaceId: string +): string | null { + if (!isCloud) return 'personal' + return userId ? `${userId}:${workspaceId}` : null +} + /** * Storage key generators for V2 workflow persistence. * From 5680f8f0e5faa226a6e0afc9ea4b6cf451cba793 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 15:28:48 -0700 Subject: [PATCH 03/52] test: cover scoped workflow storage gate and wipe --- .../persistence/base/storageIO.test.ts | 113 ++++++++++++++++-- 1 file changed, 101 insertions(+), 12 deletions(-) diff --git a/src/platform/workflow/persistence/base/storageIO.test.ts b/src/platform/workflow/persistence/base/storageIO.test.ts index a4105d8e6f7..755f3614ac1 100644 --- a/src/platform/workflow/persistence/base/storageIO.test.ts +++ b/src/platform/workflow/persistence/base/storageIO.test.ts @@ -2,8 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { DraftIndexV2, DraftPayloadV2 } from './draftTypes' import { - clearAllWorkflowStorage, clearWorkflowRestoreState, + clearWorkflowStorageForScope, deleteOrphanPayloads, deletePayload, deletePayloads, @@ -19,6 +19,9 @@ import { writePayload } from './storageIO' +const mockDistributionTypes = vi.hoisted(() => ({ isCloud: false })) +vi.mock(import('@/platform/distribution/types'), () => mockDistributionTypes) + describe('storageIO', () => { beforeEach(() => { vi.resetModules() @@ -276,11 +279,10 @@ describe('storageIO', () => { }) }) - describe('clearAllWorkflowStorage', () => { - it('clears all restorable workflow keys from localStorage', () => { + describe('clearWorkflowStorageForScope', () => { + it('clears only the given scope and unscoped legacy keys from localStorage', () => { localStorage.setItem('Comfy.Workflow.DraftIndex.v2:ws-1', '{}') localStorage.setItem('Comfy.Workflow.Draft.v2:ws-1:abc', '{}') - localStorage.setItem('Comfy.Workflow.Draft.v2:ws-2:def', '{}') localStorage.setItem('Comfy.Workflow.LastActivePath:ws-1', '{}') localStorage.setItem('Comfy.Workflow.LastOpenPaths:ws-1', '{}') localStorage.setItem('Comfy.Workflow.Drafts:ws-1', '{}') @@ -291,15 +293,23 @@ describe('storageIO', () => { localStorage.setItem('Comfy.ActiveWorkflowIndex', '0') localStorage.setItem('Comfy.PreviousWorkflow', 'workflows/old.json') localStorage.setItem('workflow', '{}') + localStorage.setItem('Comfy.Workflow.DraftIndex.v2:ws-10', '{}') + localStorage.setItem('Comfy.Workflow.Draft.v2:ws-10:def', '{}') + localStorage.setItem('Comfy.Workflow.LastActivePath:ws-10', '{}') localStorage.setItem('unrelated', 'keep') - clearAllWorkflowStorage() + clearWorkflowStorageForScope('ws-1') expect( - [...Array(localStorage.length)].map((_, index) => - localStorage.key(index) - ) - ).toEqual(['unrelated']) + [...Array(localStorage.length)] + .map((_, index) => localStorage.key(index)) + .sort() + ).toEqual([ + 'Comfy.Workflow.Draft.v2:ws-10:def', + 'Comfy.Workflow.DraftIndex.v2:ws-10', + 'Comfy.Workflow.LastActivePath:ws-10', + 'unrelated' + ]) expect(localStorage.getItem('unrelated')).toBe('keep') }) @@ -316,7 +326,7 @@ describe('storageIO', () => { sessionStorage.setItem('workflow:client-1', '{}') sessionStorage.setItem('unrelated', 'keep') - clearAllWorkflowStorage() + clearWorkflowStorageForScope('ws-1') expect( sessionStorage.getItem('Comfy.Workflow.ActivePath:client-1') @@ -341,7 +351,7 @@ describe('storageIO', () => { const isolatedStorageIO = await import('./storageIO') isolatedStorageIO.prepareWorkflowLogoutTransition() - isolatedStorageIO.clearAllWorkflowStorage() + isolatedStorageIO.clearWorkflowStorageForScope('ws-1') expect(isolatedStorageIO.isStorageAvailable()).toBe(false) expect( @@ -377,7 +387,7 @@ describe('storageIO', () => { sessionStorage.setItem('Comfy.Workflow.ActivePath:client-1', '{}') markStorageUnavailable() - clearAllWorkflowStorage() + clearWorkflowStorageForScope('personal') expect( localStorage.getItem('Comfy.Workflow.LastActivePath:personal') @@ -388,6 +398,85 @@ describe('storageIO', () => { }) }) + describe('storage scope', () => { + const emptyIndex: DraftIndexV2 = { + v: 2, + updatedAt: 1, + order: [], + entries: {} + } + + beforeEach(() => { + mockDistributionTypes.isCloud = true + sessionStorage.setItem( + 'Comfy.Workspace.Current', + JSON.stringify({ type: 'team', id: 'ws-1' }) + ) + }) + + it('defers writes in cloud until the storage identity is resolved', async () => { + const isolatedStorageIO = await import('./storageIO') + + expect(isolatedStorageIO.getStorageScope()).toBeNull() + expect(isolatedStorageIO.getStorageWriteGate()).toBe('deferred') + expect(isolatedStorageIO.isStorageAvailable()).toBe(false) + expect(isolatedStorageIO.writeIndex('ws-1', emptyIndex)).toBe(false) + expect(localStorage).toHaveLength(0) + }) + + it('scopes storage to the resolved user and current workspace', async () => { + const isolatedStorageIO = await import('./storageIO') + + isolatedStorageIO.setStorageIdentity('user-a') + + expect(isolatedStorageIO.getStorageScope()).toBe('user-a:ws-1') + expect(isolatedStorageIO.getStorageWriteGate()).toBe('open') + expect(isolatedStorageIO.isStorageAvailable()).toBe(true) + expect(isolatedStorageIO.writeIndex('user-a:ws-1', emptyIndex)).toBe( + true + ) + }) + + it('defers writes again once the identity is dropped', async () => { + const isolatedStorageIO = await import('./storageIO') + isolatedStorageIO.setStorageIdentity('user-a') + + isolatedStorageIO.setStorageIdentity(null) + + expect(isolatedStorageIO.getStorageScope()).toBeNull() + expect(isolatedStorageIO.getStorageWriteGate()).toBe('deferred') + }) + + it('reports closed rather than deferred when storage is unavailable', async () => { + const isolatedStorageIO = await import('./storageIO') + isolatedStorageIO.setStorageIdentity('user-a') + + isolatedStorageIO.markStorageUnavailable() + + expect(isolatedStorageIO.getStorageWriteGate()).toBe('closed') + expect(isolatedStorageIO.isStorageAvailable()).toBe(false) + }) + + it('defers writes across a logout transition and reopens on completion', async () => { + const isolatedStorageIO = await import('./storageIO') + isolatedStorageIO.setStorageIdentity('user-a') + + isolatedStorageIO.prepareWorkflowLogoutTransition() + expect(isolatedStorageIO.getStorageWriteGate()).toBe('deferred') + + isolatedStorageIO.completeWorkflowLogoutTransition() + expect(isolatedStorageIO.getStorageWriteGate()).toBe('open') + }) + + it('uses the personal scope without an identity outside cloud', async () => { + mockDistributionTypes.isCloud = false + const isolatedStorageIO = await import('./storageIO') + + expect(isolatedStorageIO.getStorageScope()).toBe('personal') + expect(isolatedStorageIO.getStorageWriteGate()).toBe('open') + }) + }) + describe('workflow storage transitions', () => { it('blocks writes and clears restore state when a persistence flush fails', async () => { const isolatedStorageIO = await import('./storageIO') From 561b2773769185f3c43e25e858ef8df850539c45 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 15:31:05 -0700 Subject: [PATCH 04/52] fix: gate workflow storage on resolved identity and scope wipes --- .../workflow/persistence/base/storageIO.ts | 38 ++++++++++++++++--- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index dede097a90f..6873cff288f 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -10,9 +10,10 @@ import type { DraftPayloadV2, OpenPathsPointer } from './draftTypes' -import { StorageKeys } from './storageKeys' +import { StorageKeys, getWorkspaceId, resolveStorageScope } from './storageKeys' type StorageAvailability = 'available' | 'unavailable' +type StorageWriteGate = 'open' | 'deferred' | 'closed' type WorkflowStorageState = | { status: 'ready'; availability: StorageAvailability } | { @@ -31,8 +32,23 @@ let workflowStorageState: WorkflowStorageState = { status: 'ready', availability: 'available' } +let storageIdentity: string | null = null const pendingPersistenceFlushes = new Set<() => void>() +export function setStorageIdentity(userId: string | null): void { + storageIdentity = userId +} + +export function getStorageScope(): string | null { + return resolveStorageScope(storageIdentity, getWorkspaceId()) +} + +export function getStorageWriteGate(): StorageWriteGate { + if (workflowStorageState.status === 'transitioning') return 'deferred' + if (getStorageScope() === null) return 'deferred' + return workflowStorageState.availability === 'available' ? 'open' : 'closed' +} + export function registerWorkflowPersistenceFlush( flush: () => void ): () => void { @@ -51,10 +67,7 @@ function flushPendingWorkflowPersistence(): void { } export function isStorageAvailable(): boolean { - return ( - workflowStorageState.status === 'ready' && - workflowStorageState.availability === 'available' - ) + return getStorageWriteGate() === 'open' } export function markStorageUnavailable(): void { @@ -552,6 +565,21 @@ export function completeWorkflowLogoutTransition(): void { } } +export function clearWorkflowStorageForScope(scope: string): void { + const localKeys = [ + StorageKeys.draftIndex(scope), + StorageKeys.lastActivePath(scope), + StorageKeys.lastOpenPaths(scope), + `Comfy.Workflow.Drafts:${scope}`, + `Comfy.Workflow.DraftOrder:${scope}`, + ...legacyLocalRestoreKeys + ] + const localPrefixes = [`${StorageKeys.prefixes.draftPayload}${scope}:`] + + removeStorageKeys(localStorage, localKeys, localPrefixes) + removeStorageKeys(sessionStorage, sessionRestoreKeys, sessionRestorePrefixes) +} + export function clearAllWorkflowStorage(): void { const localPrefixes = [ StorageKeys.prefixes.draftIndex, From baa46b20d0b2b62cd4f7d3daef6926644ff12521 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 15:40:42 -0700 Subject: [PATCH 05/52] test: cover moving workspace drafts into a user scope --- .../migration/migrateWorkspaceToScope.test.ts | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts new file mode 100644 index 00000000000..f5947784909 --- /dev/null +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -0,0 +1,183 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { DraftIndexV2 } from '../base/draftTypes' +import { hashPath } from '../base/hashUtil' +import { StorageKeys } from '../base/storageKeys' +import { migrateWorkspaceToScope } from './migrateWorkspaceToScope' + +const sourceWorkspaceId = 'workspace-a' +const destinationScope = 'user-a:workspace-a' +const draftPath = 'workflows/one.json' +const draftKey = hashPath(draftPath) + +function buildIndex(): DraftIndexV2 { + return { + v: 2, + updatedAt: 10, + order: [draftKey], + entries: { + [draftKey]: { + path: draftPath, + name: 'one', + isTemporary: false, + updatedAt: 10 + } + } + } +} + +function seedSourceWorkspace() { + localStorage.setItem( + StorageKeys.draftIndex(sourceWorkspaceId), + JSON.stringify(buildIndex()) + ) + localStorage.setItem( + StorageKeys.draftPayload(draftPath, sourceWorkspaceId), + JSON.stringify({ data: '{"nodes":[]}', updatedAt: 10 }) + ) + localStorage.setItem( + StorageKeys.lastActivePath(sourceWorkspaceId), + JSON.stringify({ workspaceId: sourceWorkspaceId, path: draftPath }) + ) + localStorage.setItem( + StorageKeys.lastOpenPaths(sourceWorkspaceId), + JSON.stringify({ + workspaceId: sourceWorkspaceId, + paths: [draftPath], + activeIndex: 0 + }) + ) +} + +function readJson(key: string): unknown { + const json = localStorage.getItem(key) + return json === null ? null : JSON.parse(json) +} + +describe('migrateWorkspaceToScope', () => { + beforeEach(() => { + vi.resetModules() + }) + + it('moves drafts and restore pointers into the scope and removes the workspace copy', () => { + seedSourceWorkspace() + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + buildIndex() + ) + expect( + readJson(StorageKeys.draftPayload(draftPath, destinationScope)) + ).toEqual({ data: '{"nodes":[]}', updatedAt: 10 }) + expect(readJson(StorageKeys.lastActivePath(destinationScope))).toEqual({ + workspaceId: destinationScope, + path: draftPath + }) + expect(readJson(StorageKeys.lastOpenPaths(destinationScope))).toEqual({ + workspaceId: destinationScope, + paths: [draftPath], + activeIndex: 0 + }) + + expect( + localStorage.getItem(StorageKeys.draftIndex(sourceWorkspaceId)) + ).toBe(null) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, sourceWorkspaceId) + ) + ).toBe(null) + expect( + localStorage.getItem(StorageKeys.lastActivePath(sourceWorkspaceId)) + ).toBe(null) + expect( + localStorage.getItem(StorageKeys.lastOpenPaths(sourceWorkspaceId)) + ).toBe(null) + }) + + it('leaves an already scoped destination untouched', () => { + seedSourceWorkspace() + const destinationIndex: DraftIndexV2 = { + v: 2, + updatedAt: 99, + order: [], + entries: {} + } + localStorage.setItem( + StorageKeys.draftIndex(destinationScope), + JSON.stringify(destinationIndex) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + destinationIndex + ) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, destinationScope) + ) + ).toBe(null) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + }) + + it('does nothing when the workspace has no draft index', () => { + localStorage.setItem( + StorageKeys.draftPayload(draftPath, sourceWorkspaceId), + JSON.stringify({ data: '{}', updatedAt: 1 }) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(localStorage.getItem(StorageKeys.draftIndex(destinationScope))).toBe( + null + ) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, destinationScope) + ) + ).toBe(null) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, sourceWorkspaceId) + ) + ).not.toBe(null) + }) + + it('keeps the workspace copy and writes no scoped index when a payload copy hits the quota', () => { + seedSourceWorkspace() + const destinationPayloadKey = StorageKeys.draftPayload( + draftPath, + destinationScope + ) + const originalSetItem = Storage.prototype.setItem + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function ( + this: Storage, + key: string, + value: string + ) { + if (key === destinationPayloadKey) { + throw new DOMException('Quota exceeded', 'QuotaExceededError') + } + originalSetItem.call(this, key, value) + }) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(localStorage.getItem(StorageKeys.draftIndex(destinationScope))).toBe( + null + ) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect( + readJson(StorageKeys.draftPayload(draftPath, sourceWorkspaceId)) + ).toEqual({ data: '{"nodes":[]}', updatedAt: 10 }) + expect(readJson(StorageKeys.lastActivePath(sourceWorkspaceId))).not.toBe( + null + ) + }) +}) From 41ca6dff919bd7eff401afe1cb26aff8aed1a179 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 15:43:25 -0700 Subject: [PATCH 06/52] fix: move workspace drafts into the resolved user scope --- .../migration/migrateWorkspaceToScope.test.ts | 18 ++--- .../migration/migrateWorkspaceToScope.ts | 81 +++++++++++++++++++ 2 files changed, 89 insertions(+), 10 deletions(-) create mode 100644 src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index f5947784909..d1d5787553f 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -153,17 +153,15 @@ describe('migrateWorkspaceToScope', () => { draftPath, destinationScope ) - const originalSetItem = Storage.prototype.setItem - vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function ( - this: Storage, - key: string, - value: string - ) { - if (key === destinationPayloadKey) { - throw new DOMException('Quota exceeded', 'QuotaExceededError') + const realSetItem = localStorage.setItem.bind(localStorage) + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + if (key === destinationPayloadKey) { + throw new DOMException('Quota exceeded', 'QuotaExceededError') + } + realSetItem(key, value) } - originalSetItem.call(this, key, value) - }) + ) migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts new file mode 100644 index 00000000000..3a1657e99a7 --- /dev/null +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -0,0 +1,81 @@ +/** + * Workspace-to-scope migration + * + * Moves drafts stored under a bare workspace id into a user-scoped key space. + * The destination index is written last so a partial copy never looks + * complete, and the source is removed only after the destination is whole. + */ + +import { + deletePayloads, + getPayloadKeys, + readIndex, + readPayload, + writeIndex, + writePayload +} from '../base/storageIO' +import { StorageKeys } from '../base/storageKeys' + +const restorePointerKeys = [ + StorageKeys.lastActivePath, + StorageKeys.lastOpenPaths +] + +export function migrateWorkspaceToScope( + workspaceId: string, + scope: string +): void { + if (readIndex(scope) !== null) return + const index = readIndex(workspaceId) + if (index === null) return + + const draftKeys = getPayloadKeys(workspaceId) + const copied = + draftKeys.every((draftKey) => copyPayload(workspaceId, scope, draftKey)) && + restorePointerKeys.every((keyFor) => + copyRestorePointer(keyFor, workspaceId, scope) + ) && + writeIndex(scope, index) + + if (!copied) { + deletePayloads(scope, draftKeys) + return + } + + deletePayloads(workspaceId, draftKeys) + localStorage.removeItem(StorageKeys.draftIndex(workspaceId)) + for (const keyFor of restorePointerKeys) { + localStorage.removeItem(keyFor(workspaceId)) + } +} + +function copyPayload( + workspaceId: string, + scope: string, + draftKey: string +): boolean { + const payload = readPayload(workspaceId, draftKey) + if (payload === null) return true + return writePayload(scope, draftKey, payload) +} + +function copyRestorePointer( + keyFor: (workspaceId: string) => string, + workspaceId: string, + scope: string +): boolean { + const json = localStorage.getItem(keyFor(workspaceId)) + if (!json) return true + + try { + const pointer: unknown = JSON.parse(json) + if (typeof pointer !== 'object' || pointer === null) return true + localStorage.setItem( + keyFor(scope), + JSON.stringify({ ...pointer, workspaceId: scope }) + ) + return true + } catch { + return false + } +} From 05fe3eeb97ab954d6ae187ac00c7b1fe2fa4a312 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 15:53:31 -0700 Subject: [PATCH 07/52] test: cover scoped draft and tab pointer storage --- .../composables/useWorkflowTabState.test.ts | 99 +++++++++++-------- .../stores/workflowDraftStoreV2.scope.test.ts | 76 ++++++++++++++ 2 files changed, 133 insertions(+), 42 deletions(-) create mode 100644 src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts diff --git a/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts b/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts index b55c0347e89..4b13b75d1b4 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts @@ -9,45 +9,68 @@ vi.mock(import('@/scripts/api'), () => ({ vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) +async function loadTabState(userId: string | null) { + const { setStorageIdentity } = await import('../base/storageIO') + setStorageIdentity(userId) + const { useWorkflowTabState } = await import('./useWorkflowTabState') + return useWorkflowTabState() +} + +function setCurrentWorkspace(id: string) { + sessionStorage.setItem( + 'Comfy.Workspace.Current', + JSON.stringify({ type: 'team', id }) + ) +} + describe('useWorkflowTabState', () => { beforeEach(() => { vi.resetModules() + sessionStorage.clear() }) describe('activePath', () => { it('returns null when no pointer exists', async () => { - const { useWorkflowTabState } = await import('./useWorkflowTabState') - const { getActivePath } = useWorkflowTabState() + const { getActivePath } = await loadTabState('user-a') expect(getActivePath()).toBeNull() }) it('saves and retrieves active path', async () => { - const { useWorkflowTabState } = await import('./useWorkflowTabState') - const { getActivePath, setActivePath } = useWorkflowTabState() + const { getActivePath, setActivePath } = await loadTabState('user-a') setActivePath('workflows/test.json') expect(getActivePath()).toBe('workflows/test.json') }) + it('writes nothing and reads nothing while identity is unresolved', async () => { + const { getActivePath, setActivePath } = await loadTabState(null) + + setActivePath('workflows/test.json') + + expect(sessionStorage.length).toBe(0) + expect(getActivePath()).toBeNull() + }) + it('ignores pointer from different workspace', async () => { - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-1' }) - ) - const { useWorkflowTabState } = await import('./useWorkflowTabState') - const { setActivePath } = useWorkflowTabState() + setCurrentWorkspace('ws-1') + const { setActivePath } = await loadTabState('user-a') setActivePath('workflows/test.json') vi.resetModules() - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-2' }) - ) + setCurrentWorkspace('ws-2') + const { getActivePath } = await loadTabState('user-a') + + expect(getActivePath()).toBeNull() + }) - const { useWorkflowTabState: useWorkflowTabState2 } = - await import('./useWorkflowTabState') - const { getActivePath } = useWorkflowTabState2() + it('ignores pointer written by a different user in the same workspace', async () => { + setCurrentWorkspace('ws-1') + const { setActivePath } = await loadTabState('user-a') + setActivePath('workflows/test.json') + + vi.resetModules() + const { getActivePath } = await loadTabState('user-b') expect(getActivePath()).toBeNull() }) @@ -55,15 +78,13 @@ describe('useWorkflowTabState', () => { describe('openPaths', () => { it('returns null when no pointer exists', async () => { - const { useWorkflowTabState } = await import('./useWorkflowTabState') - const { getOpenPaths } = useWorkflowTabState() + const { getOpenPaths } = await loadTabState('user-a') expect(getOpenPaths()).toBeNull() }) it('saves and retrieves open paths', async () => { - const { useWorkflowTabState } = await import('./useWorkflowTabState') - const { getOpenPaths, setOpenPaths } = useWorkflowTabState() + const { getOpenPaths, setOpenPaths } = await loadTabState('user-a') const paths = ['workflows/a.json', 'workflows/b.json'] setOpenPaths(paths, 1) @@ -74,39 +95,33 @@ describe('useWorkflowTabState', () => { expect(result!.activeIndex).toBe(1) }) + it('writes nothing while identity is unresolved', async () => { + const { getOpenPaths, setOpenPaths } = await loadTabState(null) + + setOpenPaths(['workflows/test.json'], 0) + + expect(sessionStorage.length).toBe(0) + expect(getOpenPaths()).toBeNull() + }) + it('ignores pointer from different workspace', async () => { - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-1' }) - ) - const { useWorkflowTabState } = await import('./useWorkflowTabState') - const { setOpenPaths } = useWorkflowTabState() + setCurrentWorkspace('ws-1') + const { setOpenPaths } = await loadTabState('user-a') setOpenPaths(['workflows/test.json'], 0) vi.resetModules() - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-2' }) - ) - - const { useWorkflowTabState: useWorkflowTabState2 } = - await import('./useWorkflowTabState') - const { getOpenPaths } = useWorkflowTabState2() + setCurrentWorkspace('ws-2') + const { getOpenPaths } = await loadTabState('user-a') expect(getOpenPaths()).toBeNull() }) it('retains paths when staying in same workspace', async () => { - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-1' }) - ) - const { useWorkflowTabState } = await import('./useWorkflowTabState') - const { setOpenPaths, getOpenPaths } = useWorkflowTabState() + setCurrentWorkspace('ws-1') + const { setOpenPaths, getOpenPaths } = await loadTabState('user-a') setOpenPaths(['workflows/test.json'], 0) - // Simulate re-reading (same workspace, same clientId) const result = getOpenPaths() expect(result).not.toBeNull() expect(result!.paths).toEqual(['workflows/test.json']) diff --git a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts new file mode 100644 index 00000000000..635d2674dfd --- /dev/null +++ b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts @@ -0,0 +1,76 @@ +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { hashPath } from '../base/hashUtil' +import { readIndex, setStorageIdentity } from '../base/storageIO' +import { StorageKeys } from '../base/storageKeys' +import { useWorkflowDraftStoreV2 } from './workflowDraftStoreV2' + +vi.mock(import('@/scripts/api'), () => ({ + api: { clientId: 'test-client', initialClientId: 'test-client' } +})) + +vi.mock(import('@/scripts/app'), () => ({ + app: { loadGraphData: vi.fn().mockResolvedValue(undefined) } +})) + +vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) + +const PATH = 'workflows/test.json' +const META = { name: 'test', isTemporary: false } + +describe('workflowDraftStoreV2 storage scope', () => { + beforeEach(() => { + localStorage.clear() + sessionStorage.clear() + setActivePinia(createPinia()) + setStorageIdentity(null) + }) + + it('reads nothing and leaves storage untouched while the scope is unresolved', () => { + localStorage.setItem( + StorageKeys.draftPayload(PATH, 'personal'), + JSON.stringify({ data: '{}', updatedAt: 1 }) + ) + localStorage.setItem( + StorageKeys.draftIndex('personal'), + JSON.stringify({ + entries: { [hashPath(PATH)]: { path: PATH, ...META } }, + order: [hashPath(PATH)] + }) + ) + const store = useWorkflowDraftStoreV2() + + expect(store.getDraft(PATH)).toBeNull() + expect(store.getMostRecentPath()).toBeNull() + store.removeDraft(PATH) + + expect(localStorage.length).toBe(2) + }) + + it('keys drafts by the resolved user scope, not the bare workspace', () => { + setStorageIdentity('user-a') + const store = useWorkflowDraftStoreV2() + + expect(store.saveDraft(PATH, '{"a":1}', META)).toBe(true) + + expect(readIndex('user-a:personal')?.order).toEqual([hashPath(PATH)]) + expect(readIndex('personal')).toBeNull() + expect( + localStorage.getItem(StorageKeys.draftPayload(PATH, 'user-a:personal')) + ).not.toBeNull() + }) + + it('serves each user their own drafts after identity changes', () => { + setStorageIdentity('user-a') + const store = useWorkflowDraftStoreV2() + store.saveDraft(PATH, '{"owner":"a"}', META) + + setStorageIdentity('user-b') + expect(store.getDraft(PATH)).toBeNull() + store.saveDraft(PATH, '{"owner":"b"}', META) + + setStorageIdentity('user-a') + expect(store.getDraft(PATH)?.data).toBe('{"owner":"a"}') + }) +}) From 41eec657eb69c826b5a6e764445852a27ce1deb9 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 15:53:31 -0700 Subject: [PATCH 08/52] fix: key drafts and tab pointers by resolved storage scope --- .../composables/useWorkflowTabState.ts | 31 ++++++++-------- .../stores/workflowDraftStoreV2.ts | 35 +++++++++---------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/platform/workflow/persistence/composables/useWorkflowTabState.ts b/src/platform/workflow/persistence/composables/useWorkflowTabState.ts index b23a0c8d9d1..74a1a2a8983 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowTabState.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowTabState.ts @@ -6,9 +6,9 @@ */ import type { ActivePathPointer, OpenPathsPointer } from '../base/draftTypes' -import { getWorkspaceId } from '../base/storageKeys' import { clearActivePath, + getStorageScope, readActivePath, readOpenPaths, writeActivePath, @@ -34,10 +34,10 @@ export function useWorkflowTabState() { */ function getActivePath(): string | null { const clientId = getClientId() - const workspaceId = getWorkspaceId() - if (!clientId) return null + const scope = getStorageScope() + if (!clientId || !scope) return null - const pointer = readActivePath(clientId, workspaceId) + const pointer = readActivePath(clientId, scope) return pointer?.path ?? null } @@ -46,11 +46,11 @@ export function useWorkflowTabState() { */ function setActivePath(path: string): void { const clientId = getClientId() - const workspaceId = getWorkspaceId() - if (!clientId) return + const scope = getStorageScope() + if (!clientId || !scope) return const pointer: ActivePathPointer = { - workspaceId, + workspaceId: scope, path } writeActivePath(clientId, pointer) @@ -59,9 +59,10 @@ export function useWorkflowTabState() { /** Forgets the active workflow, so nothing is restored on the next boot. */ function clearActivePathPointer(): void { const clientId = getClientId() - if (!clientId) return + const scope = getStorageScope() + if (!clientId || !scope) return - clearActivePath(clientId, getWorkspaceId()) + clearActivePath(clientId, scope) } /** @@ -70,10 +71,10 @@ export function useWorkflowTabState() { */ function getOpenPaths(): { paths: string[]; activeIndex: number } | null { const clientId = getClientId() - const workspaceId = getWorkspaceId() - if (!clientId) return null + const scope = getStorageScope() + if (!clientId || !scope) return null - const pointer = readOpenPaths(clientId, workspaceId) + const pointer = readOpenPaths(clientId, scope) if (!pointer) return null return { paths: pointer.paths, activeIndex: pointer.activeIndex } @@ -84,11 +85,11 @@ export function useWorkflowTabState() { */ function setOpenPaths(paths: string[], activeIndex: number): void { const clientId = getClientId() - const workspaceId = getWorkspaceId() - if (!clientId) return + const scope = getStorageScope() + if (!clientId || !scope) return const pointer: OpenPathsPointer = { - workspaceId, + workspaceId: scope, paths, activeIndex } diff --git a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts index da7a745c009..e6200fd9ed6 100644 --- a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts +++ b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts @@ -24,12 +24,12 @@ import { upsertEntry } from '../base/draftCacheV2' import { hashPath } from '../base/hashUtil' -import { getWorkspaceId } from '../base/storageKeys' import { deleteOrphanPayloads, deletePayload, deletePayloads, getPayloadKeys, + getStorageScope, isStorageAvailable, markStorageUnavailable, readIndex, @@ -53,19 +53,12 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { // Key is workspaceId, value is the cached index const indexCacheByWorkspace = ref>({}) - /** - * Gets the current workspace ID fresh (not cached). - * This ensures operations use the correct workspace after switches. - */ - function currentWorkspaceId(): string { - return getWorkspaceId() - } - /** * Loads the index from localStorage or creates empty. */ function loadIndex(): DraftIndexV2 { - const workspaceId = currentWorkspaceId() + const workspaceId = getStorageScope() + if (!workspaceId) return createEmptyIndex() const cached = getCachedIndex(workspaceId) if (cached) return cached @@ -97,7 +90,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Persists the current index to localStorage. */ function persistIndex(index: DraftIndexV2): boolean { - const workspaceId = currentWorkspaceId() + const workspaceId = getStorageScope() + if (!workspaceId) return false indexCacheByWorkspace.value[workspaceId] = index return writeIndex(workspaceId, index) } @@ -107,9 +101,9 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Primes index cache, writes payload, then persists updated index. */ function saveDraft(path: string, data: string, meta: DraftMeta): boolean { - if (!isStorageAvailable()) return false + const workspaceId = getStorageScope() + if (!workspaceId || !isStorageAvailable()) return false - const workspaceId = currentWorkspaceId() const draftKey = hashPath(path) const now = Date.now() @@ -163,7 +157,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { data: string, meta: DraftMeta ): boolean { - const workspaceId = currentWorkspaceId() + const workspaceId = getStorageScope() + if (!workspaceId) return false const draftKey = hashPath(path) let currentIndex = loadIndex() @@ -259,7 +254,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Removes a draft. */ function removeDraft(path: string): void { - const workspaceId = currentWorkspaceId() + const workspaceId = getStorageScope() + if (!workspaceId) return const index = loadIndex() const { index: newIndex, removedKey } = removeEntry(index, path) @@ -273,7 +269,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Moves a draft from one path to another (rename). */ function moveDraft(oldPath: string, newPath: string, name: string): void { - const workspaceId = currentWorkspaceId() + const workspaceId = getStorageScope() + if (!workspaceId) return const index = loadIndex() const result = moveEntry(index, oldPath, newPath, name) @@ -304,7 +301,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { isTemporary: boolean updatedAt: number } | null { - const workspaceId = currentWorkspaceId() + const workspaceId = getStorageScope() + if (!workspaceId) return null const index = loadIndex() const entry = getEntryByPath(index, path) if (!entry) return null @@ -418,7 +416,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Resets the store (clears in-memory cache for current workspace). */ function reset(): void { - const workspaceId = currentWorkspaceId() + const workspaceId = getStorageScope() + if (!workspaceId) return delete indexCacheByWorkspace.value[workspaceId] } From ba25a542e6af0f977d11d7796027714918964b68 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 16:17:50 -0700 Subject: [PATCH 09/52] test: cover identity-scoped workflow persistence --- .../useWorkflowPersistenceV2.test.ts | 148 +++++++++++++++++- 1 file changed, 143 insertions(+), 5 deletions(-) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index e58c671b898..bb6d62a5301 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -199,6 +199,8 @@ describe('useWorkflowPersistenceV2', () => { routeMocks.query = {} preservedQueryMocks.payloads = {} distributionMocks.isCloud = false + storageIO.setStorageIdentity(null) + storageIO.resetStorageAvailable() Object.assign(useTeamWorkspaceStore(), { initState: 'uninitialized' }) Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: null }) }) @@ -753,6 +755,12 @@ describe('useWorkflowPersistenceV2', () => { .load() workflowStore.activeWorkflow = workflow mountWorkflowPersistence() + currentUserMocks.onUserResolved.mock.calls[0][0]({ id: 'user-a' }) + Object.assign(useTeamWorkspaceStore(), { + activeWorkspaceId: sourceWorkspaceId + }) + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + await nextTick() mocks.state.currentGraph = { nodes: [], @@ -762,11 +770,11 @@ describe('useWorkflowPersistenceV2', () => { const sourcePayloadKey = StorageKeys.draftPayload( workflow.path, - sourceWorkspaceId + `user-a:${sourceWorkspaceId}` ) const destinationPayloadKey = StorageKeys.draftPayload( workflow.path, - destinationWorkspaceId + `user-a:${destinationWorkspaceId}` ) expect(localStorage.getItem(sourcePayloadKey)).toBeNull() @@ -807,8 +815,6 @@ describe('useWorkflowPersistenceV2', () => { const onUserResolved = currentUserMocks.onUserResolved.mock.calls[0][0] onLogout() - expect(localStorage).toHaveLength(0) - expect(sessionStorage).toHaveLength(0) expect( storageIO.writePayload('workspace-a', 'blocked', { data: '{}', @@ -909,7 +915,7 @@ describe('useWorkflowPersistenceV2', () => { ) const destinationPayloadKey = StorageKeys.draftPayload( workflow.path, - destinationWorkspaceId + `user-b:${destinationWorkspaceId}` ) const personalPayloadKey = StorageKeys.draftPayload( workflow.path, @@ -937,4 +943,136 @@ describe('useWorkflowPersistenceV2', () => { expect(localStorage.getItem(personalPayloadKey)).toBeNull() expect(localStorage.getItem(destinationPayloadKey)).not.toBeNull() }) + + it('fences writes across an identity swap that skips logout', async () => { + distributionMocks.isCloud = true + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: 'workspace-a', type: 'team' }) + ) + const workflowStore = useWorkflowStore() + const workflow = await workflowStore + .createTemporary('IdentitySwap.json') + .load() + workflowStore.activeWorkflow = workflow + mountWorkflowPersistence() + const onUserResolved = currentUserMocks.onUserResolved.mock.calls[0][0] + + onUserResolved({ id: 'user-a' }) + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-a' }) + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + await nextTick() + mocks.state.currentGraph = { marker: 'user-a-edit' } + mocks.state.graphChangedHandler?.() + await vi.runAllTimersAsync() + + const userAPayloadKey = StorageKeys.draftPayload( + workflow.path, + 'user-a:workspace-a' + ) + const userBPayloadKey = StorageKeys.draftPayload( + workflow.path, + 'user-b:workspace-a' + ) + expect(localStorage.getItem(userAPayloadKey)).not.toBeNull() + + mocks.state.currentGraph = { marker: 'pending-during-swap' } + mocks.state.graphChangedHandler?.() + Object.assign(useTeamWorkspaceStore(), { initState: 'uninitialized' }) + onUserResolved({ id: 'user-b' }) + await vi.runAllTimersAsync() + + const userAPayload = JSON.parse(localStorage.getItem(userAPayloadKey)!) + expect(JSON.parse(userAPayload.data)).toEqual({ marker: 'user-a-edit' }) + expect(localStorage.getItem(userBPayloadKey)).toBeNull() + + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + await nextTick() + mocks.state.currentGraph = { marker: 'user-b-edit' } + mocks.state.graphChangedHandler?.() + await vi.runAllTimersAsync() + + expect(JSON.parse(localStorage.getItem(userAPayloadKey)!).data).toBe( + userAPayload.data + ) + const userBPayload = JSON.parse(localStorage.getItem(userBPayloadKey)!) + expect(JSON.parse(userBPayload.data)).toEqual({ marker: 'user-b-edit' }) + }) + + it('stays silent while the write gate is deferred on an unresolved identity', async () => { + distributionMocks.isCloud = true + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: 'workspace-a', type: 'team' }) + ) + const workflowStore = useWorkflowStore() + const workflow = await workflowStore + .createTemporary('Deferred.json') + .load() + workflowStore.activeWorkflow = workflow + mountWorkflowPersistence() + + mocks.state.currentGraph = { marker: 'before-identity' } + mocks.state.graphChangedHandler?.() + await vi.runAllTimersAsync() + + expect(mockToastAdd).not.toHaveBeenCalled() + expect( + localStorage.getItem( + StorageKeys.draftPayload(workflow.path, 'workspace-a') + ) + ).toBeNull() + }) + + it('moves workspace-scoped drafts into the resolved user scope', async () => { + distributionMocks.isCloud = true + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: 'workspace-a', type: 'team' }) + ) + const workspaceIndexKey = StorageKeys.draftIndex('workspace-a') + const workspacePayloadKey = StorageKeys.draftPayload( + 'Legacy.json', + 'workspace-a' + ) + localStorage.setItem( + workspaceIndexKey, + JSON.stringify({ + v: 2, + updatedAt: 1, + order: ['Legacy.json'], + entries: { + 'Legacy.json': { + path: 'Legacy.json', + name: 'Legacy', + isTemporary: true, + updatedAt: 1 + } + } + }) + ) + localStorage.setItem( + workspacePayloadKey, + JSON.stringify({ data: '{"marker":"legacy"}', updatedAt: 1 }) + ) + mountWorkflowPersistence() + + currentUserMocks.onUserResolved.mock.calls[0][0]({ id: 'user-a' }) + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-a' }) + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + await nextTick() + + expect(localStorage.getItem(workspaceIndexKey)).toBeNull() + expect(localStorage.getItem(workspacePayloadKey)).toBeNull() + expect( + localStorage.getItem(StorageKeys.draftIndex('user-a:workspace-a')) + ).not.toBeNull() + expect( + JSON.parse( + localStorage.getItem( + StorageKeys.draftPayload('Legacy.json', 'user-a:workspace-a') + )! + ).data + ).toBe('{"marker":"legacy"}') + }) }) From d147de7891d14da6be59695e83e394081c65bed2 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 16:26:42 -0700 Subject: [PATCH 10/52] fix: fence and scope workflow persistence on resolved identity --- .../composables/useWorkflowPersistenceV2.ts | 56 +++++++++++++++---- 1 file changed, 46 insertions(+), 10 deletions(-) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts index 51e555aa89b..2a3ec93d0cf 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts @@ -32,12 +32,17 @@ import { import { PERSIST_DEBOUNCE_MS } from '../base/draftTypes' import type { StartupOutcome } from '../base/draftTypes' import { - clearAllWorkflowStorage, completeWorkflowLogoutTransition, + getStorageScope, + getStorageWriteGate, prepareWorkflowLogoutTransition, - registerWorkflowPersistenceFlush + readIndex, + registerWorkflowPersistenceFlush, + setStorageIdentity } from '../base/storageIO' +import { getWorkspaceId } from '../base/storageKeys' import { migrateV1toV2 } from '../migration/migrateV1toV2' +import { migrateWorkspaceToScope } from '../migration/migrateWorkspaceToScope' import { useWorkflowDraftStoreV2 } from '../stores/workflowDraftStoreV2' import { useWorkflowTabState } from './useWorkflowTabState' import { useSharedWorkflowUrlLoader } from '@/platform/workflow/sharing/composables/useSharedWorkflowUrlLoader' @@ -67,8 +72,20 @@ export function useWorkflowPersistenceV2() { stopWorkspaceReadinessWatcher = undefined } - // Run migration on module load, passing clientId for tab state migration - migrateV1toV2(undefined, api.clientId ?? api.initialClientId ?? undefined) + function ensureScopedStorage(clientId?: string): void { + const workspaceId = getWorkspaceId() + const scope = getStorageScope() + if (scope === null) return + if (scope === workspaceId) { + migrateV1toV2(scope, clientId) + return + } + if (readIndex(scope) !== null) return + migrateV1toV2(workspaceId, clientId) + migrateWorkspaceToScope(workspaceId, scope) + } + + ensureScopedStorage(api.clientId ?? api.initialClientId ?? undefined) const ensureTemplateQueryFromIntent = async () => { hydratePreservedQuery(TEMPLATE_NAMESPACE) @@ -108,6 +125,7 @@ export function useWorkflowPersistenceV2() { // Skip if unchanged if (workflowJson === lastSavedJsonByPath.value[workflowPath]) return + if (getStorageWriteGate() === 'deferred') return // Save to V2 draft store const saved = draftStore.saveDraft(workflowPath, workflowJson, { @@ -147,16 +165,34 @@ export function useWorkflowPersistenceV2() { ) window.addEventListener('pagehide', flushPendingPersistence) - onUserLogout(() => { - if (!isCloud) return + let resolvedUserId: string | null = null + + function fenceIdentityChange(): void { stopPendingWorkspaceReadinessWatcher() debouncedPersist.cancel() prepareWorkflowLogoutTransition() - clearAllWorkflowStorage() + lastSavedJsonByPath.value = {} + } + + function releaseIdentityFence(): void { + completeWorkflowLogoutTransition() + ensureScopedStorage() + } + + onUserLogout(() => { + if (!isCloud) return + fenceIdentityChange() + resolvedUserId = null + setStorageIdentity(null) }) - onUserResolved(() => { + onUserResolved((user) => { if (!isCloud) return + if (resolvedUserId !== null && resolvedUserId !== user.id) { + fenceIdentityChange() + } stopPendingWorkspaceReadinessWatcher() + resolvedUserId = user.id + setStorageIdentity(user.id) // Release the fence once initialization concludes either way: a resolved // workspace, or a permanent init failure. Waiting on 'ready' alone would @@ -167,7 +203,7 @@ export function useWorkflowPersistenceV2() { teamWorkspaceStore.activeWorkspaceId !== null) || teamWorkspaceStore.initState === 'error' if (isWorkspaceInitConcluded()) { - completeWorkflowLogoutTransition() + releaseIdentityFence() return } @@ -175,7 +211,7 @@ export function useWorkflowPersistenceV2() { isWorkspaceInitConcluded, () => { stopWorkspaceReadinessWatcher = undefined - completeWorkflowLogoutTransition() + releaseIdentityFence() }, { once: true } ) From 72300a26351ed771fd4622b6b68376dafcdb3b52 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 16:31:36 -0700 Subject: [PATCH 11/52] test: cover scoped workflow wipe on cloud logout --- src/composables/auth/useAuthActions.test.ts | 43 ++++++++++++++----- .../persistence/base/storageIO.test.ts | 4 +- .../useWorkflowPersistenceV2.test.ts | 4 +- 3 files changed, 34 insertions(+), 17 deletions(-) diff --git a/src/composables/auth/useAuthActions.test.ts b/src/composables/auth/useAuthActions.test.ts index 40be50ea6a3..34c610ddfad 100644 --- a/src/composables/auth/useAuthActions.test.ts +++ b/src/composables/auth/useAuthActions.test.ts @@ -41,7 +41,10 @@ const mockDistributionState = vi.hoisted(() => ({ isCloud: false })) const mockBillingState = vi.hoisted(() => ({ canAccessSubscriptionFeatures: false })) -const mockClearAllWorkflowStorage = vi.hoisted(() => vi.fn()) +const mockClearWorkflowStorageForScope = vi.hoisted(() => vi.fn()) +const mockGetStorageScope = vi.hoisted(() => + vi.fn<() => string | null>(() => 'user-a:ws-1') +) const mockPrepareWorkflowLogoutTransition = vi.hoisted(() => vi.fn()) const authErrorMessages: Record = enLocale.auth.errors @@ -88,7 +91,8 @@ vi.mock(import('@/composables/billing/usePendingTopup'), () => ({ })) vi.mock(import('@/platform/workflow/persistence/base/storageIO'), () => ({ - clearAllWorkflowStorage: mockClearAllWorkflowStorage, + clearWorkflowStorageForScope: mockClearWorkflowStorageForScope, + getStorageScope: mockGetStorageScope, prepareWorkflowLogoutTransition: mockPrepareWorkflowLogoutTransition })) @@ -214,7 +218,7 @@ describe('useAuthActions.logout', () => { expect(mockDialogService.confirm).not.toHaveBeenCalled() expect(mockWorkflowService.saveWorkflow).not.toHaveBeenCalled() expect(mockAuthStore.logout).toHaveBeenCalledTimes(1) - expect(mockClearAllWorkflowStorage).not.toHaveBeenCalled() + expect(mockClearWorkflowStorageForScope).not.toHaveBeenCalled() }) it('logs out without prompting when no workflows are modified', async () => { @@ -227,7 +231,7 @@ describe('useAuthActions.logout', () => { expect(mockAuthStore.logout).toHaveBeenCalledTimes(1) }) - it('clears persisted workflows after cloud logout and before navigation', async () => { + it('wipes only the departing identity scope after cloud logout and before navigation', async () => { const navigationSpy = vi .spyOn(window.location, 'href', 'set') .mockImplementation(() => {}) @@ -236,20 +240,37 @@ describe('useAuthActions.logout', () => { await logout() expect(mockPrepareWorkflowLogoutTransition).toHaveBeenCalledOnce() - expect(mockClearAllWorkflowStorage).toHaveBeenCalledExactlyOnceWith() - expect( - vi.mocked(mockAuthStore.logout).mock.invocationCallOrder[0] - ).toBeLessThan( + expect(mockClearWorkflowStorageForScope).toHaveBeenCalledExactlyOnceWith( + 'user-a:ws-1' + ) + const logoutCallOrder = vi.mocked(mockAuthStore.logout).mock + .invocationCallOrder[0] + expect(mockGetStorageScope.mock.invocationCallOrder[0]).toBeLessThan( + logoutCallOrder + ) + expect(logoutCallOrder).toBeLessThan( mockPrepareWorkflowLogoutTransition.mock.invocationCallOrder[0] ) expect( mockPrepareWorkflowLogoutTransition.mock.invocationCallOrder[0] - ).toBeLessThan(mockClearAllWorkflowStorage.mock.invocationCallOrder[0]) + ).toBeLessThan(mockClearWorkflowStorageForScope.mock.invocationCallOrder[0]) expect( - mockClearAllWorkflowStorage.mock.invocationCallOrder[0] + mockClearWorkflowStorageForScope.mock.invocationCallOrder[0] ).toBeLessThan(navigationSpy.mock.invocationCallOrder[0]) }) + it('does not wipe any scope when no identity scope was resolved', async () => { + mockGetStorageScope.mockReturnValueOnce(null) + vi.spyOn(window.location, 'href', 'set').mockImplementation(() => {}) + const { logout } = useAuthActions() + + await logout() + + expect(mockAuthStore.logout).toHaveBeenCalledTimes(1) + expect(mockPrepareWorkflowLogoutTransition).toHaveBeenCalledOnce() + expect(mockClearWorkflowStorageForScope).not.toHaveBeenCalled() + }) + it('does not clear cloud workflows when logout fails', async () => { vi.mocked(mockAuthStore.logout).mockRejectedValueOnce( new Error('network failed') @@ -259,7 +280,7 @@ describe('useAuthActions.logout', () => { await logout() expect(mockPrepareWorkflowLogoutTransition).not.toHaveBeenCalled() - expect(mockClearAllWorkflowStorage).not.toHaveBeenCalled() + expect(mockClearWorkflowStorageForScope).not.toHaveBeenCalled() }) it('cancels sign-out when the dialog is dismissed (null)', async () => { diff --git a/src/platform/workflow/persistence/base/storageIO.test.ts b/src/platform/workflow/persistence/base/storageIO.test.ts index 755f3614ac1..9f302ada9f8 100644 --- a/src/platform/workflow/persistence/base/storageIO.test.ts +++ b/src/platform/workflow/persistence/base/storageIO.test.ts @@ -432,9 +432,7 @@ describe('storageIO', () => { expect(isolatedStorageIO.getStorageScope()).toBe('user-a:ws-1') expect(isolatedStorageIO.getStorageWriteGate()).toBe('open') expect(isolatedStorageIO.isStorageAvailable()).toBe(true) - expect(isolatedStorageIO.writeIndex('user-a:ws-1', emptyIndex)).toBe( - true - ) + expect(isolatedStorageIO.writeIndex('user-a:ws-1', emptyIndex)).toBe(true) }) it('defers writes again once the identity is dropped', async () => { diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index bb6d62a5301..26fdaa1b274 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -1006,9 +1006,7 @@ describe('useWorkflowPersistenceV2', () => { JSON.stringify({ id: 'workspace-a', type: 'team' }) ) const workflowStore = useWorkflowStore() - const workflow = await workflowStore - .createTemporary('Deferred.json') - .load() + const workflow = await workflowStore.createTemporary('Deferred.json').load() workflowStore.activeWorkflow = workflow mountWorkflowPersistence() From 11ede87f62557dca61f40150c351dc6d9934b810 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 16:33:16 -0700 Subject: [PATCH 12/52] fix: wipe only the departing identity scope on cloud logout --- src/composables/auth/useAuthActions.ts | 6 ++++-- .../workflow/persistence/base/storageIO.ts | 14 -------------- 2 files changed, 4 insertions(+), 16 deletions(-) diff --git a/src/composables/auth/useAuthActions.ts b/src/composables/auth/useAuthActions.ts index 8a4ee4f5de5..44eeaff2e5e 100644 --- a/src/composables/auth/useAuthActions.ts +++ b/src/composables/auth/useAuthActions.ts @@ -20,7 +20,8 @@ import { useTelemetry } from '@/platform/telemetry' import type { AuthFlowAction } from '@/platform/telemetry/types' import { useToastStore } from '@/platform/updates/common/toastStore' import { - clearAllWorkflowStorage, + clearWorkflowStorageForScope, + getStorageScope, prepareWorkflowLogoutTransition } from '@/platform/workflow/persistence/base/storageIO' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' @@ -132,10 +133,11 @@ export const useAuthActions = () => { } } + const departingScope = isCloud ? getStorageScope() : null await authStore.logout() if (isCloud) { prepareWorkflowLogoutTransition() - clearAllWorkflowStorage() + if (departingScope !== null) clearWorkflowStorageForScope(departingScope) } toastStore.add({ diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index 6873cff288f..f34f0b8da52 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -579,17 +579,3 @@ export function clearWorkflowStorageForScope(scope: string): void { removeStorageKeys(localStorage, localKeys, localPrefixes) removeStorageKeys(sessionStorage, sessionRestoreKeys, sessionRestorePrefixes) } - -export function clearAllWorkflowStorage(): void { - const localPrefixes = [ - StorageKeys.prefixes.draftIndex, - StorageKeys.prefixes.draftPayload, - StorageKeys.prefixes.lastActivePath, - StorageKeys.prefixes.lastOpenPaths, - 'Comfy.Workflow.Drafts:', - 'Comfy.Workflow.DraftOrder:' - ] - - removeStorageKeys(localStorage, legacyLocalRestoreKeys, localPrefixes) - removeStorageKeys(sessionStorage, sessionRestoreKeys, sessionRestorePrefixes) -} From 494dd072233274089086160926e34b0c2140e206 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 16:43:56 -0700 Subject: [PATCH 13/52] docs: add ADR for identity-scoped workflow persistence --- docs/adr/README.md | 1 + ...ENCE-0031-identity-scoped-draft-storage.md | 185 ++++++++++++++++++ 2 files changed, 186 insertions(+) create mode 100644 docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md diff --git a/docs/adr/README.md b/docs/adr/README.md index 77a4a85bc11..b9beeaa20e5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -43,6 +43,7 @@ An Architecture Decision Record captures an important architectural decision mad | [TELEMETRY-STARTUP-0030](TELEMETRY-STARTUP-0030-production-startup-telemetry.md) | Production Startup Telemetry | Proposed | 2026-09-08 | | [TESTING-E2E-0027](TESTING-E2E-0027-coverage-measurement-and-test-selection.md) | E2E Coverage Measurement and Test Selection | Proposed | 2026-09-01 | | [WIDGET-SERIALIZATION-0006](WIDGET-SERIALIZATION-0006-preserve-primitive-widget-values-across-copy-and-paste.md) | PrimitiveNode Widget Restoration Lifecycle | Accepted | 2026-02-22 | +| [WORKFLOW-PERSISTENCE-0031](WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md) | Identity-Scoped Draft Storage | Proposed | 2026-09-09 | ## Creating a New ADR diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md new file mode 100644 index 00000000000..f951efd3d79 --- /dev/null +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -0,0 +1,185 @@ +# ADR-WORKFLOW-PERSISTENCE-0031: Identity-Scoped Draft Storage + +Date: 2026-09-09 + +## Status + +Proposed + +## Context + +Workflow drafts, the draft index, and tab restore pointers live in +`localStorage`, keyed by workspace id. The workspace id is read from +`sessionStorage` (`Comfy.Workspace.Current`), which is per tab. The signed-in +Firebase user is persisted in IndexedDB, which is per origin. The two storage +mediums have different lifetimes, so the keys under which drafts are written can +name a workspace that belongs to a different user than the one currently signed +in. + +A sequence of fixes narrowed the resulting data loss and cross-user leakage +without removing the cause: + +- https://github.com/Comfy-Org/ComfyUI_frontend/pull/8517, + https://github.com/Comfy-Org/ComfyUI_frontend/pull/8519 and + https://github.com/Comfy-Org/ComfyUI_frontend/pull/8520 introduced the + workspace-keyed V2 draft store and its V1 migration. +- https://github.com/Comfy-Org/ComfyUI_frontend/pull/14266 wiped all draft + storage on logout so the next user could not see the previous user's drafts. +- https://github.com/Comfy-Org/ComfyUI_frontend/pull/14290, + https://github.com/Comfy-Org/ComfyUI_frontend/pull/14306 and + https://github.com/Comfy-Org/ComfyUI_frontend/pull/14337 added a + transitioning state around logout and workspace switches so in-flight + debounced writes would not resurrect wiped data. + +The remaining gaps are listed in +https://github.com/christian-byrne/blocked-on-christian/issues/522#issuecomment-5609244580. +The ones this ADR addresses: + +- Auth-state transitions that are not a logout (expired session restored as a + different user, account switch in another tab, user resolved before the + workspace store is ready) do not enter the transitioning state, so a debounced + write can land under the previous identity's key. +- The logout wipe is unconditional. It destroys the drafts of the departing + user in every workspace they had opened in that browser, including drafts + that were never touched during the session. +- Two users sharing a workspace id (a personal workspace named `personal`, or a + team workspace both belong to) share one set of keys, so one user's drafts + are readable by the other after login. + +The behaviour these keys need is the same as a database row scoped by tenant: +each row has exactly one owner, writes are rejected while the owner is unknown, +and a change of owner is fenced so no write from the old owner's transaction can +commit after the new owner has started. `docs/guidance/state-and-effects.md` +adds a second constraint: the logout sequence is a command with an explicit +order of effects, not a chain of watchers reacting to each other. + +## Decision + +### Keys are scoped by resolved identity + +`resolveStorageScope(userId, workspaceId)` in +`src/platform/workflow/persistence/base/storageKeys.ts` is the single source of +the storage scope. Non-cloud builds resolve to `personal`. Cloud builds resolve +to `${userId}:${workspaceId}` when a user is known and `null` otherwise. Draft +payloads, the draft index and the tab restore pointers (`lastActivePath`, +`lastOpenPaths`) are all keyed by the resolved scope, never by the bare +workspace id. + +`storageIO.ts` holds the identity (`setStorageIdentity`) and exposes +`getStorageScope()`; nothing outside the persistence module computes a key. + +### Writes pass a tri-state gate + +`getStorageWriteGate()` returns `open`, `deferred` or `closed`: + +- `closed` when `localStorage` is unavailable. Writes are dropped, as before. +- `deferred` when the store is transitioning or the scope is `null`. The + persistence composable skips the write and keeps the in-memory workflow as + the authority. The next change after the gate opens persists the full state. +- `open` otherwise. + +A `null` scope is the "owner unknown" case. Refusing writes there is what stops +a debounced save from landing under a key that later turns out to belong to a +different user. + +### Identity swaps are fenced + +`useWorkflowPersistenceV2.ts` tracks the last resolved user id. When +`onUserResolved` fires with a different id, or `onUserLogout` fires, it calls +`fenceIdentityChange()`: cancel the debounced save, enter the transitioning +state, and drop the `lastSavedJsonByPath` cache so the first write under the +new scope is not suppressed by a hash computed under the old one. The fence is +released only once the workspace store has concluded initialisation (`ready` +with an active workspace, or `error`), because the scope is not resolvable +before that. + +### Logout wipes one scope, from the command + +`useAuthActions.logout` captures `getStorageScope()` before calling +`authStore.logout()`, then, after `prepareWorkflowLogoutTransition()`, calls +`clearWorkflowStorageForScope(departingScope)`. `onUserLogout` in the +persistence composable no longer wipes anything; it only fences and clears the +identity. `clearAllWorkflowStorage` is removed. + +The wipe lives in the command because the command is the only place that knows +the departing scope before the auth store forgets it. A watcher on the user +becoming `null` cannot know which scope to clear. + +### Legacy data is migrated once per scope + +`migrateWorkspaceToScope(workspaceId, scope)` copies the workspace-keyed index, +payloads and restore pointers to the scoped keys the first time a scope is +resolved that has no index. The destination index is written last so a partial +copy is never observed as complete; on failure the copied payloads are removed. +The source keys are removed after a successful copy. + +The first user to sign in on a browser therefore claims any pre-existing +workspace-keyed drafts. This is accepted: before this change those drafts were +already readable by whoever signed in, and the alternative of discarding them +is a data loss for the common single-user case. + +## Deferred decisions + +- `resetForIdentityChange()` in `teamWorkspaceStore.ts` is called from the auth + store's `onAuthStateChanged` and clears workspace state before the persistence + fence observes the new user. The ordering is currently benign because the + fence blocks writes until the store is `ready` again, but it is an implicit + dependency between two effects and should become an explicit sequence. +- `prepareWorkflowLogoutTransition()` overwrites a `workspace` transition reason + with `logout`. The two reasons are not yet distinguished by any reader, so the + overwrite has no observable effect; a reducer over + `WorkflowStorageState` would make the precedence explicit. +- Modelling the write gate, transition and identity as one reducer with named + events, plus write leases so a debounced save carries the scope it was + scheduled under, is the shape `state-and-effects.md` prescribes. The current + change keeps the existing module-level state and adds the minimum needed to + close the data-loss gaps. +- `useNewUserService.ts` reads the literal key `DraftIndex.v2:personal`. It is + correct for non-cloud builds and is not part of the cloud identity problem. + +## Alternatives considered + +- **Wipe on every auth-state change, not only logout.** Closes the leak but + turns a session refresh into data loss, and still depends on the wipe racing + ahead of the next debounced write. +- **Keep workspace-keyed storage and store the owner uid alongside each + entry.** Requires every reader to filter by owner and every writer to stamp + it; a scoped key does both by construction. +- **Store drafts in IndexedDB alongside the Firebase user so the mediums + match.** Correct in principle, but a storage-engine migration for all draft + data, and it does not by itself gate writes during identity transitions. +- **Reducer and leases now.** Rejected for this change to keep the PR under the + 300-line non-test budget and reviewable; recorded above as deferred. + +## Consequences + +### Positive + +- Two users on one browser never read or overwrite each other's drafts, even + when they share a workspace id. +- Logout removes only the departing user's data in the scope they were in; + drafts in their other workspaces survive. +- No write can commit while the owner is unknown or changing. + +### Negative + +- Existing workspace-keyed drafts are attributed to the first user who signs in + after the upgrade. +- Writes made while the gate is `deferred` are not queued; if the tab closes + before the gate opens, changes made during the transition are lost. This is + the same window that already existed for the transitioning state. +- One more key segment in `localStorage`; total storage use is unchanged after + migration because source keys are removed. + +## Notes + +Storage layout after this change, cloud build: + +```text +Comfy.Workflow.DraftIndex.v2:: +Comfy.Workflow.Draft.v2::: +Comfy.Workflow.LastActivePath:: +Comfy.Workflow.LastOpenPaths:: +``` + +Non-cloud builds keep `personal` as the scope, so their keys are unchanged. From 4d245ccb7dc3d80a35e83598b59c2c34f522ec76 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 17:01:31 -0700 Subject: [PATCH 14/52] test: defer draft writes while the cloud workspace is unresolved --- .../persistence/base/storageIO.test.ts | 13 ++++++++ .../persistence/base/storageKeys.test.ts | 33 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/platform/workflow/persistence/base/storageIO.test.ts b/src/platform/workflow/persistence/base/storageIO.test.ts index 9f302ada9f8..6e3955abcaa 100644 --- a/src/platform/workflow/persistence/base/storageIO.test.ts +++ b/src/platform/workflow/persistence/base/storageIO.test.ts @@ -435,6 +435,19 @@ describe('storageIO', () => { expect(isolatedStorageIO.writeIndex('user-a:ws-1', emptyIndex)).toBe(true) }) + it('defers writes while the cloud workspace is unresolved', async () => { + const isolatedStorageIO = await import('./storageIO') + isolatedStorageIO.setStorageIdentity('user-a') + + sessionStorage.clear() + + expect(isolatedStorageIO.getStorageScope()).toBeNull() + expect(isolatedStorageIO.getStorageWriteGate()).toBe('deferred') + expect(isolatedStorageIO.writeIndex('user-a:ws-1', emptyIndex)).toBe( + false + ) + }) + it('defers writes again once the identity is dropped', async () => { const isolatedStorageIO = await import('./storageIO') isolatedStorageIO.setStorageIdentity('user-a') diff --git a/src/platform/workflow/persistence/base/storageKeys.test.ts b/src/platform/workflow/persistence/base/storageKeys.test.ts index 5e99dd0543e..72545ddbdf4 100644 --- a/src/platform/workflow/persistence/base/storageKeys.test.ts +++ b/src/platform/workflow/persistence/base/storageKeys.test.ts @@ -85,6 +85,34 @@ describe('storageKeys', () => { }) }) + describe('readWorkspaceId', () => { + it('returns null in cloud until a workspace is stored', async () => { + const { readWorkspaceId } = await import('./storageKeys') + expect(readWorkspaceId()).toBeNull() + }) + + it('returns null in cloud when the stored workspace is unreadable', async () => { + sessionStorage.setItem('Comfy.Workspace.Current', 'invalid-json') + const { readWorkspaceId } = await import('./storageKeys') + expect(readWorkspaceId()).toBeNull() + }) + + it('returns personal for the personal workspace type', async () => { + sessionStorage.setItem( + 'Comfy.Workspace.Current', + JSON.stringify({ type: 'personal', id: null }) + ) + const { readWorkspaceId } = await import('./storageKeys') + expect(readWorkspaceId()).toBe('personal') + }) + + it('returns personal outside cloud without reading sessionStorage', async () => { + mockDistributionTypes.isCloud = false + const { readWorkspaceId } = await import('./storageKeys') + expect(readWorkspaceId()).toBe('personal') + }) + }) + describe('resolveStorageScope', () => { it('combines user and workspace in cloud', async () => { const { resolveStorageScope } = await import('./storageKeys') @@ -96,6 +124,11 @@ describe('storageKeys', () => { expect(resolveStorageScope(null, 'ws-1')).toBeNull() }) + it('returns null in cloud until the workspace is resolved', async () => { + const { resolveStorageScope } = await import('./storageKeys') + expect(resolveStorageScope('user-a', null)).toBeNull() + }) + it('ignores identity outside cloud', async () => { mockDistributionTypes.isCloud = false const { resolveStorageScope } = await import('./storageKeys') From ab9386d0f1d6eab1cac4c6a931285ebc9f70faf3 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 17:04:32 -0700 Subject: [PATCH 15/52] fix: defer draft writes until the cloud workspace is resolved --- .../workflow/persistence/base/storageIO.ts | 8 +++-- .../workflow/persistence/base/storageKeys.ts | 30 ++++++++++++------- .../useWorkflowPersistenceV2.test.ts | 4 +++ .../composables/useWorkflowTabState.test.ts | 2 ++ .../stores/workflowDraftStoreV2.scope.test.ts | 11 +++++++ 5 files changed, 43 insertions(+), 12 deletions(-) diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index f34f0b8da52..0fd87da1f1d 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -10,7 +10,11 @@ import type { DraftPayloadV2, OpenPathsPointer } from './draftTypes' -import { StorageKeys, getWorkspaceId, resolveStorageScope } from './storageKeys' +import { + StorageKeys, + readWorkspaceId, + resolveStorageScope +} from './storageKeys' type StorageAvailability = 'available' | 'unavailable' type StorageWriteGate = 'open' | 'deferred' | 'closed' @@ -40,7 +44,7 @@ export function setStorageIdentity(userId: string | null): void { } export function getStorageScope(): string | null { - return resolveStorageScope(storageIdentity, getWorkspaceId()) + return resolveStorageScope(storageIdentity, readWorkspaceId()) } export function getStorageWriteGate(): StorageWriteGate { diff --git a/src/platform/workflow/persistence/base/storageKeys.ts b/src/platform/workflow/persistence/base/storageKeys.ts index c5b7e01fb4f..94d9a3f65ba 100644 --- a/src/platform/workflow/persistence/base/storageKeys.ts +++ b/src/platform/workflow/persistence/base/storageKeys.ts @@ -4,41 +4,51 @@ import { isCloud } from '@/platform/distribution/types' import { hashPath } from './hashUtil' /** - * Gets the current workspace ID from sessionStorage. - * Returns 'personal' for personal workspace or when no workspace is set. + * Reads the current workspace ID from sessionStorage. + * Returns 'personal' outside cloud or for the personal workspace, and null + * while the cloud workspace is unresolved. * * NOTE: This is called fresh each time rather than cached at module load, * because the workspace auth store may not have set sessionStorage yet * when this module is first imported. */ -export function getWorkspaceId(): string { +export function readWorkspaceId(): string | null { if (!isCloud) return 'personal' try { const json = sessionStorage.getItem( WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE ) - if (!json) return 'personal' + if (!json) return null const workspace = JSON.parse(json) - if (workspace.type === 'personal' || !workspace.id) return 'personal' - return workspace.id + if (workspace.type === 'personal') return 'personal' + return typeof workspace.id === 'string' && workspace.id + ? workspace.id + : null } catch { - return 'personal' + return null } } +/** + * Gets the current workspace ID, falling back to 'personal' when unresolved. + */ +export function getWorkspaceId(): string { + return readWorkspaceId() ?? 'personal' +} + /** * Resolves the localStorage scope for workflow drafts. * Cloud drafts belong to one user in one workspace, so the scope is - * `${userId}:${workspaceId}` and unresolvable until the user is known. + * `${userId}:${workspaceId}` and unresolvable until both are known. */ export function resolveStorageScope( userId: string | null, - workspaceId: string + workspaceId: string | null ): string | null { if (!isCloud) return 'personal' - return userId ? `${userId}:${workspaceId}` : null + return userId && workspaceId ? `${userId}:${workspaceId}` : null } /** diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index 26fdaa1b274..b65727082dc 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -807,6 +807,10 @@ describe('useWorkflowPersistenceV2', () => { it('resumes workflow writes once workspace readiness is confirmed after authentication recovers', async () => { distributionMocks.isCloud = true + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: 'workspace-a', type: 'team' }) + ) localStorage.setItem('Comfy.Workflow.DraftIndex.v2:workspace-a', '{}') sessionStorage.setItem('Comfy.Workflow.ActivePath:test-client', '{}') mountWorkflowPersistence() diff --git a/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts b/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts index 4b13b75d1b4..b09e5d3348b 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts @@ -37,6 +37,7 @@ describe('useWorkflowTabState', () => { }) it('saves and retrieves active path', async () => { + setCurrentWorkspace('ws-1') const { getActivePath, setActivePath } = await loadTabState('user-a') setActivePath('workflows/test.json') @@ -84,6 +85,7 @@ describe('useWorkflowTabState', () => { }) it('saves and retrieves open paths', async () => { + setCurrentWorkspace('ws-1') const { getOpenPaths, setOpenPaths } = await loadTabState('user-a') const paths = ['workflows/a.json', 'workflows/b.json'] diff --git a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts index 635d2674dfd..d0b247aafd9 100644 --- a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts +++ b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts @@ -1,6 +1,8 @@ import { createPinia, setActivePinia } from 'pinia' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' + import { hashPath } from '../base/hashUtil' import { readIndex, setStorageIdentity } from '../base/storageIO' import { StorageKeys } from '../base/storageKeys' @@ -19,6 +21,13 @@ vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) const PATH = 'workflows/test.json' const META = { name: 'test', isTemporary: false } +function setPersonalWorkspace() { + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ type: 'personal' }) + ) +} + describe('workflowDraftStoreV2 storage scope', () => { beforeEach(() => { localStorage.clear() @@ -49,6 +58,7 @@ describe('workflowDraftStoreV2 storage scope', () => { }) it('keys drafts by the resolved user scope, not the bare workspace', () => { + setPersonalWorkspace() setStorageIdentity('user-a') const store = useWorkflowDraftStoreV2() @@ -62,6 +72,7 @@ describe('workflowDraftStoreV2 storage scope', () => { }) it('serves each user their own drafts after identity changes', () => { + setPersonalWorkspace() setStorageIdentity('user-a') const store = useWorkflowDraftStoreV2() store.saveDraft(PATH, '{"owner":"a"}', META) From 6a674220de694a6f04b333b3e0741eee19a6540d Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 17:06:32 -0700 Subject: [PATCH 16/52] test: fence draft writes on the initial identity resolution --- .../useWorkflowPersistenceV2.test.ts | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index b65727082dc..1a9c2abe1b9 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -1003,6 +1003,43 @@ describe('useWorkflowPersistenceV2', () => { expect(JSON.parse(userBPayload.data)).toEqual({ marker: 'user-b-edit' }) }) + it('fences writes on the initial identity resolution until the workspace store confirms the workspace', async () => { + distributionMocks.isCloud = true + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: 'workspace-a', type: 'team' }) + ) + const workflowStore = useWorkflowStore() + const workflow = await workflowStore + .createTemporary('InitialResolve.json') + .load() + workflowStore.activeWorkflow = workflow + mountWorkflowPersistence() + const payloadKey = StorageKeys.draftPayload( + workflow.path, + 'user-a:workspace-a' + ) + + currentUserMocks.onUserResolved.mock.calls[0][0]({ id: 'user-a' }) + mocks.state.currentGraph = { marker: 'before-workspace-ready' } + mocks.state.graphChangedHandler?.() + await vi.runAllTimersAsync() + + expect(localStorage.getItem(payloadKey)).toBeNull() + expect(mockToastAdd).not.toHaveBeenCalled() + + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-a' }) + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + await nextTick() + mocks.state.currentGraph = { marker: 'after-workspace-ready' } + mocks.state.graphChangedHandler?.() + await vi.runAllTimersAsync() + + expect( + JSON.parse(JSON.parse(localStorage.getItem(payloadKey)!).data) + ).toEqual({ marker: 'after-workspace-ready' }) + }) + it('stays silent while the write gate is deferred on an unresolved identity', async () => { distributionMocks.isCloud = true sessionStorage.setItem( From 979c3d49b54a368949abbae7d6ede455cdfd8cbb Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 17:06:49 -0700 Subject: [PATCH 17/52] fix: fence draft writes on the initial identity resolution --- .../persistence/composables/useWorkflowPersistenceV2.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts index 2a3ec93d0cf..1616c1d38a2 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts @@ -187,9 +187,7 @@ export function useWorkflowPersistenceV2() { }) onUserResolved((user) => { if (!isCloud) return - if (resolvedUserId !== null && resolvedUserId !== user.id) { - fenceIdentityChange() - } + if (resolvedUserId !== user.id) fenceIdentityChange() stopPendingWorkspaceReadinessWatcher() resolvedUserId = user.id setStorageIdentity(user.id) From c5f474e5b154d21d3f57daa1ec468bb1a7f98867 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 17:08:34 -0700 Subject: [PATCH 18/52] test: roll back and converge the workspace-to-scope migration --- .../migration/migrateWorkspaceToScope.test.ts | 80 ++++++++++++++++++- 1 file changed, 77 insertions(+), 3 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index d1d5787553f..59db05a390c 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -96,7 +96,7 @@ describe('migrateWorkspaceToScope', () => { ).toBe(null) }) - it('leaves an already scoped destination untouched', () => { + it('finishes the source cleanup when the destination is already committed', () => { seedSourceWorkspace() const destinationIndex: DraftIndexV2 = { v: 2, @@ -119,9 +119,48 @@ describe('migrateWorkspaceToScope', () => { StorageKeys.draftPayload(draftPath, destinationScope) ) ).toBe(null) - expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( - buildIndex() + expect( + localStorage.getItem(StorageKeys.draftIndex(sourceWorkspaceId)) + ).toBe(null) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, sourceWorkspaceId) + ) + ).toBe(null) + expect( + localStorage.getItem(StorageKeys.lastActivePath(sourceWorkspaceId)) + ).toBe(null) + expect( + localStorage.getItem(StorageKeys.lastOpenPaths(sourceWorkspaceId)) + ).toBe(null) + }) + + it('leaves a committed destination alone when there is no source to clean up', () => { + const destinationIndex: DraftIndexV2 = { + v: 2, + updatedAt: 99, + order: [], + entries: {} + } + localStorage.setItem( + StorageKeys.draftIndex(destinationScope), + JSON.stringify(destinationIndex) + ) + localStorage.setItem( + StorageKeys.draftPayload(draftPath, sourceWorkspaceId), + JSON.stringify({ data: '{}', updatedAt: 1 }) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + destinationIndex ) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, sourceWorkspaceId) + ) + ).not.toBe(null) }) it('does nothing when the workspace has no draft index', () => { @@ -178,4 +217,39 @@ describe('migrateWorkspaceToScope', () => { null ) }) + + it('removes every copied destination artifact when a restore pointer copy hits the quota', () => { + seedSourceWorkspace() + const failingKey = StorageKeys.lastOpenPaths(destinationScope) + const realSetItem = localStorage.setItem.bind(localStorage) + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + if (key === failingKey) { + throw new DOMException('Quota exceeded', 'QuotaExceededError') + } + realSetItem(key, value) + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(localStorage.getItem(StorageKeys.draftIndex(destinationScope))).toBe( + null + ) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, destinationScope) + ) + ).toBe(null) + expect( + localStorage.getItem(StorageKeys.lastActivePath(destinationScope)) + ).toBe(null) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect(readJson(StorageKeys.lastActivePath(sourceWorkspaceId))).toEqual({ + workspaceId: sourceWorkspaceId, + path: draftPath + }) + }) }) From 2008ff353b01ec2bb04bca2d24b7fbfa1ee42e7a Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 17:10:08 -0700 Subject: [PATCH 19/52] fix: roll back and converge the workspace-to-scope migration --- .../migration/migrateWorkspaceToScope.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index 3a1657e99a7..d31bd4f00bf 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -25,11 +25,15 @@ export function migrateWorkspaceToScope( workspaceId: string, scope: string ): void { - if (readIndex(scope) !== null) return const index = readIndex(workspaceId) if (index === null) return const draftKeys = getPayloadKeys(workspaceId) + if (readIndex(scope) !== null) { + removeScopeArtifacts(workspaceId, draftKeys) + return + } + const copied = draftKeys.every((draftKey) => copyPayload(workspaceId, scope, draftKey)) && restorePointerKeys.every((keyFor) => @@ -37,15 +41,14 @@ export function migrateWorkspaceToScope( ) && writeIndex(scope, index) - if (!copied) { - deletePayloads(scope, draftKeys) - return - } + removeScopeArtifacts(copied ? workspaceId : scope, draftKeys) +} - deletePayloads(workspaceId, draftKeys) - localStorage.removeItem(StorageKeys.draftIndex(workspaceId)) +function removeScopeArtifacts(scope: string, draftKeys: string[]): void { + deletePayloads(scope, draftKeys) + localStorage.removeItem(StorageKeys.draftIndex(scope)) for (const keyFor of restorePointerKeys) { - localStorage.removeItem(keyFor(workspaceId)) + localStorage.removeItem(keyFor(scope)) } } From e8ce7edbfde04fd74fdf506cdf531f08dd5a2edc Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 17:11:28 -0700 Subject: [PATCH 20/52] docs: record migration rollback and multi-tab deferrals in ADR 0031 --- ...ENCE-0031-identity-scoped-draft-storage.md | 36 +++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md index f951efd3d79..a8cda15a0e5 100644 --- a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -60,7 +60,9 @@ order of effects, not a chain of watchers reacting to each other. `resolveStorageScope(userId, workspaceId)` in `src/platform/workflow/persistence/base/storageKeys.ts` is the single source of the storage scope. Non-cloud builds resolve to `personal`. Cloud builds resolve -to `${userId}:${workspaceId}` when a user is known and `null` otherwise. Draft +to `${userId}:${workspaceId}` when both a user and a workspace are known and +`null` otherwise; a missing `Comfy.Workspace.Current` entry is not defaulted to +`personal`, because a cloud tab with no workspace has no owner yet. Draft payloads, the draft index and the tab restore pointers (`lastActivePath`, `lastOpenPaths`) are all keyed by the resolved scope, never by the bare workspace id. @@ -85,13 +87,17 @@ different user. ### Identity swaps are fenced `useWorkflowPersistenceV2.ts` tracks the last resolved user id. When -`onUserResolved` fires with a different id, or `onUserLogout` fires, it calls +`onUserResolved` fires with an id other than the tracked one (including the +first resolution from no user), or `onUserLogout` fires, it calls `fenceIdentityChange()`: cancel the debounced save, enter the transitioning state, and drop the `lastSavedJsonByPath` cache so the first write under the -new scope is not suppressed by a hash computed under the old one. The fence is +new scope is not suppressed by a hash computed under the old one. A repeat +resolution of the same user (token refresh) does not fence. The fence is released only once the workspace store has concluded initialisation (`ready` with an active workspace, or `error`), because the scope is not resolvable -before that. +before that. Until the next `onUserResolved`, a logout fence stays in place; +a tab that observes another tab's logout therefore stays read-only rather than +writing under an identity that no longer exists. ### Logout wipes one scope, from the command @@ -110,8 +116,14 @@ becoming `null` cannot know which scope to clear. `migrateWorkspaceToScope(workspaceId, scope)` copies the workspace-keyed index, payloads and restore pointers to the scoped keys the first time a scope is resolved that has no index. The destination index is written last so a partial -copy is never observed as complete; on failure the copied payloads are removed. -The source keys are removed after a successful copy. +copy is never observed as complete. On failure every destination artifact the +copy produced (payloads, restore pointers, index) is removed and the source is +left intact, so a retry starts from the same state. On success the source +payloads, index and restore pointers are removed. If the source index still +exists but the destination index is already present, an earlier run committed +and was interrupted before its source cleanup; the migration only finishes that +cleanup and does not copy again, so the committed destination is never +overwritten by stale source data. The first user to sign in on a browser therefore claims any pre-existing workspace-keyed drafts. This is accepted: before this change those drafts were @@ -136,6 +148,18 @@ is a data loss for the common single-user case. close the data-loss gaps. - `useNewUserService.ts` reads the literal key `DraftIndex.v2:personal`. It is correct for non-cloud builds and is not part of the cloud identity problem. +- Two tabs of the same user in the same workspace share one scope. Logging out + in one tab wipes that scope, so unsaved drafts in the other tab are removed + while it is still open; that tab is fenced and cannot write them back. This + is the pre-existing multi-tab behaviour of the logout wipe, now narrowed to + one scope. A per-tab claim on the scope (a lease keyed by tab id, released on + `pagehide`) would let the wipe skip scopes another live tab still holds; it + needs a cross-tab protocol and belongs with the reducer work above. Owner: + the workflow persistence maintainers. +- A tab fenced by another tab's logout stays fenced until its own auth state + resolves a user again. It does not re-open on its own because it cannot + know whether the departing scope is still valid. Surfacing this to the user + (read-only indicator, prompt to sign in) is UI work outside this ADR. ## Alternatives considered From 239ae910d1d6ba3eebc3554deb9ffcb687c7d2ad Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 18:17:37 -0700 Subject: [PATCH 21/52] test: cover review findings for scoped draft migration and deferred writes --- .../persistence/base/storageKeys.test.ts | 139 +++++++----------- .../useWorkflowPersistenceV2.test.ts | 98 ++++++++++-- .../composables/useWorkflowTabState.test.ts | 11 ++ .../migration/migrateWorkspaceToScope.test.ts | 81 +++++++++- .../stores/workflowDraftStoreV2.scope.test.ts | 5 +- 5 files changed, 236 insertions(+), 98 deletions(-) diff --git a/src/platform/workflow/persistence/base/storageKeys.test.ts b/src/platform/workflow/persistence/base/storageKeys.test.ts index 72545ddbdf4..167606ae532 100644 --- a/src/platform/workflow/persistence/base/storageKeys.test.ts +++ b/src/platform/workflow/persistence/base/storageKeys.test.ts @@ -4,157 +4,136 @@ const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true })) vi.mock(import('@/platform/distribution/types'), () => mockDistributionTypes) +const { getWorkspaceId, readWorkspaceId, resolveStorageScope, StorageKeys } = + await import('./storageKeys') + +function setCurrentWorkspace(workspace: unknown) { + sessionStorage.setItem( + 'Comfy.Workspace.Current', + typeof workspace === 'string' ? workspace : JSON.stringify(workspace) + ) +} + describe('storageKeys', () => { beforeEach(() => { + sessionStorage.clear() mockDistributionTypes.isCloud = true - vi.resetModules() }) describe('getWorkspaceId', () => { - it('returns personal when no workspace is set', async () => { - const { getWorkspaceId } = await import('./storageKeys') + it('returns personal when no workspace is set', () => { expect(getWorkspaceId()).toBe('personal') }) - it('returns personal for personal workspace type', async () => { - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'personal', id: null }) - ) - const { getWorkspaceId } = await import('./storageKeys') + it('returns personal for personal workspace type', () => { + setCurrentWorkspace({ type: 'personal', id: null }) expect(getWorkspaceId()).toBe('personal') }) - it('returns workspace ID for team workspace', async () => { - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-abc-123' }) - ) - const { getWorkspaceId } = await import('./storageKeys') + it('returns workspace ID for team workspace', () => { + setCurrentWorkspace({ type: 'team', id: 'ws-abc-123' }) expect(getWorkspaceId()).toBe('ws-abc-123') }) - it('keeps local workflow storage in the personal namespace', async () => { + it('keeps local workflow storage in the personal namespace', () => { mockDistributionTypes.isCloud = false - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-abc-123' }) - ) - const { getWorkspaceId } = await import('./storageKeys') + setCurrentWorkspace({ type: 'team', id: 'ws-abc-123' }) expect(getWorkspaceId()).toBe('personal') }) - it('returns personal when JSON parsing fails', async () => { - sessionStorage.setItem('Comfy.Workspace.Current', 'invalid-json') - const { getWorkspaceId } = await import('./storageKeys') + it('returns personal when JSON parsing fails', () => { + setCurrentWorkspace('invalid-json') expect(getWorkspaceId()).toBe('personal') }) - it('returns personal when workspace has no id', async () => { - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: '' }) - ) - const { getWorkspaceId } = await import('./storageKeys') + it('returns personal when workspace has no id', () => { + setCurrentWorkspace({ type: 'team', id: '' }) expect(getWorkspaceId()).toBe('personal') }) - it('reads fresh value on each call (not cached)', async () => { - const { getWorkspaceId } = await import('./storageKeys') - - // Initially no workspace set + it('reads fresh value on each call (not cached)', () => { expect(getWorkspaceId()).toBe('personal') - // Set workspace after import - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-new' }) - ) - - // Should read the new value (not cached 'personal') + setCurrentWorkspace({ type: 'team', id: 'ws-new' }) expect(getWorkspaceId()).toBe('ws-new') - // Change workspace again - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'team', id: 'ws-another' }) - ) - + setCurrentWorkspace({ type: 'team', id: 'ws-another' }) expect(getWorkspaceId()).toBe('ws-another') }) }) describe('readWorkspaceId', () => { - it('returns null in cloud until a workspace is stored', async () => { - const { readWorkspaceId } = await import('./storageKeys') + it('returns null in cloud until a workspace is stored', () => { expect(readWorkspaceId()).toBeNull() }) - it('returns null in cloud when the stored workspace is unreadable', async () => { - sessionStorage.setItem('Comfy.Workspace.Current', 'invalid-json') - const { readWorkspaceId } = await import('./storageKeys') + it('returns null in cloud when the stored workspace is unreadable', () => { + setCurrentWorkspace('invalid-json') expect(readWorkspaceId()).toBeNull() }) - it('returns personal for the personal workspace type', async () => { - sessionStorage.setItem( - 'Comfy.Workspace.Current', - JSON.stringify({ type: 'personal', id: null }) - ) - const { readWorkspaceId } = await import('./storageKeys') + it('returns the team workspace id in cloud', () => { + setCurrentWorkspace({ type: 'team', id: 'workspace-a' }) + expect(readWorkspaceId()).toBe('workspace-a') + }) + + it('returns null in cloud when the stored workspace has no type or id', () => { + setCurrentWorkspace({}) + expect(readWorkspaceId()).toBeNull() + }) + + it('returns null in cloud when the team workspace id is empty', () => { + setCurrentWorkspace({ type: 'team', id: '' }) + expect(readWorkspaceId()).toBeNull() + }) + + it('returns personal for the personal workspace type', () => { + setCurrentWorkspace({ type: 'personal', id: null }) expect(readWorkspaceId()).toBe('personal') }) - it('returns personal outside cloud without reading sessionStorage', async () => { + it('returns personal outside cloud without reading sessionStorage', () => { mockDistributionTypes.isCloud = false - const { readWorkspaceId } = await import('./storageKeys') + setCurrentWorkspace({ type: 'team', id: 'workspace-a' }) expect(readWorkspaceId()).toBe('personal') }) }) describe('resolveStorageScope', () => { - it('combines user and workspace in cloud', async () => { - const { resolveStorageScope } = await import('./storageKeys') + it('combines user and workspace in cloud', () => { expect(resolveStorageScope('user-a', 'ws-1')).toBe('user-a:ws-1') }) - it('returns null in cloud until the user is resolved', async () => { - const { resolveStorageScope } = await import('./storageKeys') + it('returns null in cloud until the user is resolved', () => { expect(resolveStorageScope(null, 'ws-1')).toBeNull() }) - it('returns null in cloud until the workspace is resolved', async () => { - const { resolveStorageScope } = await import('./storageKeys') + it('returns null in cloud until the workspace is resolved', () => { expect(resolveStorageScope('user-a', null)).toBeNull() }) - it('ignores identity outside cloud', async () => { + it('ignores identity outside cloud', () => { mockDistributionTypes.isCloud = false - const { resolveStorageScope } = await import('./storageKeys') expect(resolveStorageScope(null, 'ws-1')).toBe('personal') expect(resolveStorageScope('user-a', 'ws-1')).toBe('personal') }) }) describe('StorageKeys', () => { - it('generates draftIndex key with workspace scope', async () => { - const { StorageKeys } = await import('./storageKeys') - + it('generates draftIndex key with workspace scope', () => { expect(StorageKeys.draftIndex('ws-123')).toBe( 'Comfy.Workflow.DraftIndex.v2:ws-123' ) }) - it('generates draftPayload key with hash', async () => { - const { StorageKeys } = await import('./storageKeys') + it('generates draftPayload key with hash', () => { const key = StorageKeys.draftPayload('workflows/test.json', 'ws-1') expect(key).toMatch(/^Comfy\.Workflow\.Draft\.v2:ws-1:[0-9a-f]{8}$/) }) - it('generates consistent draftKey from path', async () => { - const { StorageKeys } = await import('./storageKeys') + it('generates consistent draftKey from path', () => { const key1 = StorageKeys.draftKey('workflows/test.json') const key2 = StorageKeys.draftKey('workflows/test.json') @@ -162,23 +141,19 @@ describe('storageKeys', () => { expect(key1).toMatch(/^[0-9a-f]{8}$/) }) - it('generates activePath key with clientId', async () => { - const { StorageKeys } = await import('./storageKeys') + it('generates activePath key with clientId', () => { expect(StorageKeys.activePath('client-abc')).toBe( 'Comfy.Workflow.ActivePath:client-abc' ) }) - it('generates openPaths key with clientId', async () => { - const { StorageKeys } = await import('./storageKeys') + it('generates openPaths key with clientId', () => { expect(StorageKeys.openPaths('client-abc')).toBe( 'Comfy.Workflow.OpenPaths:client-abc' ) }) - it('exposes prefix patterns for cleanup', async () => { - const { StorageKeys } = await import('./storageKeys') - + it('exposes prefix patterns for cleanup', () => { expect(StorageKeys.prefixes.draftIndex).toBe( 'Comfy.Workflow.DraftIndex.v2:' ) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index 1a9c2abe1b9..9bb2ad2851c 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -7,6 +7,7 @@ import { createI18n } from 'vue-i18n' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' +import { hashPath } from '../base/hashUtil' import { StorageKeys } from '../base/storageKeys' import * as storageIO from '../base/storageIO' import { useWorkflowDraftStoreV2 } from '../stores/workflowDraftStoreV2' @@ -1076,19 +1077,7 @@ describe('useWorkflowPersistenceV2', () => { ) localStorage.setItem( workspaceIndexKey, - JSON.stringify({ - v: 2, - updatedAt: 1, - order: ['Legacy.json'], - entries: { - 'Legacy.json': { - path: 'Legacy.json', - name: 'Legacy', - isTemporary: true, - updatedAt: 1 - } - } - }) + JSON.stringify(legacyIndex('Legacy.json')) ) localStorage.setItem( workspacePayloadKey, @@ -1113,5 +1102,88 @@ describe('useWorkflowPersistenceV2', () => { )! ).data ).toBe('{"marker":"legacy"}') + expect(useWorkflowDraftStoreV2().getDraft('Legacy.json')?.data).toBe( + '{"marker":"legacy"}' + ) + }) + + it('removes stale workspace drafts even when the user scope already has an index', async () => { + distributionMocks.isCloud = true + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: 'workspace-a', type: 'team' }) + ) + const workspaceIndexKey = StorageKeys.draftIndex('workspace-a') + const workspacePayloadKey = StorageKeys.draftPayload( + 'Legacy.json', + 'workspace-a' + ) + const scopedIndexKey = StorageKeys.draftIndex('user-a:workspace-a') + const scopedIndex = JSON.stringify(legacyIndex('Scoped.json')) + localStorage.setItem( + workspaceIndexKey, + JSON.stringify(legacyIndex('Legacy.json')) + ) + localStorage.setItem( + workspacePayloadKey, + JSON.stringify({ data: '{"marker":"legacy"}', updatedAt: 1 }) + ) + localStorage.setItem(scopedIndexKey, scopedIndex) + mountWorkflowPersistence() + + currentUserMocks.onUserResolved.mock.calls[0][0]({ id: 'user-a' }) + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-a' }) + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + await nextTick() + + expect(localStorage.getItem(workspaceIndexKey)).toBeNull() + expect(localStorage.getItem(workspacePayloadKey)).toBeNull() + expect(localStorage.getItem(scopedIndexKey)).toBe(scopedIndex) + }) + + it('writes the edit deferred during identity resolution once the identity resolves', async () => { + distributionMocks.isCloud = true + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: 'workspace-a', type: 'team' }) + ) + const workflowStore = useWorkflowStore() + const workflow = await workflowStore.createTemporary('Deferred.json').load() + workflowStore.activeWorkflow = workflow + mountWorkflowPersistence() + + mocks.state.currentGraph = { marker: 'before-identity' } + mocks.state.graphChangedHandler?.() + await vi.runAllTimersAsync() + + currentUserMocks.onUserResolved.mock.calls[0][0]({ id: 'user-a' }) + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-a' }) + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + await nextTick() + await vi.runAllTimersAsync() + + const payload = localStorage.getItem( + StorageKeys.draftPayload(workflow.path, 'user-a:workspace-a') + ) + expect(payload).not.toBeNull() + expect(JSON.parse(JSON.parse(payload!).data)).toEqual({ + marker: 'before-identity' + }) }) }) + +function legacyIndex(path: string) { + return { + v: 2, + updatedAt: 1, + order: [hashPath(path)], + entries: { + [hashPath(path)]: { + path, + name: path.replace(/\.json$/, ''), + isTemporary: true, + updatedAt: 1 + } + } + } +} diff --git a/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts b/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts index b09e5d3348b..708f7c0fd58 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts @@ -118,6 +118,17 @@ describe('useWorkflowTabState', () => { expect(getOpenPaths()).toBeNull() }) + it('ignores pointer written by a different user in the same workspace', async () => { + setCurrentWorkspace('ws-1') + const { setOpenPaths } = await loadTabState('user-a') + setOpenPaths(['workflows/test.json'], 0) + + vi.resetModules() + const { getOpenPaths } = await loadTabState('user-b') + + expect(getOpenPaths()).toBeNull() + }) + it('retains paths when staying in same workspace', async () => { setCurrentWorkspace('ws-1') const { setOpenPaths, getOpenPaths } = await loadTabState('user-a') diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 59db05a390c..bafef8cb135 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -56,7 +56,7 @@ function readJson(key: string): unknown { describe('migrateWorkspaceToScope', () => { beforeEach(() => { - vi.resetModules() + localStorage.clear() }) it('moves drafts and restore pointers into the scope and removes the workspace copy', () => { @@ -252,4 +252,83 @@ describe('migrateWorkspaceToScope', () => { path: draftPath }) }) + + it('keeps a restore pointer the scope already owns and still copies the missing one', () => { + seedSourceWorkspace() + const existingPointer = { + workspaceId: destinationScope, + path: 'workflows/existing.json' + } + localStorage.setItem( + StorageKeys.lastActivePath(destinationScope), + JSON.stringify(existingPointer) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.lastActivePath(destinationScope))).toEqual( + existingPointer + ) + expect(readJson(StorageKeys.lastOpenPaths(destinationScope))).toEqual({ + workspaceId: destinationScope, + paths: [draftPath], + activeIndex: 0 + }) + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + buildIndex() + ) + expect( + localStorage.getItem(StorageKeys.draftIndex(sourceWorkspaceId)) + ).toBe(null) + expect( + localStorage.getItem(StorageKeys.lastActivePath(sourceWorkspaceId)) + ).toBe(null) + expect( + localStorage.getItem(StorageKeys.lastOpenPaths(sourceWorkspaceId)) + ).toBe(null) + }) + + it('leaves a pre-existing scope restore pointer untouched when the copy rolls back', () => { + seedSourceWorkspace() + const existingPointer = { + workspaceId: destinationScope, + path: 'workflows/existing.json' + } + localStorage.setItem( + StorageKeys.lastActivePath(destinationScope), + JSON.stringify(existingPointer) + ) + const failingKey = StorageKeys.lastOpenPaths(destinationScope) + const realSetItem = localStorage.setItem.bind(localStorage) + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + if (key === failingKey) { + throw new DOMException('Quota exceeded', 'QuotaExceededError') + } + realSetItem(key, value) + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.lastActivePath(destinationScope))).toEqual( + existingPointer + ) + expect(localStorage.getItem(StorageKeys.draftIndex(destinationScope))).toBe( + null + ) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, destinationScope) + ) + ).toBe(null) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect(readJson(StorageKeys.lastOpenPaths(sourceWorkspaceId))).toEqual({ + workspaceId: sourceWorkspaceId, + paths: [draftPath], + activeIndex: 0 + }) + }) }) diff --git a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts index d0b247aafd9..b47c62da9b7 100644 --- a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts +++ b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts @@ -1,4 +1,5 @@ -import { createPinia, setActivePinia } from 'pinia' +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' import { beforeEach, describe, expect, it, vi } from 'vitest' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' @@ -32,7 +33,7 @@ describe('workflowDraftStoreV2 storage scope', () => { beforeEach(() => { localStorage.clear() sessionStorage.clear() - setActivePinia(createPinia()) + setActivePinia(createTestingPinia({ stubActions: false })) setStorageIdentity(null) }) From bb9ac3383856177099eb30d1bff5192f423c47a5 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 18:22:57 -0700 Subject: [PATCH 22/52] fix: keep scope restore pointers and flush edits deferred during identity resolution --- .../useWorkflowPersistenceV2.test.ts | 5 +++- .../composables/useWorkflowPersistenceV2.ts | 3 +-- .../migration/migrateWorkspaceToScope.ts | 25 ++++++++++++++----- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index 9bb2ad2851c..cb4bb6fb53a 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -777,7 +777,10 @@ describe('useWorkflowPersistenceV2', () => { workflow.path, `user-a:${destinationWorkspaceId}` ) - expect(localStorage.getItem(sourcePayloadKey)).toBeNull() + const payloadBeforeTransition = JSON.parse( + localStorage.getItem(sourcePayloadKey)! + ) + expect(JSON.parse(payloadBeforeTransition.data)).toEqual({ initial: true }) const cancelTransition = storageIO.prepareWorkflowWorkspaceTransition() sessionStorage.setItem( diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts index 1616c1d38a2..7f77053e11b 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts @@ -36,7 +36,6 @@ import { getStorageScope, getStorageWriteGate, prepareWorkflowLogoutTransition, - readIndex, registerWorkflowPersistenceFlush, setStorageIdentity } from '../base/storageIO' @@ -80,7 +79,6 @@ export function useWorkflowPersistenceV2() { migrateV1toV2(scope, clientId) return } - if (readIndex(scope) !== null) return migrateV1toV2(workspaceId, clientId) migrateWorkspaceToScope(workspaceId, scope) } @@ -177,6 +175,7 @@ export function useWorkflowPersistenceV2() { function releaseIdentityFence(): void { completeWorkflowLogoutTransition() ensureScopedStorage() + persistCurrentWorkflow() } onUserLogout(() => { diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index d31bd4f00bf..301b7676244 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -16,7 +16,9 @@ import { } from '../base/storageIO' import { StorageKeys } from '../base/storageKeys' -const restorePointerKeys = [ +type RestorePointerKey = (workspaceId: string) => string + +const restorePointerKeys: RestorePointerKey[] = [ StorageKeys.lastActivePath, StorageKeys.lastOpenPaths ] @@ -30,24 +32,35 @@ export function migrateWorkspaceToScope( const draftKeys = getPayloadKeys(workspaceId) if (readIndex(scope) !== null) { - removeScopeArtifacts(workspaceId, draftKeys) + removeScopeArtifacts(workspaceId, draftKeys, restorePointerKeys) return } + const missingPointerKeys = restorePointerKeys.filter( + (keyFor) => localStorage.getItem(keyFor(scope)) === null + ) const copied = draftKeys.every((draftKey) => copyPayload(workspaceId, scope, draftKey)) && - restorePointerKeys.every((keyFor) => + missingPointerKeys.every((keyFor) => copyRestorePointer(keyFor, workspaceId, scope) ) && writeIndex(scope, index) - removeScopeArtifacts(copied ? workspaceId : scope, draftKeys) + if (copied) { + removeScopeArtifacts(workspaceId, draftKeys, restorePointerKeys) + return + } + removeScopeArtifacts(scope, draftKeys, missingPointerKeys) } -function removeScopeArtifacts(scope: string, draftKeys: string[]): void { +function removeScopeArtifacts( + scope: string, + draftKeys: string[], + pointerKeys: RestorePointerKey[] +): void { deletePayloads(scope, draftKeys) localStorage.removeItem(StorageKeys.draftIndex(scope)) - for (const keyFor of restorePointerKeys) { + for (const keyFor of pointerKeys) { localStorage.removeItem(keyFor(scope)) } } From 3004beb827437a948e23b7702a9547b0822c27a2 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 18:24:48 -0700 Subject: [PATCH 23/52] test: sort storage keys with an explicit comparator --- src/platform/workflow/persistence/base/storageIO.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/platform/workflow/persistence/base/storageIO.test.ts b/src/platform/workflow/persistence/base/storageIO.test.ts index 6e3955abcaa..722ce158ef9 100644 --- a/src/platform/workflow/persistence/base/storageIO.test.ts +++ b/src/platform/workflow/persistence/base/storageIO.test.ts @@ -301,9 +301,7 @@ describe('storageIO', () => { clearWorkflowStorageForScope('ws-1') expect( - [...Array(localStorage.length)] - .map((_, index) => localStorage.key(index)) - .sort() + Object.keys(localStorage).toSorted((a, b) => a.localeCompare(b)) ).toEqual([ 'Comfy.Workflow.Draft.v2:ws-10:def', 'Comfy.Workflow.DraftIndex.v2:ws-10', From 2100c7ed22276fa1544e384be735c60ee0b884d0 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 9 Sep 2026 19:04:52 -0700 Subject: [PATCH 24/52] test: cover readWorkspaceId null and storage failures --- .../workflow/persistence/base/storageKeys.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/platform/workflow/persistence/base/storageKeys.test.ts b/src/platform/workflow/persistence/base/storageKeys.test.ts index 167606ae532..dd4e8a9c525 100644 --- a/src/platform/workflow/persistence/base/storageKeys.test.ts +++ b/src/platform/workflow/persistence/base/storageKeys.test.ts @@ -73,6 +73,18 @@ describe('storageKeys', () => { expect(readWorkspaceId()).toBeNull() }) + it('returns null in cloud when the stored workspace is JSON null', () => { + setCurrentWorkspace(null) + expect(readWorkspaceId()).toBeNull() + }) + + it('returns null in cloud when sessionStorage cannot be read', () => { + vi.spyOn(sessionStorage, 'getItem').mockImplementation(() => { + throw new Error('sessionStorage unavailable') + }) + expect(readWorkspaceId()).toBeNull() + }) + it('returns the team workspace id in cloud', () => { setCurrentWorkspace({ type: 'team', id: 'workspace-a' }) expect(readWorkspaceId()).toBe('workspace-a') From a150c65234df928e2cab502a9ecad2d0c0930212 Mon Sep 17 00:00:00 2001 From: Amp Date: Thu, 10 Sep 2026 03:55:09 +0000 Subject: [PATCH 25/52] test: expose cross-identity draft adoption Amp-Thread-ID: https://ampcode.com/threads/T-01a0895c-0438-716a-8d80-1dc0ca10fee0 --- .../useWorkflowPersistenceV2.test.ts | 40 ++++++++++++++++--- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index cb4bb6fb53a..f696b792cf3 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -1007,6 +1007,39 @@ describe('useWorkflowPersistenceV2', () => { expect(JSON.parse(userBPayload.data)).toEqual({ marker: 'user-b-edit' }) }) + it('does not adopt the previous identity canvas when the workspace stays ready', async () => { + distributionMocks.isCloud = true + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: 'workspace-a', type: 'team' }) + ) + const workflowStore = useWorkflowStore() + const workflow = await workflowStore + .createTemporary('IdentitySwap.json') + .load() + workflowStore.activeWorkflow = workflow + mountWorkflowPersistence() + const onUserResolved = currentUserMocks.onUserResolved.mock.calls[0][0] + + onUserResolved({ id: 'user-a' }) + Object.assign(useTeamWorkspaceStore(), { + activeWorkspaceId: 'workspace-a', + initState: 'ready' + }) + await nextTick() + + mocks.state.currentGraph = { marker: 'user-a-pending-edit' } + mocks.state.graphChangedHandler?.() + onUserResolved({ id: 'user-b' }) + await vi.runAllTimersAsync() + + expect( + localStorage.getItem( + StorageKeys.draftPayload(workflow.path, 'user-b:workspace-a') + ) + ).toBeNull() + }) + it('fences writes on the initial identity resolution until the workspace store confirms the workspace', async () => { distributionMocks.isCloud = true sessionStorage.setItem( @@ -1144,7 +1177,7 @@ describe('useWorkflowPersistenceV2', () => { expect(localStorage.getItem(scopedIndexKey)).toBe(scopedIndex) }) - it('writes the edit deferred during identity resolution once the identity resolves', async () => { + it('does not adopt an ownerless edit when the identity resolves', async () => { distributionMocks.isCloud = true sessionStorage.setItem( WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, @@ -1168,10 +1201,7 @@ describe('useWorkflowPersistenceV2', () => { const payload = localStorage.getItem( StorageKeys.draftPayload(workflow.path, 'user-a:workspace-a') ) - expect(payload).not.toBeNull() - expect(JSON.parse(JSON.parse(payload!).data)).toEqual({ - marker: 'before-identity' - }) + expect(payload).toBeNull() }) }) From 9000422b9b4ade58d004ab061c3b60365bf2a23b Mon Sep 17 00:00:00 2001 From: Amp Date: Thu, 10 Sep 2026 03:57:28 +0000 Subject: [PATCH 26/52] test: preserve resolved deferred draft writes Amp-Thread-ID: https://ampcode.com/threads/T-01a0895c-0438-716a-8d80-1dc0ca10fee0 --- .../persistence/composables/useWorkflowPersistenceV2.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index f696b792cf3..b8fbacd453b 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -1068,6 +1068,11 @@ describe('useWorkflowPersistenceV2', () => { Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-a' }) Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) await nextTick() + + expect( + JSON.parse(JSON.parse(localStorage.getItem(payloadKey)!).data) + ).toEqual({ marker: 'before-workspace-ready' }) + mocks.state.currentGraph = { marker: 'after-workspace-ready' } mocks.state.graphChangedHandler?.() await vi.runAllTimersAsync() From 0bdd0b4b5b5ad0b79fc241df6e81f0b9ce00e89f Mon Sep 17 00:00:00 2001 From: Amp Date: Thu, 10 Sep 2026 04:00:52 +0000 Subject: [PATCH 27/52] fix: retain draft persistence ownership Amp-Thread-ID: https://ampcode.com/threads/T-01a0895c-0438-716a-8d80-1dc0ca10fee0 --- .../useWorkflowPersistenceV2.test.ts | 3 ++ .../composables/useWorkflowPersistenceV2.ts | 45 +++++++++++++++---- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index b8fbacd453b..d95105baafa 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -763,6 +763,9 @@ describe('useWorkflowPersistenceV2', () => { Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) await nextTick() + mocks.state.graphChangedHandler?.() + await vi.runAllTimersAsync() + mocks.state.currentGraph = { nodes: [], extra: { marker: 'workspace-a-final-edit' } diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts index 7f77053e11b..d36f09e91dd 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts @@ -104,6 +104,8 @@ export function useWorkflowPersistenceV2() { ) const lastSavedJsonByPath = ref>({}) + let resolvedUserId: string | null = null + let pendingPersistenceOwnerId: string | null = null watch(workflowPersistenceEnabled, (enabled) => { if (!enabled) { @@ -113,17 +115,27 @@ export function useWorkflowPersistenceV2() { }) const persistCurrentWorkflow = () => { - if (!workflowPersistenceEnabled.value) return + if (!workflowPersistenceEnabled.value) { + pendingPersistenceOwnerId = null + return + } const activeWorkflow = workflowStore.activeWorkflow - if (!activeWorkflow) return + if (!activeWorkflow) { + pendingPersistenceOwnerId = null + return + } const graphData = comfyApp.rootGraph.serialize() const workflowJson = JSON.stringify(graphData) const workflowPath = activeWorkflow.path // Skip if unchanged - if (workflowJson === lastSavedJsonByPath.value[workflowPath]) return + if (workflowJson === lastSavedJsonByPath.value[workflowPath]) { + pendingPersistenceOwnerId = null + return + } if (getStorageWriteGate() === 'deferred') return + pendingPersistenceOwnerId = null // Save to V2 draft store const saved = draftStore.saveDraft(workflowPath, workflowJson, { @@ -154,6 +166,16 @@ export function useWorkflowPersistenceV2() { // Debounced version for graphChanged events const debouncedPersist = debounce(persistCurrentWorkflow, PERSIST_DEBOUNCE_MS) + function scheduleWorkflowPersistence(): void { + pendingPersistenceOwnerId = resolvedUserId + debouncedPersist() + } + + function persistWorkflowForCurrentOwner(): void { + pendingPersistenceOwnerId = resolvedUserId + persistCurrentWorkflow() + } + function flushPendingPersistence() { debouncedPersist.flush() } @@ -163,11 +185,10 @@ export function useWorkflowPersistenceV2() { ) window.addEventListener('pagehide', flushPendingPersistence) - let resolvedUserId: string | null = null - function fenceIdentityChange(): void { stopPendingWorkspaceReadinessWatcher() debouncedPersist.cancel() + pendingPersistenceOwnerId = null prepareWorkflowLogoutTransition() lastSavedJsonByPath.value = {} } @@ -175,7 +196,13 @@ export function useWorkflowPersistenceV2() { function releaseIdentityFence(): void { completeWorkflowLogoutTransition() ensureScopedStorage() - persistCurrentWorkflow() + if ( + pendingPersistenceOwnerId !== null && + pendingPersistenceOwnerId === resolvedUserId + ) { + debouncedPersist.cancel() + persistCurrentWorkflow() + } } onUserLogout(() => { @@ -337,16 +364,16 @@ export function useWorkflowPersistenceV2() { // Flush any pending persistence from the previous workflow debouncedPersist.flush() // Persist the new workflow immediately - persistCurrentWorkflow() + persistWorkflowForCurrentOwner() } ) // Debounced persistence on graph changes - api.addEventListener('graphChanged', debouncedPersist) + api.addEventListener('graphChanged', scheduleWorkflowPersistence) // Clean up event listener when component unmounts tryOnScopeDispose(() => { - api.removeEventListener('graphChanged', debouncedPersist) + api.removeEventListener('graphChanged', scheduleWorkflowPersistence) window.removeEventListener('pagehide', flushPendingPersistence) unregisterPersistenceFlush() debouncedPersist.cancel() From 9c576868b374590597542e1d657366b00e7b02a6 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 10 Sep 2026 18:50:31 -0700 Subject: [PATCH 28/52] test: narrow draft payload before parsing Read the persisted payload through the storage adapter and narrow it at runtime instead of asserting non-null before JSON.parse. Addresses: https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3975349284 --- .../useWorkflowPersistenceV2.test.ts | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index d95105baafa..42527a47a03 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -1072,17 +1072,29 @@ describe('useWorkflowPersistenceV2', () => { Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) await nextTick() - expect( - JSON.parse(JSON.parse(localStorage.getItem(payloadKey)!).data) - ).toEqual({ marker: 'before-workspace-ready' }) + const readyPayload = storageIO.readPayload( + 'user-a:workspace-a', + hashPath(workflow.path) + ) + expect(readyPayload).not.toBeNull() + if (!readyPayload) return + expect(JSON.parse(readyPayload.data)).toEqual({ + marker: 'before-workspace-ready' + }) mocks.state.currentGraph = { marker: 'after-workspace-ready' } mocks.state.graphChangedHandler?.() await vi.runAllTimersAsync() - expect( - JSON.parse(JSON.parse(localStorage.getItem(payloadKey)!).data) - ).toEqual({ marker: 'after-workspace-ready' }) + const updatedPayload = storageIO.readPayload( + 'user-a:workspace-a', + hashPath(workflow.path) + ) + expect(updatedPayload).not.toBeNull() + if (!updatedPayload) return + expect(JSON.parse(updatedPayload.data)).toEqual({ + marker: 'after-workspace-ready' + }) }) it('stays silent while the write gate is deferred on an unresolved identity', async () => { From 374c03b41e2e41cfde33a54f4349ce29ba5e6d17 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 00:15:02 -0700 Subject: [PATCH 29/52] fix: claim workspace drafts before migrating them Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3985409586 --- .../workflow/persistence/base/storageIO.ts | 14 ++- .../workflow/persistence/base/storageKeys.ts | 7 +- .../migration/migrateWorkspaceToScope.test.ts | 69 +++++++++++++++ .../migration/migrateWorkspaceToScope.ts | 86 ++++++++++++------- 4 files changed, 139 insertions(+), 37 deletions(-) diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index 0fd87da1f1d..f93b203e4e7 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -438,7 +438,7 @@ function isValidOpenPathsPointer(value: unknown): value is OpenPathsPointer { ) } -function readLocalPointer( +export function readLocalPointer( key: string, validate: (value: unknown) => value is T ): T | null { @@ -452,13 +452,19 @@ function readLocalPointer( } } -function writeStorage(storage: Storage, key: string, value: string): void { - if (!isStorageAvailable()) return +export function writeStorage( + storage: Storage, + key: string, + value: string +): boolean { + if (!isStorageAvailable()) return false try { storage.setItem(key, value) + return true } catch { // Best effort — silently degrade when storage is full or unavailable + return false } } @@ -486,7 +492,7 @@ const sessionRestoreKeys = [ 'Comfy.ActiveWorkflowIndex' ] -function removeStorageKeys( +export function removeStorageKeys( storage: Storage, keys: string[], prefixes: string[] = [] diff --git a/src/platform/workflow/persistence/base/storageKeys.ts b/src/platform/workflow/persistence/base/storageKeys.ts index 94d9a3f65ba..1b0b74263de 100644 --- a/src/platform/workflow/persistence/base/storageKeys.ts +++ b/src/platform/workflow/persistence/base/storageKeys.ts @@ -111,6 +111,10 @@ export const StorageKeys = { return `Comfy.Workflow.LastOpenPaths:${workspaceId}` }, + migrationClaim(workspaceId: string): string { + return `Comfy.Workflow.MigrationClaim:${workspaceId}` + }, + /** * Prefix patterns for cleanup operations. */ @@ -120,6 +124,7 @@ export const StorageKeys = { activePath: 'Comfy.Workflow.ActivePath:', openPaths: 'Comfy.Workflow.OpenPaths:', lastActivePath: 'Comfy.Workflow.LastActivePath:', - lastOpenPaths: 'Comfy.Workflow.LastOpenPaths:' + lastOpenPaths: 'Comfy.Workflow.LastOpenPaths:', + migrationClaim: 'Comfy.Workflow.MigrationClaim:' } } as const diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index bafef8cb135..dc894744fd3 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -108,6 +108,10 @@ describe('migrateWorkspaceToScope', () => { StorageKeys.draftIndex(destinationScope), JSON.stringify(destinationIndex) ) + localStorage.setItem( + StorageKeys.migrationClaim(sourceWorkspaceId), + JSON.stringify({ scope: destinationScope, sourceUpdatedAt: 10 }) + ) migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) @@ -133,6 +137,9 @@ describe('migrateWorkspaceToScope', () => { expect( localStorage.getItem(StorageKeys.lastOpenPaths(sourceWorkspaceId)) ).toBe(null) + expect( + localStorage.getItem(StorageKeys.migrationClaim(sourceWorkspaceId)) + ).toBe(null) }) it('leaves a committed destination alone when there is no source to clean up', () => { @@ -331,4 +338,66 @@ describe('migrateWorkspaceToScope', () => { activeIndex: 0 }) }) + + it('preserves the workspace when another scope holds the migration claim', () => { + seedSourceWorkspace() + localStorage.setItem( + StorageKeys.migrationClaim(sourceWorkspaceId), + JSON.stringify({ + scope: 'user-b:workspace-a', + sourceUpdatedAt: 10 + }) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(localStorage.getItem(StorageKeys.draftIndex(destinationScope))).toBe( + null + ) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + }) + + it('preserves a newer workspace when the committed destination claim is stale', () => { + seedSourceWorkspace() + localStorage.setItem( + StorageKeys.draftIndex(destinationScope), + JSON.stringify(buildIndex()) + ) + localStorage.setItem( + StorageKeys.migrationClaim(sourceWorkspaceId), + JSON.stringify({ scope: destinationScope, sourceUpdatedAt: 5 }) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + }) + + it('preserves the workspace when the destination has no migration claim', () => { + seedSourceWorkspace() + localStorage.setItem( + StorageKeys.draftIndex(destinationScope), + JSON.stringify(buildIndex()) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + }) + + it('removes the migration claim after a successful migration', () => { + seedSourceWorkspace() + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect( + localStorage.getItem(StorageKeys.migrationClaim(sourceWorkspaceId)) + ).toBe(null) + }) }) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index 301b7676244..9d75f504c25 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -1,46 +1,68 @@ -/** - * Workspace-to-scope migration - * - * Moves drafts stored under a bare workspace id into a user-scoped key space. - * The destination index is written last so a partial copy never looks - * complete, and the source is removed only after the destination is whole. - */ - import { deletePayloads, getPayloadKeys, readIndex, + readLocalPointer, readPayload, + removeStorageKeys, writeIndex, - writePayload + writePayload, + writeStorage } from '../base/storageIO' import { StorageKeys } from '../base/storageKeys' -type RestorePointerKey = (workspaceId: string) => string +type MigrationClaim = { + scope: string + sourceUpdatedAt: number +} -const restorePointerKeys: RestorePointerKey[] = [ +const restorePointerKeys = [ StorageKeys.lastActivePath, StorageKeys.lastOpenPaths ] +function isValidClaim(value: unknown): value is MigrationClaim { + if (typeof value !== 'object' || value === null) return false + const candidate = value as Record + return ( + typeof candidate.scope === 'string' && + typeof candidate.sourceUpdatedAt === 'number' + ) +} + export function migrateWorkspaceToScope( workspaceId: string, scope: string ): void { const index = readIndex(workspaceId) - if (index === null) return + if (!index) return + + const claimKey = StorageKeys.migrationClaim(workspaceId) + const existingClaim = readLocalPointer(claimKey, isValidClaim) + if (existingClaim && existingClaim.scope !== scope) return const draftKeys = getPayloadKeys(workspaceId) - if (readIndex(scope) !== null) { + + if (readIndex(scope)) { + const ownsDestination = + existingClaim !== null && index.updatedAt <= existingClaim.sourceUpdatedAt + if (!ownsDestination) return removeScopeArtifacts(workspaceId, draftKeys, restorePointerKeys) + removeStorageKeys(localStorage, [claimKey]) return } + const claim: MigrationClaim = { scope, sourceUpdatedAt: index.updatedAt } + if (!writeStorage(localStorage, claimKey, JSON.stringify(claim))) return + const committedClaim = readLocalPointer(claimKey, isValidClaim) + if (committedClaim?.scope !== scope) return + const missingPointerKeys = restorePointerKeys.filter( (keyFor) => localStorage.getItem(keyFor(scope)) === null ) + const copied = - draftKeys.every((draftKey) => copyPayload(workspaceId, scope, draftKey)) && + draftKeys.every((draftKey) => copyPayload(draftKey, workspaceId, scope)) && missingPointerKeys.every((keyFor) => copyRestorePointer(keyFor, workspaceId, scope) ) && @@ -48,49 +70,49 @@ export function migrateWorkspaceToScope( if (copied) { removeScopeArtifacts(workspaceId, draftKeys, restorePointerKeys) - return + } else { + removeScopeArtifacts(scope, draftKeys, missingPointerKeys) } - removeScopeArtifacts(scope, draftKeys, missingPointerKeys) + removeStorageKeys(localStorage, [claimKey]) } function removeScopeArtifacts( scope: string, draftKeys: string[], - pointerKeys: RestorePointerKey[] + pointerKeys: ((scope: string) => string)[] ): void { deletePayloads(scope, draftKeys) - localStorage.removeItem(StorageKeys.draftIndex(scope)) - for (const keyFor of pointerKeys) { - localStorage.removeItem(keyFor(scope)) - } + removeStorageKeys(localStorage, [ + StorageKeys.draftIndex(scope), + ...pointerKeys.map((keyFor) => keyFor(scope)) + ]) } function copyPayload( + draftKey: string, workspaceId: string, - scope: string, - draftKey: string + scope: string ): boolean { const payload = readPayload(workspaceId, draftKey) - if (payload === null) return true + if (!payload) return false return writePayload(scope, draftKey, payload) } function copyRestorePointer( - keyFor: (workspaceId: string) => string, + keyFor: (scope: string) => string, workspaceId: string, scope: string ): boolean { - const json = localStorage.getItem(keyFor(workspaceId)) - if (!json) return true - try { - const pointer: unknown = JSON.parse(json) - if (typeof pointer !== 'object' || pointer === null) return true - localStorage.setItem( + const raw = localStorage.getItem(keyFor(workspaceId)) + if (raw === null) return true + const pointer: unknown = JSON.parse(raw) + if (typeof pointer !== 'object' || pointer === null) return false + return writeStorage( + localStorage, keyFor(scope), JSON.stringify({ ...pointer, workspaceId: scope }) ) - return true } catch { return false } From ec101abad64732fcad7441d17dea85ad3b8e5bb2 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 00:25:40 -0700 Subject: [PATCH 30/52] refactor: name scope parameters in draft storage keys Storage key builders and IO helpers now take the resolved scope string rather than a workspace id, matching what callers pass on cloud. The persistence test file is staged alongside so the hook typecheck sees the updated signatures; its non-null assertions are dropped in the same change. Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3985409589 Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3985409594 --- .../workflow/persistence/base/storageIO.ts | 75 ++++++++--------- .../workflow/persistence/base/storageKeys.ts | 18 ++-- .../useWorkflowPersistenceV2.test.ts | 47 +++++++---- .../stores/workflowDraftStoreV2.ts | 83 +++++++++---------- 4 files changed, 116 insertions(+), 107 deletions(-) diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index f93b203e4e7..ce103024312 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -117,11 +117,11 @@ function isValidIndex(value: unknown): value is DraftIndexV2 { /** * Reads and parses the draft index from localStorage. */ -export function readIndex(workspaceId: string): DraftIndexV2 | null { +export function readIndex(scope: string): DraftIndexV2 | null { if (!isStorageReadable()) return null try { - const key = StorageKeys.draftIndex(workspaceId) + const key = StorageKeys.draftIndex(scope) const json = localStorage.getItem(key) if (!json) return null @@ -137,11 +137,11 @@ export function readIndex(workspaceId: string): DraftIndexV2 | null { /** * Writes the draft index to localStorage. */ -export function writeIndex(workspaceId: string, index: DraftIndexV2): boolean { +export function writeIndex(scope: string, index: DraftIndexV2): boolean { if (!isStorageAvailable()) return false try { - const key = StorageKeys.draftIndex(workspaceId) + const key = StorageKeys.draftIndex(scope) localStorage.setItem(key, JSON.stringify(index)) return true } catch (error) { @@ -154,13 +154,13 @@ export function writeIndex(workspaceId: string, index: DraftIndexV2): boolean { * Reads a draft payload from localStorage. */ export function readPayload( - workspaceId: string, + scope: string, draftKey: string ): DraftPayloadV2 | null { if (!isStorageReadable()) return null try { - const key = `${StorageKeys.prefixes.draftPayload}${workspaceId}:${draftKey}` + const key = `${StorageKeys.prefixes.draftPayload}${scope}:${draftKey}` const json = localStorage.getItem(key) if (!json) return null @@ -174,14 +174,14 @@ export function readPayload( * Writes a draft payload to localStorage. */ export function writePayload( - workspaceId: string, + scope: string, draftKey: string, payload: DraftPayloadV2 ): boolean { if (!isStorageAvailable()) return false try { - const key = `${StorageKeys.prefixes.draftPayload}${workspaceId}:${draftKey}` + const key = `${StorageKeys.prefixes.draftPayload}${scope}:${draftKey}` localStorage.setItem(key, JSON.stringify(payload)) return true } catch (error) { @@ -193,9 +193,9 @@ export function writePayload( /** * Deletes a draft payload from localStorage. */ -export function deletePayload(workspaceId: string, draftKey: string): void { +export function deletePayload(scope: string, draftKey: string): void { try { - const key = `${StorageKeys.prefixes.draftPayload}${workspaceId}:${draftKey}` + const key = `${StorageKeys.prefixes.draftPayload}${scope}:${draftKey}` localStorage.removeItem(key) } catch { // Ignore errors during deletion @@ -205,19 +205,19 @@ export function deletePayload(workspaceId: string, draftKey: string): void { /** * Deletes multiple draft payloads from localStorage. */ -export function deletePayloads(workspaceId: string, draftKeys: string[]): void { +export function deletePayloads(scope: string, draftKeys: string[]): void { for (const draftKey of draftKeys) { - deletePayload(workspaceId, draftKey) + deletePayload(scope, draftKey) } } /** - * Gets all draft payload keys for a workspace from localStorage. + * Gets all draft payload keys for a scope from localStorage. */ -export function getPayloadKeys(workspaceId: string): string[] { +export function getPayloadKeys(scope: string): string[] { if (!isStorageReadable()) return [] - const prefix = `${StorageKeys.prefixes.draftPayload}${workspaceId}:` + const prefix = `${StorageKeys.prefixes.draftPayload}${scope}:` const keys: string[] = [] try { @@ -238,15 +238,15 @@ export function getPayloadKeys(workspaceId: string): string[] { * Deletes orphan payloads that are not in the index. */ export function deleteOrphanPayloads( - workspaceId: string, + scope: string, indexKeys: Set ): number { - const payloadKeys = getPayloadKeys(workspaceId) + const payloadKeys = getPayloadKeys(scope) let deleted = 0 for (const key of payloadKeys) { if (!indexKeys.has(key)) { - deletePayload(workspaceId, key) + deletePayload(scope, key) deleted++ } } @@ -255,14 +255,14 @@ export function deleteOrphanPayloads( } /** - * Searches sessionStorage for a pointer matching the target workspaceId + * Searches sessionStorage for a pointer matching the target scope * when the exact clientId key has no entry (e.g. clientId changed after reload). * Migrates the found pointer to the new clientId key. */ function findAndMigratePointer( newKey: string, prefix: string, - targetWorkspaceId: string, + targetScope: string, isValid: (value: unknown) => value is T ): T | null { for (let i = 0; i < sessionStorage.length; i++) { @@ -274,7 +274,7 @@ function findAndMigratePointer( try { const pointer: unknown = JSON.parse(json) - if (isValid(pointer) && pointer.workspaceId === targetWorkspaceId) { + if (isValid(pointer) && pointer.workspaceId === targetScope) { sessionStorage.setItem(newKey, json) sessionStorage.removeItem(storageKey) return pointer @@ -290,12 +290,12 @@ function findAndMigratePointer( * Reads a session pointer by clientId with workspace-based fallback. * Validates workspace on exact match and removes stale cross-workspace pointers. * If no valid entry exists, searches for any pointer matching the target - * workspaceId and migrates it to the new key. + * scope and migrates it to the new key. */ function readSessionPointer( key: string, prefix: string, - targetWorkspaceId: string | undefined, + targetScope: string | undefined, isValid: (value: unknown) => value is T ): T | null { try { @@ -304,18 +304,15 @@ function readSessionPointer( const pointer: unknown = JSON.parse(json) if (!isValid(pointer)) { sessionStorage.removeItem(key) - } else if ( - targetWorkspaceId && - pointer.workspaceId !== targetWorkspaceId - ) { + } else if (targetScope && pointer.workspaceId !== targetScope) { sessionStorage.removeItem(key) } else { return pointer } } - if (targetWorkspaceId) { - return findAndMigratePointer(key, prefix, targetWorkspaceId, isValid) + if (targetScope) { + return findAndMigratePointer(key, prefix, targetScope, isValid) } return null @@ -331,18 +328,18 @@ function readSessionPointer( */ export function readActivePath( clientId: string, - targetWorkspaceId?: string + targetScope?: string ): ActivePathPointer | null { return ( readSessionPointer( StorageKeys.activePath(clientId), StorageKeys.prefixes.activePath, - targetWorkspaceId, + targetScope, isValidActivePathPointer ) ?? - (targetWorkspaceId + (targetScope ? readLocalPointer( - StorageKeys.lastActivePath(targetWorkspaceId), + StorageKeys.lastActivePath(targetScope), isValidActivePathPointer ) : null) @@ -367,10 +364,10 @@ export function writeActivePath( } /** Inverse of {@link writeActivePath}: drops both pointers it writes. */ -export function clearActivePath(clientId: string, workspaceId: string): void { +export function clearActivePath(clientId: string, scope: string): void { try { sessionStorage.removeItem(StorageKeys.activePath(clientId)) - localStorage.removeItem(StorageKeys.lastActivePath(workspaceId)) + localStorage.removeItem(StorageKeys.lastActivePath(scope)) } catch { // Storage access can throw in private-mode browsers; nothing to undo. } @@ -383,18 +380,18 @@ export function clearActivePath(clientId: string, workspaceId: string): void { */ export function readOpenPaths( clientId: string, - targetWorkspaceId?: string + targetScope?: string ): OpenPathsPointer | null { return ( readSessionPointer( StorageKeys.openPaths(clientId), StorageKeys.prefixes.openPaths, - targetWorkspaceId, + targetScope, isValidOpenPathsPointer ) ?? - (targetWorkspaceId + (targetScope ? readLocalPointer( - StorageKeys.lastOpenPaths(targetWorkspaceId), + StorageKeys.lastOpenPaths(targetScope), isValidOpenPathsPointer ) : null) diff --git a/src/platform/workflow/persistence/base/storageKeys.ts b/src/platform/workflow/persistence/base/storageKeys.ts index 1b0b74263de..f0dea7adfbe 100644 --- a/src/platform/workflow/persistence/base/storageKeys.ts +++ b/src/platform/workflow/persistence/base/storageKeys.ts @@ -54,7 +54,7 @@ export function resolveStorageScope( /** * Storage key generators for V2 workflow persistence. * - * localStorage keys are scoped by workspaceId. + * localStorage keys are scoped by storage scope. * sessionStorage keys are scoped by clientId. */ export const StorageKeys = { @@ -62,17 +62,17 @@ export const StorageKeys = { * Draft index key for localStorage. * Contains LRU order and metadata for all drafts. */ - draftIndex(workspaceId: string): string { - return `Comfy.Workflow.DraftIndex.v2:${workspaceId}` + draftIndex(scope: string): string { + return `Comfy.Workflow.DraftIndex.v2:${scope}` }, /** * Individual draft payload key for localStorage. * @param path - Workflow path (will be hashed to create key) */ - draftPayload(path: string, workspaceId: string): string { + draftPayload(path: string, scope: string): string { const draftKey = hashPath(path) - return `Comfy.Workflow.Draft.v2:${workspaceId}:${draftKey}` + return `Comfy.Workflow.Draft.v2:${scope}:${draftKey}` }, /** @@ -103,12 +103,12 @@ export const StorageKeys = { * sessionStorage is per-tab (correct for in-session use) but lost * on browser restart; these keys preserve the last-written state. */ - lastActivePath(workspaceId: string): string { - return `Comfy.Workflow.LastActivePath:${workspaceId}` + lastActivePath(scope: string): string { + return `Comfy.Workflow.LastActivePath:${scope}` }, - lastOpenPaths(workspaceId: string): string { - return `Comfy.Workflow.LastOpenPaths:${workspaceId}` + lastOpenPaths(scope: string): string { + return `Comfy.Workflow.LastOpenPaths:${scope}` }, migrationClaim(workspaceId: string): string { diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index 42527a47a03..404446aeefa 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -7,12 +7,31 @@ import { createI18n } from 'vue-i18n' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' +import type { DraftPayloadV2 } from '../base/draftTypes' import { hashPath } from '../base/hashUtil' import { StorageKeys } from '../base/storageKeys' import * as storageIO from '../base/storageIO' import { useWorkflowDraftStoreV2 } from '../stores/workflowDraftStoreV2' import { useWorkflowPersistenceV2 } from './useWorkflowPersistenceV2' +function readDraftPayload(key: string): DraftPayloadV2 { + const raw = localStorage.getItem(key) + expect(raw).not.toBeNull() + if (raw === null) throw new Error(`Missing draft payload: ${key}`) + + const payload: unknown = JSON.parse(raw) + if (typeof payload !== 'object' || payload === null) { + throw new Error(`Invalid draft payload: ${key}`) + } + if (!('data' in payload) || typeof payload.data !== 'string') { + throw new Error(`Invalid draft payload: ${key}`) + } + if (!('updatedAt' in payload) || typeof payload.updatedAt !== 'number') { + throw new Error(`Invalid draft payload: ${key}`) + } + return { data: payload.data, updatedAt: payload.updatedAt } +} + const mockToastAdd = vi.fn() vi.mock( import('primevue'), // eslint-disable-line primevue-removal/no-imports @@ -708,7 +727,7 @@ describe('useWorkflowPersistenceV2', () => { window.dispatchEvent(new PageTransitionEvent('pagehide')) - const payload = JSON.parse(localStorage.getItem(payloadKey)!) + const payload = readDraftPayload(payloadKey) expect(JSON.parse(payload.data)).toEqual({ nodes: [], extra: { marker: 'final-edit' } @@ -780,9 +799,7 @@ describe('useWorkflowPersistenceV2', () => { workflow.path, `user-a:${destinationWorkspaceId}` ) - const payloadBeforeTransition = JSON.parse( - localStorage.getItem(sourcePayloadKey)! - ) + const payloadBeforeTransition = readDraftPayload(sourcePayloadKey) expect(JSON.parse(payloadBeforeTransition.data)).toEqual({ initial: true }) const cancelTransition = storageIO.prepareWorkflowWorkspaceTransition() @@ -797,7 +814,7 @@ describe('useWorkflowPersistenceV2', () => { mocks.state.graphChangedHandler?.() await vi.runAllTimersAsync() - const sourcePayload = JSON.parse(localStorage.getItem(sourcePayloadKey)!) + const sourcePayload = readDraftPayload(sourcePayloadKey) expect(JSON.parse(sourcePayload.data)).toEqual({ nodes: [], extra: { marker: 'workspace-a-final-edit' } @@ -993,7 +1010,7 @@ describe('useWorkflowPersistenceV2', () => { onUserResolved({ id: 'user-b' }) await vi.runAllTimersAsync() - const userAPayload = JSON.parse(localStorage.getItem(userAPayloadKey)!) + const userAPayload = readDraftPayload(userAPayloadKey) expect(JSON.parse(userAPayload.data)).toEqual({ marker: 'user-a-edit' }) expect(localStorage.getItem(userBPayloadKey)).toBeNull() @@ -1003,10 +1020,8 @@ describe('useWorkflowPersistenceV2', () => { mocks.state.graphChangedHandler?.() await vi.runAllTimersAsync() - expect(JSON.parse(localStorage.getItem(userAPayloadKey)!).data).toBe( - userAPayload.data - ) - const userBPayload = JSON.parse(localStorage.getItem(userBPayloadKey)!) + expect(readDraftPayload(userAPayloadKey).data).toBe(userAPayload.data) + const userBPayload = readDraftPayload(userBPayloadKey) expect(JSON.parse(userBPayload.data)).toEqual({ marker: 'user-b-edit' }) }) @@ -1152,10 +1167,8 @@ describe('useWorkflowPersistenceV2', () => { localStorage.getItem(StorageKeys.draftIndex('user-a:workspace-a')) ).not.toBeNull() expect( - JSON.parse( - localStorage.getItem( - StorageKeys.draftPayload('Legacy.json', 'user-a:workspace-a') - )! + readDraftPayload( + StorageKeys.draftPayload('Legacy.json', 'user-a:workspace-a') ).data ).toBe('{"marker":"legacy"}') expect(useWorkflowDraftStoreV2().getDraft('Legacy.json')?.data).toBe( @@ -1163,7 +1176,7 @@ describe('useWorkflowPersistenceV2', () => { ) }) - it('removes stale workspace drafts even when the user scope already has an index', async () => { + it('preserves unclaimed workspace drafts when the user scope already has an index', async () => { distributionMocks.isCloud = true sessionStorage.setItem( WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, @@ -1192,8 +1205,8 @@ describe('useWorkflowPersistenceV2', () => { Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) await nextTick() - expect(localStorage.getItem(workspaceIndexKey)).toBeNull() - expect(localStorage.getItem(workspacePayloadKey)).toBeNull() + expect(localStorage.getItem(workspaceIndexKey)).not.toBeNull() + expect(localStorage.getItem(workspacePayloadKey)).not.toBeNull() expect(localStorage.getItem(scopedIndexKey)).toBe(scopedIndex) }) diff --git a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts index e6200fd9ed6..fb9241ba79a 100644 --- a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts +++ b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts @@ -49,51 +49,50 @@ interface LoadPersistedWorkflowOptions { } export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { - // In-memory cache of the index per workspace (synced with localStorage) - // Key is workspaceId, value is the cached index - const indexCacheByWorkspace = ref>({}) + // In-memory cache of the index per scope (synced with localStorage) + const indexCacheByScope = ref>({}) /** * Loads the index from localStorage or creates empty. */ function loadIndex(): DraftIndexV2 { - const workspaceId = getStorageScope() - if (!workspaceId) return createEmptyIndex() + const scope = getStorageScope() + if (!scope) return createEmptyIndex() - const cached = getCachedIndex(workspaceId) + const cached = getCachedIndex(scope) if (cached) return cached - const stored = readIndex(workspaceId) + const stored = readIndex(scope) if (stored) { // Clean up any index/payload drift - const payloadKeys = new Set(getPayloadKeys(workspaceId)) + const payloadKeys = new Set(getPayloadKeys(scope)) const cleaned = removeOrphanedEntries(stored, payloadKeys) - indexCacheByWorkspace.value[workspaceId] = cleaned + indexCacheByScope.value[scope] = cleaned // Also clean up orphan payloads const indexKeys = new Set(cleaned.order) - deleteOrphanPayloads(workspaceId, indexKeys) + deleteOrphanPayloads(scope, indexKeys) return cleaned } const emptyIndex = createEmptyIndex() - indexCacheByWorkspace.value[workspaceId] = emptyIndex + indexCacheByScope.value[scope] = emptyIndex return emptyIndex } - function getCachedIndex(workspaceId: string): DraftIndexV2 | null { - return indexCacheByWorkspace.value[workspaceId] + function getCachedIndex(scope: string): DraftIndexV2 | null { + return indexCacheByScope.value[scope] } /** * Persists the current index to localStorage. */ function persistIndex(index: DraftIndexV2): boolean { - const workspaceId = getStorageScope() - if (!workspaceId) return false - indexCacheByWorkspace.value[workspaceId] = index - return writeIndex(workspaceId, index) + const scope = getStorageScope() + if (!scope) return false + indexCacheByScope.value[scope] = index + return writeIndex(scope, index) } /** @@ -101,8 +100,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Primes index cache, writes payload, then persists updated index. */ function saveDraft(path: string, data: string, meta: DraftMeta): boolean { - const workspaceId = getStorageScope() - if (!workspaceId || !isStorageAvailable()) return false + const scope = getStorageScope() + if (!scope || !isStorageAvailable()) return false const draftKey = hashPath(path) const now = Date.now() @@ -113,7 +112,7 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { const index = loadIndex() // Write payload before persisting the updated index - const payloadWritten = writePayload(workspaceId, draftKey, { + const payloadWritten = writePayload(scope, draftKey, { data, updatedAt: now }) @@ -130,12 +129,12 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { ) if (!persistIndex(newIndex)) { - deletePayload(workspaceId, draftKey) + deletePayload(scope, draftKey) persistIndex(index) return false } - deletePayloads(workspaceId, evicted) + deletePayloads(scope, evicted) return true } @@ -157,8 +156,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { data: string, meta: DraftMeta ): boolean { - const workspaceId = getStorageScope() - if (!workspaceId) return false + const scope = getStorageScope() + if (!scope) return false const draftKey = hashPath(path) let currentIndex = loadIndex() @@ -177,12 +176,12 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { const result = removeEntry(currentIndex, oldestEntry.path) currentIndex = result.index if (result.removedKey) { - deletePayload(workspaceId, result.removedKey) + deletePayload(scope, result.removedKey) evictedCount++ } const now = Date.now() - if (writePayload(workspaceId, draftKey, { data, updatedAt: now })) { + if (writePayload(scope, draftKey, { data, updatedAt: now })) { const { index: finalIndex } = upsertEntry( currentIndex, path, @@ -190,7 +189,7 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { MAX_DRAFTS ) if (!persistIndex(finalIndex)) { - deletePayload(workspaceId, draftKey) + deletePayload(scope, draftKey) persistIndex(currentIndex) return false } @@ -254,13 +253,13 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Removes a draft. */ function removeDraft(path: string): void { - const workspaceId = getStorageScope() - if (!workspaceId) return + const scope = getStorageScope() + if (!scope) return const index = loadIndex() const { index: newIndex, removedKey } = removeEntry(index, path) if (removedKey) { - deletePayload(workspaceId, removedKey) + deletePayload(scope, removedKey) persistIndex(newIndex) } } @@ -269,25 +268,25 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Moves a draft from one path to another (rename). */ function moveDraft(oldPath: string, newPath: string, name: string): void { - const workspaceId = getStorageScope() - if (!workspaceId) return + const scope = getStorageScope() + if (!scope) return const index = loadIndex() const result = moveEntry(index, oldPath, newPath, name) if (result) { - const oldPayload = readPayload(workspaceId, result.oldKey) + const oldPayload = readPayload(scope, result.oldKey) if (oldPayload) { - const written = writePayload(workspaceId, result.newKey, { + const written = writePayload(scope, result.newKey, { data: oldPayload.data, updatedAt: oldPayload.updatedAt }) if (!written) return if (!persistIndex(result.index)) { - deletePayload(workspaceId, result.newKey) + deletePayload(scope, result.newKey) return } - deletePayload(workspaceId, result.oldKey) + deletePayload(scope, result.oldKey) } } } @@ -301,14 +300,14 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { isTemporary: boolean updatedAt: number } | null { - const workspaceId = getStorageScope() - if (!workspaceId) return null + const scope = getStorageScope() + if (!scope) return null const index = loadIndex() const entry = getEntryByPath(index, path) if (!entry) return null const draftKey = hashPath(path) - const payload = readPayload(workspaceId, draftKey) + const payload = readPayload(scope, draftKey) if (!payload) { // Payload missing - clean up index removeDraft(path) @@ -416,9 +415,9 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Resets the store (clears in-memory cache for current workspace). */ function reset(): void { - const workspaceId = getStorageScope() - if (!workspaceId) return - delete indexCacheByWorkspace.value[workspaceId] + const scope = getStorageScope() + if (!scope) return + delete indexCacheByScope.value[scope] } return { From ef682d6de115f3819bd07d72c6c72306d0893bf8 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 00:27:36 -0700 Subject: [PATCH 31/52] docs: narrow identity-scoping guarantee in ADR 0031 Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3985409597 --- ...W-PERSISTENCE-0031-identity-scoped-draft-storage.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md index a8cda15a0e5..908b7637837 100644 --- a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -179,16 +179,18 @@ is a data loss for the common single-user case. ### Positive -- Two users on one browser never read or overwrite each other's drafts, even - when they share a workspace id. +- Once a scope has been migrated, drafts written under one identity are never + read or overwritten by another identity on the same browser, even when both + share a workspace id. Legacy workspace-scoped drafts are attributed to the + first identity that migrates them (see Negative consequences). - Logout removes only the departing user's data in the scope they were in; drafts in their other workspaces survive. - No write can commit while the owner is unknown or changing. ### Negative -- Existing workspace-keyed drafts are attributed to the first user who signs in - after the upgrade. +- Existing workspace-keyed drafts are attributed to the first identity that + migrates them after the upgrade. - Writes made while the gate is `deferred` are not queued; if the tab closes before the gate opens, changes made during the transition are lost. This is the same window that already existed for the transitioning state. From 1a9ca0bab8a0b41a4b023cc7d3d02ee6651912d8 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 00:47:34 -0700 Subject: [PATCH 32/52] test: use global testing Pinia for draft scope --- .../persistence/stores/workflowDraftStoreV2.scope.test.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts index b47c62da9b7..54879a750cc 100644 --- a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts +++ b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts @@ -1,5 +1,3 @@ -import { createTestingPinia } from '@pinia/testing' -import { setActivePinia } from 'pinia' import { beforeEach, describe, expect, it, vi } from 'vitest' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' @@ -33,7 +31,6 @@ describe('workflowDraftStoreV2 storage scope', () => { beforeEach(() => { localStorage.clear() sessionStorage.clear() - setActivePinia(createTestingPinia({ stubActions: false })) setStorageIdentity(null) }) From f38db4dff38e8508ba624452e3e91a9f1acb05cb Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 01:23:39 -0700 Subject: [PATCH 33/52] fix: make legacy draft migration claim exclusive and preserve newer source generations Verify claim ownership with a per-call nonce after writing and before committing or cleaning up, and skip source cleanup when a newer bare workspace generation appeared mid-migration. Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3987079375 --- .../migration/migrateWorkspaceToScope.test.ts | 67 +++++++++++++++++ .../migration/migrateWorkspaceToScope.ts | 74 +++++++++++++++---- 2 files changed, 127 insertions(+), 14 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index dc894744fd3..e1e91501259 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -7,6 +7,7 @@ import { migrateWorkspaceToScope } from './migrateWorkspaceToScope' const sourceWorkspaceId = 'workspace-a' const destinationScope = 'user-a:workspace-a' +const competingScope = 'user-b:workspace-a' const draftPath = 'workflows/one.json' const draftKey = hashPath(draftPath) @@ -359,6 +360,72 @@ describe('migrateWorkspaceToScope', () => { ) }) + it('allows only the winning identity to commit when another tab overwrites the claim', () => { + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const destinationPayloadKey = StorageKeys.draftPayload( + draftPath, + destinationScope + ) + const realSetItem = localStorage.setItem.bind(localStorage) + let replacedClaim = false + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === destinationPayloadKey && !replacedClaim) { + replacedClaim = true + realSetItem( + claimKey, + JSON.stringify({ + scope: competingScope, + sourceUpdatedAt: 10, + nonce: 'competing-tab' + }) + ) + migrateWorkspaceToScope(sourceWorkspaceId, competingScope) + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(competingScope))).toEqual( + buildIndex() + ) + expect(readJson(StorageKeys.draftIndex(destinationScope))).toBe(null) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) + }) + + it('preserves a newer source generation written while committing the destination index', () => { + seedSourceWorkspace() + const sourceIndexKey = StorageKeys.draftIndex(sourceWorkspaceId) + const destinationIndexKey = StorageKeys.draftIndex(destinationScope) + const newerIndex = { ...buildIndex(), updatedAt: 20 } + const realSetItem = localStorage.setItem.bind(localStorage) + const setItemSpy = vi + .spyOn(localStorage, 'setItem') + .mockImplementation((key: string, value: string) => { + realSetItem(key, value) + if (key === destinationIndexKey) { + realSetItem(sourceIndexKey, JSON.stringify(newerIndex)) + } + }) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(sourceIndexKey)).toEqual(newerIndex) + expect(readJson(destinationIndexKey)).toEqual(buildIndex()) + expect( + readJson(StorageKeys.draftPayload(draftPath, sourceWorkspaceId)) + ).toEqual({ data: '{"nodes":[]}', updatedAt: 10 }) + + setItemSpy.mockRestore() + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(sourceIndexKey)).toBe(null) + expect(readJson(destinationIndexKey)).toEqual(newerIndex) + }) + it('preserves a newer workspace when the committed destination claim is stale', () => { seedSourceWorkspace() localStorage.setItem( diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index 9d75f504c25..8e8183e8549 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -14,6 +14,7 @@ import { StorageKeys } from '../base/storageKeys' type MigrationClaim = { scope: string sourceUpdatedAt: number + nonce?: string } const restorePointerKeys = [ @@ -42,38 +43,83 @@ export function migrateWorkspaceToScope( if (existingClaim && existingClaim.scope !== scope) return const draftKeys = getPayloadKeys(workspaceId) + const destinationIndex = readIndex(scope) - if (readIndex(scope)) { - const ownsDestination = + if (destinationIndex) { + const canFinishCleanup = existingClaim !== null && index.updatedAt <= existingClaim.sourceUpdatedAt - if (!ownsDestination) return - removeScopeArtifacts(workspaceId, draftKeys, restorePointerKeys) - removeStorageKeys(localStorage, [claimKey]) - return + const hasNewerSource = index.updatedAt > destinationIndex.updatedAt + if (!canFinishCleanup && !hasNewerSource) return } - const claim: MigrationClaim = { scope, sourceUpdatedAt: index.updatedAt } + const claim: MigrationClaim = { + scope, + sourceUpdatedAt: index.updatedAt, + nonce: crypto.randomUUID() + } if (!writeStorage(localStorage, claimKey, JSON.stringify(claim))) return - const committedClaim = readLocalPointer(claimKey, isValidClaim) - if (committedClaim?.scope !== scope) return + if (!ownsClaim(claimKey, claim)) return + + if ( + destinationIndex && + existingClaim !== null && + index.updatedAt <= existingClaim.sourceUpdatedAt + ) { + cleanupSourceIfCurrent(workspaceId, draftKeys, claimKey, claim) + return + } const missingPointerKeys = restorePointerKeys.filter( (keyFor) => localStorage.getItem(keyFor(scope)) === null ) - const copied = + const artifactsCopied = draftKeys.every((draftKey) => copyPayload(draftKey, workspaceId, scope)) && missingPointerKeys.every((keyFor) => copyRestorePointer(keyFor, workspaceId, scope) - ) && - writeIndex(scope, index) + ) + const copied = + artifactsCopied && ownsClaim(claimKey, claim) && writeIndex(scope, index) if (copied) { - removeScopeArtifacts(workspaceId, draftKeys, restorePointerKeys) + cleanupSourceIfCurrent(workspaceId, draftKeys, claimKey, claim) } else { removeScopeArtifacts(scope, draftKeys, missingPointerKeys) + releaseClaimIfOwned(claimKey, claim) + } +} + +function ownsClaim(claimKey: string, claim: MigrationClaim): boolean { + const committedClaim = readLocalPointer(claimKey, isValidClaim) + return ( + committedClaim?.scope === claim.scope && + committedClaim.sourceUpdatedAt === claim.sourceUpdatedAt && + committedClaim.nonce === claim.nonce + ) +} + +function releaseClaimIfOwned(claimKey: string, claim: MigrationClaim): void { + if (ownsClaim(claimKey, claim)) { + removeStorageKeys(localStorage, [claimKey]) + } +} + +function cleanupSourceIfCurrent( + workspaceId: string, + draftKeys: string[], + claimKey: string, + claim: MigrationClaim +): void { + if (!ownsClaim(claimKey, claim)) return + const currentSource = readIndex(workspaceId) + if ( + currentSource && + currentSource.updatedAt <= claim.sourceUpdatedAt && + ownsClaim(claimKey, claim) + ) { + removeScopeArtifacts(workspaceId, draftKeys, restorePointerKeys) } - removeStorageKeys(localStorage, [claimKey]) + releaseClaimIfOwned(claimKey, claim) } function removeScopeArtifacts( From 3a482e009e5f4cea37e6a691efba1b14c30f6642 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 02:34:29 -0700 Subject: [PATCH 34/52] fix: compensate lost migration publication Revalidate claim ownership after publishing the destination index and restore the complete pre-migration destination snapshot when ownership was lost. Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3987678840 --- .../migration/migrateWorkspaceToScope.test.ts | 33 +++++++++++++++++++ .../migration/migrateWorkspaceToScope.ts | 32 ++++++++++++++++-- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index e1e91501259..26281b75544 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -396,6 +396,39 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) }) + it('rolls back a destination published after another identity takes the claim', () => { + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const destinationIndexKey = StorageKeys.draftIndex(destinationScope) + const realSetItem = localStorage.setItem.bind(localStorage) + let claimTaken = false + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + if (key === destinationIndexKey && !claimTaken) { + claimTaken = true + realSetItem( + claimKey, + JSON.stringify({ + scope: competingScope, + sourceUpdatedAt: 10, + nonce: 'competing-tab' + }) + ) + migrateWorkspaceToScope(sourceWorkspaceId, competingScope) + } + realSetItem(key, value) + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(competingScope))).toEqual( + buildIndex() + ) + expect(readJson(destinationIndexKey)).toBe(null) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) + }) + it('preserves a newer source generation written while committing the destination index', () => { seedSourceWorkspace() const sourceIndexKey = StorageKeys.draftIndex(sourceWorkspaceId) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index 8e8183e8549..f0c3f27b00e 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -72,19 +72,25 @@ export function migrateWorkspaceToScope( const missingPointerKeys = restorePointerKeys.filter( (keyFor) => localStorage.getItem(keyFor(scope)) === null ) + const destinationSnapshot = snapshotScopeArtifacts( + scope, + draftKeys, + missingPointerKeys + ) const artifactsCopied = draftKeys.every((draftKey) => copyPayload(draftKey, workspaceId, scope)) && missingPointerKeys.every((keyFor) => copyRestorePointer(keyFor, workspaceId, scope) ) - const copied = + const published = artifactsCopied && ownsClaim(claimKey, claim) && writeIndex(scope, index) + const copied = published && ownsClaim(claimKey, claim) if (copied) { cleanupSourceIfCurrent(workspaceId, draftKeys, claimKey, claim) } else { - removeScopeArtifacts(scope, draftKeys, missingPointerKeys) + restoreStorageSnapshot(destinationSnapshot) releaseClaimIfOwned(claimKey, claim) } } @@ -134,6 +140,28 @@ function removeScopeArtifacts( ]) } +function snapshotScopeArtifacts( + scope: string, + draftKeys: string[], + pointerKeys: ((scope: string) => string)[] +): Map { + const keys = [ + StorageKeys.draftIndex(scope), + ...draftKeys.map( + (draftKey) => `${StorageKeys.prefixes.draftPayload}${scope}:${draftKey}` + ), + ...pointerKeys.map((keyFor) => keyFor(scope)) + ] + return new Map(keys.map((key) => [key, localStorage.getItem(key)])) +} + +function restoreStorageSnapshot(snapshot: Map): void { + for (const [key, value] of snapshot) { + if (value === null) localStorage.removeItem(key) + else localStorage.setItem(key, value) + } +} + function copyPayload( draftKey: string, workspaceId: string, From c6706f5327a1d4f07c14be0f880d5a49391592a3 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 02:37:08 -0700 Subject: [PATCH 35/52] fix: preserve same-scope migration winner Skip destination compensation when a peer claim with the same scope has replaced this migration's nonce. Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3987678854 --- .../workflow/persistence/base/storageKeys.ts | 7 +++- .../migration/migrateWorkspaceToScope.test.ts | 39 +++++++++++++++++++ .../migration/migrateWorkspaceToScope.ts | 12 +++++- 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/platform/workflow/persistence/base/storageKeys.ts b/src/platform/workflow/persistence/base/storageKeys.ts index f0dea7adfbe..011c0a37e1b 100644 --- a/src/platform/workflow/persistence/base/storageKeys.ts +++ b/src/platform/workflow/persistence/base/storageKeys.ts @@ -115,6 +115,10 @@ export const StorageKeys = { return `Comfy.Workflow.MigrationClaim:${workspaceId}` }, + migrationCompletion(workspaceId: string): string { + return `Comfy.Workflow.MigrationCompletion:${workspaceId}` + }, + /** * Prefix patterns for cleanup operations. */ @@ -125,6 +129,7 @@ export const StorageKeys = { openPaths: 'Comfy.Workflow.OpenPaths:', lastActivePath: 'Comfy.Workflow.LastActivePath:', lastOpenPaths: 'Comfy.Workflow.LastOpenPaths:', - migrationClaim: 'Comfy.Workflow.MigrationClaim:' + migrationClaim: 'Comfy.Workflow.MigrationClaim:', + migrationCompletion: 'Comfy.Workflow.MigrationCompletion:' } } as const diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 26281b75544..9a7de4e8e51 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -429,6 +429,45 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) }) + it('keeps artifacts committed by a same-scope migration winner', () => { + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const destinationPayloadKey = StorageKeys.draftPayload( + draftPath, + destinationScope + ) + const realSetItem = localStorage.setItem.bind(localStorage) + let claimTaken = false + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === destinationPayloadKey && !claimTaken) { + claimTaken = true + realSetItem( + claimKey, + JSON.stringify({ + scope: destinationScope, + sourceUpdatedAt: 10, + nonce: 'same-scope-tab' + }) + ) + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + buildIndex() + ) + expect(readJson(destinationPayloadKey)).toEqual({ + data: '{"nodes":[]}', + updatedAt: 10 + }) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) + }) + it('preserves a newer source generation written while committing the destination index', () => { seedSourceWorkspace() const sourceIndexKey = StorageKeys.draftIndex(sourceWorkspaceId) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index f0c3f27b00e..42dd005fe71 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -39,6 +39,7 @@ export function migrateWorkspaceToScope( if (!index) return const claimKey = StorageKeys.migrationClaim(workspaceId) + const completionKey = StorageKeys.migrationCompletion(workspaceId) const existingClaim = readLocalPointer(claimKey, isValidClaim) if (existingClaim && existingClaim.scope !== scope) return @@ -88,9 +89,18 @@ export function migrateWorkspaceToScope( const copied = published && ownsClaim(claimKey, claim) if (copied) { + writeStorage(localStorage, completionKey, JSON.stringify(claim)) cleanupSourceIfCurrent(workspaceId, draftKeys, claimKey, claim) } else { - restoreStorageSnapshot(destinationSnapshot) + const currentClaim = readLocalPointer(claimKey, isValidClaim) + const completion = readLocalPointer(completionKey, isValidClaim) + const sameScopePeer = + currentClaim?.scope === scope + ? currentClaim.nonce !== claim.nonce + : completion?.scope === scope && completion.nonce !== claim.nonce + if (!sameScopePeer) { + restoreStorageSnapshot(destinationSnapshot) + } releaseClaimIfOwned(claimKey, claim) } } From b329e4a4058d17d7283896f5a6bd48d4896cb95c Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 02:41:08 -0700 Subject: [PATCH 36/52] fix: preserve concurrently saved source payloads Snapshot copied source payload bytes and delete only unchanged payload generations before removing the migrated source index. Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3987678861 --- .../migration/migrateWorkspaceToScope.test.ts | 26 +++++++ .../migration/migrateWorkspaceToScope.ts | 68 ++++++++++++------- 2 files changed, 71 insertions(+), 23 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 9a7de4e8e51..67176825b3c 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -498,6 +498,32 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(destinationIndexKey)).toEqual(newerIndex) }) + it('preserves a source payload written before its newer index', () => { + seedSourceWorkspace() + const sourceIndexKey = StorageKeys.draftIndex(sourceWorkspaceId) + const sourcePayloadKey = StorageKeys.draftPayload( + draftPath, + sourceWorkspaceId + ) + const newerPayload = { data: '{"nodes":[1]}', updatedAt: 20 } + const newerIndex = { ...buildIndex(), updatedAt: 20 } + const realGetItem = localStorage.getItem.bind(localStorage) + const realSetItem = localStorage.setItem.bind(localStorage) + let sourceIndexReads = 0 + vi.spyOn(localStorage, 'getItem').mockImplementation((key: string) => { + if (key === sourceIndexKey && ++sourceIndexReads === 2) { + realSetItem(sourcePayloadKey, JSON.stringify(newerPayload)) + } + return realGetItem(key) + }) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + realSetItem(sourceIndexKey, JSON.stringify(newerIndex)) + + expect(readJson(sourcePayloadKey)).toEqual(newerPayload) + expect(readJson(sourceIndexKey)).toEqual(newerIndex) + }) + it('preserves a newer workspace when the committed destination claim is stale', () => { seedSourceWorkspace() localStorage.setItem( diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index 42dd005fe71..086f85eb3ec 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -1,5 +1,4 @@ import { - deletePayloads, getPayloadKeys, readIndex, readLocalPointer, @@ -44,6 +43,7 @@ export function migrateWorkspaceToScope( if (existingClaim && existingClaim.scope !== scope) return const draftKeys = getPayloadKeys(workspaceId) + const sourcePayloads = snapshotPayloads(workspaceId, draftKeys) const destinationIndex = readIndex(scope) if (destinationIndex) { @@ -66,7 +66,7 @@ export function migrateWorkspaceToScope( existingClaim !== null && index.updatedAt <= existingClaim.sourceUpdatedAt ) { - cleanupSourceIfCurrent(workspaceId, draftKeys, claimKey, claim) + cleanupSourceIfCurrent(workspaceId, sourcePayloads, claimKey, claim) return } @@ -80,7 +80,14 @@ export function migrateWorkspaceToScope( ) const artifactsCopied = - draftKeys.every((draftKey) => copyPayload(draftKey, workspaceId, scope)) && + draftKeys.every((draftKey) => + copyPayload( + draftKey, + workspaceId, + scope, + sourcePayloads.get(draftKey) ?? null + ) + ) && missingPointerKeys.every((keyFor) => copyRestorePointer(keyFor, workspaceId, scope) ) @@ -90,7 +97,7 @@ export function migrateWorkspaceToScope( if (copied) { writeStorage(localStorage, completionKey, JSON.stringify(claim)) - cleanupSourceIfCurrent(workspaceId, draftKeys, claimKey, claim) + cleanupSourceIfCurrent(workspaceId, sourcePayloads, claimKey, claim) } else { const currentClaim = readLocalPointer(claimKey, isValidClaim) const completion = readLocalPointer(completionKey, isValidClaim) @@ -122,7 +129,7 @@ function releaseClaimIfOwned(claimKey: string, claim: MigrationClaim): void { function cleanupSourceIfCurrent( workspaceId: string, - draftKeys: string[], + sourcePayloads: Map, claimKey: string, claim: MigrationClaim ): void { @@ -133,23 +140,18 @@ function cleanupSourceIfCurrent( currentSource.updatedAt <= claim.sourceUpdatedAt && ownsClaim(claimKey, claim) ) { - removeScopeArtifacts(workspaceId, draftKeys, restorePointerKeys) + for (const [draftKey, sourceRaw] of sourcePayloads) { + const key = payloadKey(workspaceId, draftKey) + if (localStorage.getItem(key) === sourceRaw) localStorage.removeItem(key) + } + removeStorageKeys(localStorage, [ + ...restorePointerKeys.map((keyFor) => keyFor(workspaceId)), + StorageKeys.draftIndex(workspaceId) + ]) } releaseClaimIfOwned(claimKey, claim) } -function removeScopeArtifacts( - scope: string, - draftKeys: string[], - pointerKeys: ((scope: string) => string)[] -): void { - deletePayloads(scope, draftKeys) - removeStorageKeys(localStorage, [ - StorageKeys.draftIndex(scope), - ...pointerKeys.map((keyFor) => keyFor(scope)) - ]) -} - function snapshotScopeArtifacts( scope: string, draftKeys: string[], @@ -157,14 +159,28 @@ function snapshotScopeArtifacts( ): Map { const keys = [ StorageKeys.draftIndex(scope), - ...draftKeys.map( - (draftKey) => `${StorageKeys.prefixes.draftPayload}${scope}:${draftKey}` - ), + ...draftKeys.map((draftKey) => payloadKey(scope, draftKey)), ...pointerKeys.map((keyFor) => keyFor(scope)) ] return new Map(keys.map((key) => [key, localStorage.getItem(key)])) } +function snapshotPayloads( + scope: string, + draftKeys: string[] +): Map { + return new Map( + draftKeys.map((draftKey) => [ + draftKey, + localStorage.getItem(payloadKey(scope, draftKey)) + ]) + ) +} + +function payloadKey(scope: string, draftKey: string): string { + return `${StorageKeys.prefixes.draftPayload}${scope}:${draftKey}` +} + function restoreStorageSnapshot(snapshot: Map): void { for (const [key, value] of snapshot) { if (value === null) localStorage.removeItem(key) @@ -175,10 +191,16 @@ function restoreStorageSnapshot(snapshot: Map): void { function copyPayload( draftKey: string, workspaceId: string, - scope: string + scope: string, + sourceRaw: string | null ): boolean { + if (sourceRaw === null) return false const payload = readPayload(workspaceId, draftKey) - if (!payload) return false + if ( + !payload || + localStorage.getItem(payloadKey(workspaceId, draftKey)) !== sourceRaw + ) + return false return writePayload(scope, draftKey, payload) } From 5322140cfd9cb5d81a3f5e832f6ddcb06d7bab48 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 06:34:07 -0700 Subject: [PATCH 37/52] fix: preserve concurrent scoped draft writes Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3988321580 --- .../migration/migrateWorkspaceToScope.test.ts | 37 +++++++++++++++ .../migration/migrateWorkspaceToScope.ts | 47 ++++++++++++++++++- 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 67176825b3c..ca96a3d1138 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -429,6 +429,43 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) }) + it('preserves a newer destination generation when another identity takes the claim', () => { + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const destinationPayloadKey = StorageKeys.draftPayload( + draftPath, + destinationScope + ) + const destinationIndexKey = StorageKeys.draftIndex(destinationScope) + const newerPayload = { data: '{"nodes":[20]}', updatedAt: 20 } + const newerIndex = { ...buildIndex(), updatedAt: 20 } + const realSetItem = localStorage.setItem.bind(localStorage) + let claimTaken = false + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === destinationPayloadKey && !claimTaken) { + claimTaken = true + realSetItem(destinationPayloadKey, JSON.stringify(newerPayload)) + realSetItem(destinationIndexKey, JSON.stringify(newerIndex)) + realSetItem( + claimKey, + JSON.stringify({ + scope: competingScope, + sourceUpdatedAt: 10, + nonce: 'competing-tab' + }) + ) + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(destinationPayloadKey)).toEqual(newerPayload) + expect(readJson(destinationIndexKey)).toEqual(newerIndex) + }) + it('keeps artifacts committed by a same-scope migration winner', () => { seedSourceWorkspace() const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index 086f85eb3ec..5b2e584bdcf 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -78,6 +78,13 @@ export function migrateWorkspaceToScope( draftKeys, missingPointerKeys ) + const migrationArtifacts = snapshotMigrationArtifacts( + workspaceId, + scope, + index, + sourcePayloads, + missingPointerKeys + ) const artifactsCopied = draftKeys.every((draftKey) => @@ -106,7 +113,7 @@ export function migrateWorkspaceToScope( ? currentClaim.nonce !== claim.nonce : completion?.scope === scope && completion.nonce !== claim.nonce if (!sameScopePeer) { - restoreStorageSnapshot(destinationSnapshot) + restoreStorageSnapshot(destinationSnapshot, migrationArtifacts) } releaseClaimIfOwned(claimKey, claim) } @@ -177,12 +184,48 @@ function snapshotPayloads( ) } +function snapshotMigrationArtifacts( + workspaceId: string, + scope: string, + index: object, + sourcePayloads: Map, + pointerKeys: ((scope: string) => string)[] +): Map { + const artifacts = new Map([ + [StorageKeys.draftIndex(scope), JSON.stringify(index)] + ]) + for (const [draftKey, raw] of sourcePayloads) { + artifacts.set(payloadKey(scope, draftKey), raw) + } + for (const keyFor of pointerKeys) { + const raw = localStorage.getItem(keyFor(workspaceId)) + if (raw === null) continue + try { + const pointer: unknown = JSON.parse(raw) + if (typeof pointer === 'object' && pointer !== null) { + artifacts.set( + keyFor(scope), + JSON.stringify({ ...pointer, workspaceId: scope }) + ) + } + } catch { + continue + } + } + return artifacts +} + function payloadKey(scope: string, draftKey: string): string { return `${StorageKeys.prefixes.draftPayload}${scope}:${draftKey}` } -function restoreStorageSnapshot(snapshot: Map): void { +function restoreStorageSnapshot( + snapshot: Map, + migrationArtifacts: Map +): void { for (const [key, value] of snapshot) { + const current = localStorage.getItem(key) + if (current !== value && current !== migrationArtifacts.get(key)) continue if (value === null) localStorage.removeItem(key) else localStorage.setItem(key, value) } From c8e95418db9b4fea5cde711d7610281f1a8d7f0d Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 06:35:27 -0700 Subject: [PATCH 38/52] fix: bind migration completion to source generation Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3988321582 --- ...ENCE-0031-identity-scoped-draft-storage.md | 5 ++- .../migration/migrateWorkspaceToScope.test.ts | 41 +++++++++++++++++++ .../migration/migrateWorkspaceToScope.ts | 29 +++++++++++-- 3 files changed, 71 insertions(+), 4 deletions(-) diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md index 908b7637837..42e814eeb58 100644 --- a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -123,7 +123,10 @@ payloads, index and restore pointers are removed. If the source index still exists but the destination index is already present, an earlier run committed and was interrupted before its source cleanup; the migration only finishes that cleanup and does not copy again, so the committed destination is never -overwritten by stale source data. +overwritten by stale source data. A short-lived completion record identifies +the source generation and lets a losing same-scope tab distinguish the winning +copy from its own artifacts without allowing an older migration to suppress +rollback. The first user to sign in on a browser therefore claims any pre-existing workspace-keyed drafts. This is accepted: before this change those drafts were diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index ca96a3d1138..ae624d04ee8 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -466,6 +466,47 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(destinationIndexKey)).toEqual(newerIndex) }) + it('rolls back partial copies when same-scope completion belongs to an older source generation', () => { + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const completionKey = StorageKeys.migrationCompletion(sourceWorkspaceId) + const destinationPayloadKey = StorageKeys.draftPayload( + draftPath, + destinationScope + ) + localStorage.setItem( + completionKey, + JSON.stringify({ + scope: destinationScope, + sourceUpdatedAt: 5, + nonce: 'old-migration', + completedAt: Date.now() + }) + ) + const realSetItem = localStorage.setItem.bind(localStorage) + let claimTaken = false + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === destinationPayloadKey && !claimTaken) { + claimTaken = true + realSetItem( + claimKey, + JSON.stringify({ + scope: competingScope, + sourceUpdatedAt: 10, + nonce: 'competing-tab' + }) + ) + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(destinationPayloadKey)).toBe(null) + }) + it('keeps artifacts committed by a same-scope migration winner', () => { seedSourceWorkspace() const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index 5b2e584bdcf..c6bb4b20809 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -16,6 +16,13 @@ type MigrationClaim = { nonce?: string } +type MigrationCompletion = MigrationClaim & { + completedAt: number + nonce: string +} + +const migrationCompletionLifetime = 60_000 + const restorePointerKeys = [ StorageKeys.lastActivePath, StorageKeys.lastOpenPaths @@ -30,6 +37,16 @@ function isValidClaim(value: unknown): value is MigrationClaim { ) } +function isCurrentCompletion(value: unknown): value is MigrationCompletion { + if (!isValidClaim(value)) return false + const candidate = value as Record + return ( + typeof candidate.nonce === 'string' && + typeof candidate.completedAt === 'number' && + Date.now() - candidate.completedAt <= migrationCompletionLifetime + ) +} + export function migrateWorkspaceToScope( workspaceId: string, scope: string @@ -103,15 +120,21 @@ export function migrateWorkspaceToScope( const copied = published && ownsClaim(claimKey, claim) if (copied) { - writeStorage(localStorage, completionKey, JSON.stringify(claim)) + writeStorage( + localStorage, + completionKey, + JSON.stringify({ ...claim, completedAt: Date.now() }) + ) cleanupSourceIfCurrent(workspaceId, sourcePayloads, claimKey, claim) } else { const currentClaim = readLocalPointer(claimKey, isValidClaim) - const completion = readLocalPointer(completionKey, isValidClaim) + const completion = readLocalPointer(completionKey, isCurrentCompletion) const sameScopePeer = currentClaim?.scope === scope ? currentClaim.nonce !== claim.nonce - : completion?.scope === scope && completion.nonce !== claim.nonce + : completion?.scope === scope && + completion.sourceUpdatedAt === claim.sourceUpdatedAt && + completion.nonce !== claim.nonce if (!sameScopePeer) { restoreStorageSnapshot(destinationSnapshot, migrationArtifacts) } From af589db305ea0f2a61aa29d23f8f8c3ce3b78aad Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 06:37:16 -0700 Subject: [PATCH 39/52] fix: compare source artifacts before cleanup Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3988321585 --- .../migration/migrateWorkspaceToScope.test.ts | 39 +++++++++++++++++++ .../migration/migrateWorkspaceToScope.ts | 33 +++++++++++++--- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index ae624d04ee8..8afc8c3ccb9 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -602,6 +602,45 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(sourceIndexKey)).toEqual(newerIndex) }) + it('preserves a newer source index committed after its payload during cleanup', () => { + seedSourceWorkspace() + const sourceIndexKey = StorageKeys.draftIndex(sourceWorkspaceId) + const sourcePayloadKey = StorageKeys.draftPayload( + draftPath, + sourceWorkspaceId + ) + const newerPayload = { data: '{"nodes":[20]}', updatedAt: 20 } + const newerIndex = { ...buildIndex(), updatedAt: 20 } + const realGetItem = localStorage.getItem.bind(localStorage) + const realSetItem = localStorage.setItem.bind(localStorage) + const destinationIndexKey = StorageKeys.draftIndex(destinationScope) + let destinationPublished = false + let newerIndexCommitted = false + vi.spyOn(localStorage, 'getItem').mockImplementation((key: string) => { + if ( + key === sourcePayloadKey && + destinationPublished && + !newerIndexCommitted + ) { + realSetItem(sourcePayloadKey, JSON.stringify(newerPayload)) + realSetItem(sourceIndexKey, JSON.stringify(newerIndex)) + newerIndexCommitted = true + } + return realGetItem(key) + }) + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === destinationIndexKey) destinationPublished = true + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(sourcePayloadKey)).toEqual(newerPayload) + expect(readJson(sourceIndexKey)).toEqual(newerIndex) + }) + it('preserves a newer workspace when the committed destination claim is stale', () => { seedSourceWorkspace() localStorage.setItem( diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index c6bb4b20809..f6d7d57f9c0 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -61,6 +61,7 @@ export function migrateWorkspaceToScope( const draftKeys = getPayloadKeys(workspaceId) const sourcePayloads = snapshotPayloads(workspaceId, draftKeys) + const sourceArtifacts = snapshotSourceArtifacts(workspaceId) const destinationIndex = readIndex(scope) if (destinationIndex) { @@ -83,7 +84,13 @@ export function migrateWorkspaceToScope( existingClaim !== null && index.updatedAt <= existingClaim.sourceUpdatedAt ) { - cleanupSourceIfCurrent(workspaceId, sourcePayloads, claimKey, claim) + cleanupSourceIfCurrent( + workspaceId, + sourcePayloads, + sourceArtifacts, + claimKey, + claim + ) return } @@ -125,7 +132,13 @@ export function migrateWorkspaceToScope( completionKey, JSON.stringify({ ...claim, completedAt: Date.now() }) ) - cleanupSourceIfCurrent(workspaceId, sourcePayloads, claimKey, claim) + cleanupSourceIfCurrent( + workspaceId, + sourcePayloads, + sourceArtifacts, + claimKey, + claim + ) } else { const currentClaim = readLocalPointer(claimKey, isValidClaim) const completion = readLocalPointer(completionKey, isCurrentCompletion) @@ -160,6 +173,7 @@ function releaseClaimIfOwned(claimKey: string, claim: MigrationClaim): void { function cleanupSourceIfCurrent( workspaceId: string, sourcePayloads: Map, + sourceArtifacts: Map, claimKey: string, claim: MigrationClaim ): void { @@ -174,10 +188,9 @@ function cleanupSourceIfCurrent( const key = payloadKey(workspaceId, draftKey) if (localStorage.getItem(key) === sourceRaw) localStorage.removeItem(key) } - removeStorageKeys(localStorage, [ - ...restorePointerKeys.map((keyFor) => keyFor(workspaceId)), - StorageKeys.draftIndex(workspaceId) - ]) + for (const [key, sourceRaw] of sourceArtifacts) { + if (localStorage.getItem(key) === sourceRaw) localStorage.removeItem(key) + } } releaseClaimIfOwned(claimKey, claim) } @@ -207,6 +220,14 @@ function snapshotPayloads( ) } +function snapshotSourceArtifacts(scope: string): Map { + const keys = [ + ...restorePointerKeys.map((keyFor) => keyFor(scope)), + StorageKeys.draftIndex(scope) + ] + return new Map(keys.map((key) => [key, localStorage.getItem(key)])) +} + function snapshotMigrationArtifacts( workspaceId: string, scope: string, From a1338da6a9feb6e10b4de1ed81d2e0611553fcb4 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 10:33:11 -0700 Subject: [PATCH 40/52] fix(persistence): keep source when migration completion write fails Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3990328830 --- .../migration/migrateWorkspaceToScope.test.ts | 41 +++++++++++++++++++ .../migration/migrateWorkspaceToScope.ts | 3 +- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 8afc8c3ccb9..598e312079e 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -546,6 +546,47 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) }) + it('keeps both copies when a winner cannot record completion', () => { + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const completionKey = StorageKeys.migrationCompletion(sourceWorkspaceId) + const destinationPayloadKey = StorageKeys.draftPayload( + draftPath, + destinationScope + ) + const realSetItem = localStorage.setItem.bind(localStorage) + let claimTaken = false + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + if (key === completionKey) { + throw new DOMException('Quota exceeded', 'QuotaExceededError') + } + realSetItem(key, value) + if (key === destinationPayloadKey && !claimTaken) { + claimTaken = true + realSetItem( + claimKey, + JSON.stringify({ + scope: destinationScope, + sourceUpdatedAt: 10, + nonce: 'same-scope-tab' + }) + ) + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + buildIndex() + ) + }) + it('preserves a newer source generation written while committing the destination index', () => { seedSourceWorkspace() const sourceIndexKey = StorageKeys.draftIndex(sourceWorkspaceId) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index f6d7d57f9c0..ca4830384b3 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -127,11 +127,12 @@ export function migrateWorkspaceToScope( const copied = published && ownsClaim(claimKey, claim) if (copied) { - writeStorage( + const completionRecorded = writeStorage( localStorage, completionKey, JSON.stringify({ ...claim, completedAt: Date.now() }) ) + if (!completionRecorded) return cleanupSourceIfCurrent( workspaceId, sourcePayloads, From 9efc0b89db361f6bb4c6620bb2066795bc894d5d Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 10:34:11 -0700 Subject: [PATCH 41/52] fix(persistence): bind completion validity to source generation Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3990328841 --- ...ENCE-0031-identity-scoped-draft-storage.md | 7 ++-- .../migration/migrateWorkspaceToScope.test.ts | 41 ++++++++++++++++++- .../migration/migrateWorkspaceToScope.ts | 19 +++------ 3 files changed, 47 insertions(+), 20 deletions(-) diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md index 42e814eeb58..69cab192788 100644 --- a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -123,10 +123,9 @@ payloads, index and restore pointers are removed. If the source index still exists but the destination index is already present, an earlier run committed and was interrupted before its source cleanup; the migration only finishes that cleanup and does not copy again, so the committed destination is never -overwritten by stale source data. A short-lived completion record identifies -the source generation and lets a losing same-scope tab distinguish the winning -copy from its own artifacts without allowing an older migration to suppress -rollback. +overwritten by stale source data. A completion record identifies the source +generation and lets a losing same-scope tab distinguish the winning copy from +its own artifacts without allowing an older migration to suppress rollback. The first user to sign in on a browser therefore claims any pre-existing workspace-keyed drafts. This is accepted: before this change those drafts were diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 598e312079e..49ffef5b2cb 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -479,8 +479,7 @@ describe('migrateWorkspaceToScope', () => { JSON.stringify({ scope: destinationScope, sourceUpdatedAt: 5, - nonce: 'old-migration', - completedAt: Date.now() + nonce: 'old-migration' }) ) const realSetItem = localStorage.setItem.bind(localStorage) @@ -546,6 +545,44 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) }) + it('keeps artifacts committed by a delayed same-scope migration winner', () => { + vi.useFakeTimers() + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const completionKey = StorageKeys.migrationCompletion(sourceWorkspaceId) + const destinationPayloadKey = StorageKeys.draftPayload( + draftPath, + destinationScope + ) + const realSetItem = localStorage.setItem.bind(localStorage) + let claimTaken = false + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === destinationPayloadKey && !claimTaken) { + claimTaken = true + realSetItem( + claimKey, + JSON.stringify({ + scope: destinationScope, + sourceUpdatedAt: 10, + nonce: 'same-scope-tab' + }) + ) + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + } else if (key === completionKey) { + vi.advanceTimersByTime(60_001) + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + buildIndex() + ) + }) + it('keeps both copies when a winner cannot record completion', () => { seedSourceWorkspace() const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index ca4830384b3..0d8b40eae56 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -16,12 +16,7 @@ type MigrationClaim = { nonce?: string } -type MigrationCompletion = MigrationClaim & { - completedAt: number - nonce: string -} - -const migrationCompletionLifetime = 60_000 +type MigrationCompletion = MigrationClaim & { nonce: string } const restorePointerKeys = [ StorageKeys.lastActivePath, @@ -37,14 +32,10 @@ function isValidClaim(value: unknown): value is MigrationClaim { ) } -function isCurrentCompletion(value: unknown): value is MigrationCompletion { +function isValidCompletion(value: unknown): value is MigrationCompletion { if (!isValidClaim(value)) return false const candidate = value as Record - return ( - typeof candidate.nonce === 'string' && - typeof candidate.completedAt === 'number' && - Date.now() - candidate.completedAt <= migrationCompletionLifetime - ) + return typeof candidate.nonce === 'string' } export function migrateWorkspaceToScope( @@ -130,7 +121,7 @@ export function migrateWorkspaceToScope( const completionRecorded = writeStorage( localStorage, completionKey, - JSON.stringify({ ...claim, completedAt: Date.now() }) + JSON.stringify(claim) ) if (!completionRecorded) return cleanupSourceIfCurrent( @@ -142,7 +133,7 @@ export function migrateWorkspaceToScope( ) } else { const currentClaim = readLocalPointer(claimKey, isValidClaim) - const completion = readLocalPointer(completionKey, isCurrentCompletion) + const completion = readLocalPointer(completionKey, isValidCompletion) const sameScopePeer = currentClaim?.scope === scope ? currentClaim.nonce !== claim.nonce From 9349abf5161355348da63ef86973594164fa3a97 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 10:38:08 -0700 Subject: [PATCH 42/52] fix(persistence): avoid destructive migration cleanup races Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3990328850 --- ...ENCE-0031-identity-scoped-draft-storage.md | 8 +- .../migration/migrateWorkspaceToScope.test.ts | 78 +++++++++++++++++-- .../migration/migrateWorkspaceToScope.ts | 20 ++++- 3 files changed, 92 insertions(+), 14 deletions(-) diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md index 69cab192788..d9d3573d8bf 100644 --- a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -116,10 +116,10 @@ becoming `null` cannot know which scope to clear. `migrateWorkspaceToScope(workspaceId, scope)` copies the workspace-keyed index, payloads and restore pointers to the scoped keys the first time a scope is resolved that has no index. The destination index is written last so a partial -copy is never observed as complete. On failure every destination artifact the -copy produced (payloads, restore pointers, index) is removed and the source is -left intact, so a retry starts from the same state. On success the source -payloads, index and restore pointers are removed. If the source index still +copy is never observed as complete. On failure the source is left intact and +partial destination artifacts are ignored until a retry overwrites them. A +losing attempt never deletes destination data. On success the source payloads, +index and restore pointers are removed. If the source index still exists but the destination index is already present, an earlier run committed and was interrupted before its source cleanup; the migration only finishes that cleanup and does not copy again, so the committed destination is never diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 49ffef5b2cb..d0ea27b9640 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -226,7 +226,7 @@ describe('migrateWorkspaceToScope', () => { ) }) - it('removes every copied destination artifact when a restore pointer copy hits the quota', () => { + it('leaves harmless partial artifacts when a restore pointer copy hits the quota', () => { seedSourceWorkspace() const failingKey = StorageKeys.lastOpenPaths(destinationScope) const realSetItem = localStorage.setItem.bind(localStorage) @@ -248,10 +248,10 @@ describe('migrateWorkspaceToScope', () => { localStorage.getItem( StorageKeys.draftPayload(draftPath, destinationScope) ) - ).toBe(null) + ).not.toBe(null) expect( localStorage.getItem(StorageKeys.lastActivePath(destinationScope)) - ).toBe(null) + ).not.toBe(null) expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( buildIndex() ) @@ -329,7 +329,7 @@ describe('migrateWorkspaceToScope', () => { localStorage.getItem( StorageKeys.draftPayload(draftPath, destinationScope) ) - ).toBe(null) + ).not.toBe(null) expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( buildIndex() ) @@ -425,7 +425,7 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(StorageKeys.draftIndex(competingScope))).toEqual( buildIndex() ) - expect(readJson(destinationIndexKey)).toBe(null) + expect(readJson(destinationIndexKey)).toEqual(buildIndex()) expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) }) @@ -503,7 +503,10 @@ describe('migrateWorkspaceToScope', () => { migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) - expect(readJson(destinationPayloadKey)).toBe(null) + expect(readJson(destinationPayloadKey)).toEqual({ + data: '{"nodes":[]}', + updatedAt: 10 + }) }) it('keeps artifacts committed by a same-scope migration winner', () => { @@ -719,6 +722,69 @@ describe('migrateWorkspaceToScope', () => { expect(readJson(sourceIndexKey)).toEqual(newerIndex) }) + it('preserves a source index written between comparison and removal', () => { + seedSourceWorkspace() + const sourceIndexKey = StorageKeys.draftIndex(sourceWorkspaceId) + const newerIndex = { ...buildIndex(), updatedAt: 20 } + const realGetItem = localStorage.getItem.bind(localStorage) + const realSetItem = localStorage.setItem.bind(localStorage) + let destinationPublished = false + let comparedSourceIndex = false + vi.spyOn(localStorage, 'getItem').mockImplementation((key: string) => { + const value = realGetItem(key) + if ( + key === sourceIndexKey && + destinationPublished && + comparedSourceIndex + ) { + realSetItem(sourceIndexKey, JSON.stringify(newerIndex)) + } else if (key === sourceIndexKey && destinationPublished) { + comparedSourceIndex = true + } + return value + }) + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === StorageKeys.draftIndex(destinationScope)) { + destinationPublished = true + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(sourceIndexKey)).toEqual(newerIndex) + }) + + it('never removes a destination written while a migration loses its claim', () => { + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const destinationIndexKey = StorageKeys.draftIndex(destinationScope) + const newerIndex = { ...buildIndex(), updatedAt: 20 } + const realSetItem = localStorage.setItem.bind(localStorage) + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === destinationIndexKey) { + realSetItem(destinationIndexKey, JSON.stringify(newerIndex)) + realSetItem( + claimKey, + JSON.stringify({ + scope: competingScope, + sourceUpdatedAt: 10, + nonce: 'competing-tab' + }) + ) + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(destinationIndexKey)).toEqual(newerIndex) + }) + it('preserves a newer workspace when the committed destination claim is stale', () => { seedSourceWorkspace() localStorage.setItem( diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index 0d8b40eae56..f21eea71f08 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -178,15 +178,27 @@ function cleanupSourceIfCurrent( ) { for (const [draftKey, sourceRaw] of sourcePayloads) { const key = payloadKey(workspaceId, draftKey) - if (localStorage.getItem(key) === sourceRaw) localStorage.removeItem(key) + removeStorageValueIfStable(key, sourceRaw) } for (const [key, sourceRaw] of sourceArtifacts) { - if (localStorage.getItem(key) === sourceRaw) localStorage.removeItem(key) + removeStorageValueIfStable(key, sourceRaw) } } releaseClaimIfOwned(claimKey, claim) } +function removeStorageValueIfStable( + key: string, + expected: string | null +): void { + if ( + localStorage.getItem(key) === expected && + localStorage.getItem(key) === expected + ) { + localStorage.removeItem(key) + } +} + function snapshotScopeArtifacts( scope: string, draftKeys: string[], @@ -260,10 +272,10 @@ function restoreStorageSnapshot( migrationArtifacts: Map ): void { for (const [key, value] of snapshot) { + if (value === null) continue const current = localStorage.getItem(key) if (current !== value && current !== migrationArtifacts.get(key)) continue - if (value === null) localStorage.removeItem(key) - else localStorage.setItem(key, value) + localStorage.setItem(key, value) } } From 23f75c845f6a738fe74ef11a33d0433f58ecd281 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 12:49:28 -0700 Subject: [PATCH 43/52] test(persistence): ignore completion records from other scopes --- .../migration/migrateWorkspaceToScope.test.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index d0ea27b9640..a463a3ad938 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -509,6 +509,28 @@ describe('migrateWorkspaceToScope', () => { }) }) + it('ignores a valid completion record belonging to a different scope', () => { + seedSourceWorkspace() + localStorage.setItem( + StorageKeys.migrationCompletion(sourceWorkspaceId), + JSON.stringify({ + scope: competingScope, + sourceUpdatedAt: 10, + nonce: 'other-scope-migration' + }) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + buildIndex() + ) + expect( + readJson(StorageKeys.draftPayload(draftPath, destinationScope)) + ).toEqual({ data: '{"nodes":[]}', updatedAt: 10 }) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toBe(null) + }) + it('keeps artifacts committed by a same-scope migration winner', () => { seedSourceWorkspace() const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) From 68986e1b209371fffe973b421536f1129bc334f4 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 12:50:06 -0700 Subject: [PATCH 44/52] test(persistence): verify migration rerun idempotence --- .../migration/migrateWorkspaceToScope.test.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index a463a3ad938..4b366239109 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -171,6 +171,28 @@ describe('migrateWorkspaceToScope', () => { ).not.toBe(null) }) + it('performs no storage mutations when a completed migration runs again', () => { + seedSourceWorkspace() + const firstOutcome = migrateWorkspaceToScope( + sourceWorkspaceId, + destinationScope + ) + const setItemSpy = vi.spyOn(localStorage, 'setItem') + const removeItemSpy = vi.spyOn(localStorage, 'removeItem') + + const secondOutcome = migrateWorkspaceToScope( + sourceWorkspaceId, + destinationScope + ) + + expect(secondOutcome).toBe(firstOutcome) + expect(setItemSpy).not.toHaveBeenCalled() + expect(removeItemSpy).not.toHaveBeenCalled() + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + buildIndex() + ) + }) + it('does nothing when the workspace has no draft index', () => { localStorage.setItem( StorageKeys.draftPayload(draftPath, sourceWorkspaceId), From 26599fd52992ac0ac168786f77720cdc6800dfa6 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 12:50:50 -0700 Subject: [PATCH 45/52] test(persistence): honor write gate during migration --- .../migration/migrateWorkspaceToScope.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 4b366239109..6d47dfa52be 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { DraftIndexV2 } from '../base/draftTypes' import { hashPath } from '../base/hashUtil' +import { prepareWorkflowWorkspaceTransition } from '../base/storageIO' import { StorageKeys } from '../base/storageKeys' import { migrateWorkspaceToScope } from './migrateWorkspaceToScope' @@ -216,6 +217,24 @@ describe('migrateWorkspaceToScope', () => { ).not.toBe(null) }) + it('does not migrate drafts while workflow storage writes are deferred', () => { + seedSourceWorkspace() + const cancelTransition = prepareWorkflowWorkspaceTransition() + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect(localStorage.getItem(StorageKeys.draftIndex(destinationScope))).toBe( + null + ) + expect( + localStorage.getItem(StorageKeys.migrationClaim(sourceWorkspaceId)) + ).toBe(null) + cancelTransition() + }) + it('keeps the workspace copy and writes no scoped index when a payload copy hits the quota', () => { seedSourceWorkspace() const destinationPayloadKey = StorageKeys.draftPayload( From 8a22252290e8232434e6c44691cc029e26439462 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 12:51:58 -0700 Subject: [PATCH 46/52] test(persistence): cover migration rollback errors --- .../migration/migrateWorkspaceToScope.test.ts | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 6d47dfa52be..1913417b20c 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -302,6 +302,66 @@ describe('migrateWorkspaceToScope', () => { }) }) + it('rejects a malformed restore pointer without publishing the destination', () => { + seedSourceWorkspace() + localStorage.setItem( + StorageKeys.lastOpenPaths(sourceWorkspaceId), + 'not-json' + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(localStorage.getItem(StorageKeys.draftIndex(destinationScope))).toBe( + null + ) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect( + localStorage.getItem(StorageKeys.lastOpenPaths(destinationScope)) + ).toBe(null) + }) + + it('restores owned values without overwriting concurrent changes during rollback', () => { + seedSourceWorkspace() + const claimKey = StorageKeys.migrationClaim(sourceWorkspaceId) + const destinationIndexKey = StorageKeys.draftIndex(destinationScope) + const destinationPayloadKey = StorageKeys.draftPayload( + draftPath, + destinationScope + ) + const previousIndex = { ...buildIndex(), updatedAt: 5 } + const previousPayload = { data: '{"nodes":[5]}', updatedAt: 5 } + const concurrentPayload = { data: '{"nodes":[20]}', updatedAt: 20 } + localStorage.setItem(destinationIndexKey, JSON.stringify(previousIndex)) + localStorage.setItem(destinationPayloadKey, JSON.stringify(previousPayload)) + const realSetItem = localStorage.setItem.bind(localStorage) + vi.spyOn(localStorage, 'setItem').mockImplementation( + (key: string, value: string) => { + realSetItem(key, value) + if (key === destinationIndexKey) { + realSetItem(destinationPayloadKey, JSON.stringify(concurrentPayload)) + realSetItem( + claimKey, + JSON.stringify({ + scope: competingScope, + sourceUpdatedAt: 10, + nonce: 'competing-tab' + }) + ) + } + } + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(destinationIndexKey)).toEqual(previousIndex) + expect(readJson(destinationPayloadKey)).toEqual(concurrentPayload) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + }) + it('keeps a restore pointer the scope already owns and still copies the missing one', () => { seedSourceWorkspace() const existingPointer = { From abd625ede97e20f60721918d624cc527cb661ddc Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 14:40:10 -0700 Subject: [PATCH 47/52] docs: record migration completion key lifetime Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3992595925 --- ...RSISTENCE-0031-identity-scoped-draft-storage.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md index d9d3573d8bf..c808406d51a 100644 --- a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -126,6 +126,15 @@ cleanup and does not copy again, so the committed destination is never overwritten by stale source data. A completion record identifies the source generation and lets a losing same-scope tab distinguish the winning copy from its own artifacts without allowing an older migration to suppress rollback. +The record is stored persistently at +`Comfy.Workflow.MigrationCompletion:` as JSON containing the +destination `scope`, the source index's `sourceUpdatedAt` generation and the +winning claim's `nonce`. The winner writes it after publishing the destination +index and before removing source artifacts. Losing attempts read it when they +no longer own the claim and only treat it as another same-scope winner when +both scope and source generation match. It has no TTL and remains for the +lifetime of the browser's site storage so delayed losing attempts can still +identify the committed generation. The first user to sign in on a browser therefore claims any pre-existing workspace-keyed drafts. This is accepted: before this change those drafts were @@ -196,8 +205,9 @@ is a data loss for the common single-user case. - Writes made while the gate is `deferred` are not queued; if the tab closes before the gate opens, changes made during the transition are lost. This is the same window that already existed for the transitioning state. -- One more key segment in `localStorage`; total storage use is unchanged after - migration because source keys are removed. +- One more key segment in `localStorage`, plus one persistent migration + completion record per migrated workspace. Draft storage returns to one copy + after migration because source keys are removed. ## Notes From 54880b98211ae22db751977bb0866242f1c96eeb Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 18:32:49 -0700 Subject: [PATCH 48/52] test: drop vacuous void comparison in migration test Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3993911861 --- .../migration/migrateWorkspaceToScope.test.ts | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 1913417b20c..9e302407a20 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -174,19 +174,12 @@ describe('migrateWorkspaceToScope', () => { it('performs no storage mutations when a completed migration runs again', () => { seedSourceWorkspace() - const firstOutcome = migrateWorkspaceToScope( - sourceWorkspaceId, - destinationScope - ) + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) const setItemSpy = vi.spyOn(localStorage, 'setItem') const removeItemSpy = vi.spyOn(localStorage, 'removeItem') - const secondOutcome = migrateWorkspaceToScope( - sourceWorkspaceId, - destinationScope - ) + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) - expect(secondOutcome).toBe(firstOutcome) expect(setItemSpy).not.toHaveBeenCalled() expect(removeItemSpy).not.toHaveBeenCalled() expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( From 8f03d14aa2a966f3cadbbe6710006047355202fb Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 18:33:32 -0700 Subject: [PATCH 49/52] test: always cancel write-gate transition in migration test Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3993911866 --- .../migration/migrateWorkspaceToScope.test.ts | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts index 9e302407a20..7b543f0820d 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -214,18 +214,21 @@ describe('migrateWorkspaceToScope', () => { seedSourceWorkspace() const cancelTransition = prepareWorkflowWorkspaceTransition() - migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + try { + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) - expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( - buildIndex() - ) - expect(localStorage.getItem(StorageKeys.draftIndex(destinationScope))).toBe( - null - ) - expect( - localStorage.getItem(StorageKeys.migrationClaim(sourceWorkspaceId)) - ).toBe(null) - cancelTransition() + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect( + localStorage.getItem(StorageKeys.draftIndex(destinationScope)) + ).toBe(null) + expect( + localStorage.getItem(StorageKeys.migrationClaim(sourceWorkspaceId)) + ).toBe(null) + } finally { + cancelTransition() + } }) it('keeps the workspace copy and writes no scoped index when a payload copy hits the quota', () => { From 05673adc0b2054d46c84daf462790334ca507816 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 18:34:03 -0700 Subject: [PATCH 50/52] docs: describe migration completion record lifetime Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3993911870 --- ...FLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md index c808406d51a..f4ee643f03a 100644 --- a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -132,9 +132,11 @@ destination `scope`, the source index's `sourceUpdatedAt` generation and the winning claim's `nonce`. The winner writes it after publishing the destination index and before removing source artifacts. Losing attempts read it when they no longer own the claim and only treat it as another same-scope winner when -both scope and source generation match. It has no TTL and remains for the -lifetime of the browser's site storage so delayed losing attempts can still -identify the committed generation. +both scope and source generation match. The key has no TTL, but stores only the +latest completion value for each workspace: every later successful migration +from that workspace replaces it with the new scope, generation and nonce. A +losing attempt delayed until after that replacement can no longer identify the +winner for its older generation from the completion record. The first user to sign in on a browser therefore claims any pre-existing workspace-keyed drafts. This is accepted: before this change those drafts were From 04cb01881fb445ba272067ba5f48518f80810ad1 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Fri, 11 Sep 2026 18:34:15 -0700 Subject: [PATCH 51/52] docs: narrow post-cleanup single-copy claim Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/17313#discussion_r3993911873 --- ...RKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md index f4ee643f03a..17a888ead49 100644 --- a/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -208,8 +208,10 @@ is a data loss for the common single-user case. before the gate opens, changes made during the transition are lost. This is the same window that already existed for the transitioning state. - One more key segment in `localStorage`, plus one persistent migration - completion record per migrated workspace. Draft storage returns to one copy - after migration because source keys are removed. + completion record per migrated workspace. Unchanged artifacts from the + migrated source generation return to one copy after migration because their + source keys are removed. Artifacts changed after the migration snapshot are + preserved at the source. ## Notes From 03c3161b868fd6f5079e7f4f3794e3fe388871e4 Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 18 Sep 2026 01:35:50 -0700 Subject: [PATCH 52/52] refactor: simplify identity draft migration --- ...workflowDraftForeignWindowSignInFixture.ts | 55 +++++-- .../workflowDraftForeignWindowSignIn.spec.ts | 43 +---- .../migration/migrateWorkspaceToScope.ts | 155 +++++++++++++----- 3 files changed, 164 insertions(+), 89 deletions(-) diff --git a/browser_tests/fixtures/workflowDraftForeignWindowSignInFixture.ts b/browser_tests/fixtures/workflowDraftForeignWindowSignInFixture.ts index 7095ca4f114..d609b748988 100644 --- a/browser_tests/fixtures/workflowDraftForeignWindowSignInFixture.ts +++ b/browser_tests/fixtures/workflowDraftForeignWindowSignInFixture.ts @@ -105,21 +105,35 @@ class WorkflowDraftForeignWindowSignInHelper { ) } - async triggerForeignWindowAuthChange(): Promise { - const secondWindow = await this.page.context().newPage() - await this.bootWindow(secondWindow) - await secondWindow.evaluate(() => { - const key = Object.keys(localStorage).find((candidate) => - candidate.startsWith('firebase:authUser:') + seedIdentityScopedDrafts(): Promise<{ + departingKey: string + otherIdentityKey: string + }> { + return this.page.evaluate(() => { + const departingKey = Object.keys(localStorage).find((key) => + key.startsWith('Comfy.Workflow.Draft.v2:') ) - if (!key || !localStorage.getItem(key)) { - throw new Error('no shared Firebase auth record') - } - - localStorage.removeItem(key) + if (!departingKey) throw new Error('no departing identity draft') + const otherIdentityKey = + 'Comfy.Workflow.Draft.v2:other-user:ws-personal:other' + localStorage.setItem(otherIdentityKey, '{"data":"{}","updatedAt":1}') + return { departingKey, otherIdentityKey } }) } + hasStorageValue(key: string): Promise { + return this.page.evaluate( + (storageKey) => localStorage.getItem(storageKey) !== null, + key + ) + } + + async logout(): Promise { + await this.page.getByRole('button', { name: 'Current user' }).click() + await this.page.getByTestId('logout-menu-item').click() + await this.page.getByRole('button', { name: 'Sign out anyway' }).click() + } + private async bootWindow(page: Page): Promise { await mockCloudBoot(page, { features: BOOT_FEATURES, @@ -128,6 +142,25 @@ class WorkflowDraftForeignWindowSignInHelper { await bootCloud(page) await page.goto(APP_URL) await waitForCloudApp(page) + await page.evaluate(() => { + sessionStorage.setItem( + 'Comfy.Workspace.Current', + JSON.stringify({ + id: 'ws-personal', + name: 'Personal Workspace', + type: 'personal', + role: 'owner', + created_at: '2026-01-01T00:00:00Z', + joined_at: '2026-01-01T00:00:00Z' + }) + ) + sessionStorage.setItem('Comfy.Workspace.Token', 'mock-workspace-token') + sessionStorage.setItem( + 'Comfy.Workspace.ExpiresAt', + String(Date.now() + 60 * 60 * 1000) + ) + sessionStorage.setItem('Comfy.Workspace.OwnerUid', 'test-user-e2e') + }) await page.waitForFunction( () => !!(window.app!.extensionManager as WorkspaceStore).workflow diff --git a/browser_tests/tests/workspace/workflowDraftForeignWindowSignIn.spec.ts b/browser_tests/tests/workspace/workflowDraftForeignWindowSignIn.spec.ts index ef6331e1e5a..f994c4b6d8b 100644 --- a/browser_tests/tests/workspace/workflowDraftForeignWindowSignIn.spec.ts +++ b/browser_tests/tests/workspace/workflowDraftForeignWindowSignIn.spec.ts @@ -4,49 +4,20 @@ import { } from '@e2e/fixtures/workflowDraftForeignWindowSignInFixture' test.describe('workflow drafts across windows', { tag: '@cloud' }, () => { - test('a second window signing in neither wipes drafts nor stops persistence', async ({ + test('logout removes only the departing identity draft scope', async ({ workflowDraft }) => { const initialTouch = await workflowDraft.touchGraph() await expect .poll(() => workflowDraft.hasPersistedTouch(initialTouch)) .toBe(true) - - const draftsBefore = await workflowDraft.getDraftKeys() - expect( - await workflowDraft.hasWorkspaceContext(), - 'first window has no workspace context before the auth change' - ).toBe(true) - - await workflowDraft.triggerForeignWindowAuthChange() + const { departingKey, otherIdentityKey } = + await workflowDraft.seedIdentityScopedDrafts() + await workflowDraft.logout() await expect - .poll(() => workflowDraft.hasClearedWorkspaceContext(), { - message: - "first window never observed the second window's auth change - repro harness needs work, not a passing build" - }) - .toBe(true) - - await expect(workflowDraft.logoutButton).toBeVisible() - - test.fail( - true, - 'Foreign-window sign-in wipes drafts and fences persistence' - ) - - expect - .soft( - await workflowDraft.getDraftKeys(), - 'drafts were wiped by a transient auth change in another window' - ) - .toEqual(draftsBefore) - - const touchAfterAuthChange = await workflowDraft.touchGraph() - await expect - .poll(() => workflowDraft.hasPersistedTouch(touchAfterAuthChange), { - message: - 'persistence stayed fenced after the auth change - the logout transition was never completed' - }) - .toBe(true) + .poll(() => workflowDraft.hasStorageValue(departingKey)) + .toBe(false) + expect(await workflowDraft.hasStorageValue(otherIdentityKey)).toBe(true) }) }) diff --git a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts index f21eea71f08..320ae0d87c2 100644 --- a/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -18,6 +18,8 @@ type MigrationClaim = { type MigrationCompletion = MigrationClaim & { nonce: string } +type MigrationIndex = NonNullable> + const restorePointerKeys = [ StorageKeys.lastActivePath, StorageKeys.lastOpenPaths @@ -55,12 +57,7 @@ export function migrateWorkspaceToScope( const sourceArtifacts = snapshotSourceArtifacts(workspaceId) const destinationIndex = readIndex(scope) - if (destinationIndex) { - const canFinishCleanup = - existingClaim !== null && index.updatedAt <= existingClaim.sourceUpdatedAt - const hasNewerSource = index.updatedAt > destinationIndex.updatedAt - if (!canFinishCleanup && !hasNewerSource) return - } + if (!shouldStartMigration(index, destinationIndex, existingClaim)) return const claim: MigrationClaim = { scope, @@ -70,11 +67,7 @@ export function migrateWorkspaceToScope( if (!writeStorage(localStorage, claimKey, JSON.stringify(claim))) return if (!ownsClaim(claimKey, claim)) return - if ( - destinationIndex && - existingClaim !== null && - index.updatedAt <= existingClaim.sourceUpdatedAt - ) { + if (canFinishExistingMigration(index, destinationIndex, existingClaim)) { cleanupSourceIfCurrent( workspaceId, sourcePayloads, @@ -101,50 +94,128 @@ export function migrateWorkspaceToScope( missingPointerKeys ) - const artifactsCopied = - draftKeys.every((draftKey) => - copyPayload( - draftKey, - workspaceId, - scope, - sourcePayloads.get(draftKey) ?? null - ) - ) && - missingPointerKeys.every((keyFor) => - copyRestorePointer(keyFor, workspaceId, scope) - ) + const artifactsCopied = copyMigrationArtifacts( + workspaceId, + scope, + draftKeys, + sourcePayloads, + missingPointerKeys + ) const published = artifactsCopied && ownsClaim(claimKey, claim) && writeIndex(scope, index) const copied = published && ownsClaim(claimKey, claim) if (copied) { - const completionRecorded = writeStorage( - localStorage, - completionKey, - JSON.stringify(claim) - ) - if (!completionRecorded) return - cleanupSourceIfCurrent( + completeMigration( workspaceId, sourcePayloads, sourceArtifacts, claimKey, + completionKey, claim ) } else { - const currentClaim = readLocalPointer(claimKey, isValidClaim) - const completion = readLocalPointer(completionKey, isValidCompletion) - const sameScopePeer = - currentClaim?.scope === scope - ? currentClaim.nonce !== claim.nonce - : completion?.scope === scope && - completion.sourceUpdatedAt === claim.sourceUpdatedAt && - completion.nonce !== claim.nonce - if (!sameScopePeer) { - restoreStorageSnapshot(destinationSnapshot, migrationArtifacts) - } - releaseClaimIfOwned(claimKey, claim) + rollbackMigration( + scope, + claimKey, + completionKey, + claim, + destinationSnapshot, + migrationArtifacts + ) + } +} + +function canFinishExistingMigration( + index: MigrationIndex, + destinationIndex: MigrationIndex | null, + existingClaim: MigrationClaim | null +): boolean { + return ( + destinationIndex !== null && + existingClaim !== null && + index.updatedAt <= existingClaim.sourceUpdatedAt + ) +} + +function shouldStartMigration( + index: MigrationIndex, + destinationIndex: MigrationIndex | null, + existingClaim: MigrationClaim | null +): boolean { + if (destinationIndex === null) return true + return ( + canFinishExistingMigration(index, destinationIndex, existingClaim) || + index.updatedAt > destinationIndex.updatedAt + ) +} + +function copyMigrationArtifacts( + workspaceId: string, + scope: string, + draftKeys: string[], + sourcePayloads: Map, + missingPointerKeys: ((scope: string) => string)[] +): boolean { + const payloadsCopied = draftKeys.every((draftKey) => + copyPayload( + draftKey, + workspaceId, + scope, + sourcePayloads.get(draftKey) ?? null + ) + ) + return ( + payloadsCopied && + missingPointerKeys.every((keyFor) => + copyRestorePointer(keyFor, workspaceId, scope) + ) + ) +} + +function completeMigration( + workspaceId: string, + sourcePayloads: Map, + sourceArtifacts: Map, + claimKey: string, + completionKey: string, + claim: MigrationClaim +): void { + const completionRecorded = writeStorage( + localStorage, + completionKey, + JSON.stringify(claim) + ) + if (!completionRecorded) return + cleanupSourceIfCurrent( + workspaceId, + sourcePayloads, + sourceArtifacts, + claimKey, + claim + ) +} + +function rollbackMigration( + scope: string, + claimKey: string, + completionKey: string, + claim: MigrationClaim, + destinationSnapshot: Map, + migrationArtifacts: Map +): void { + const currentClaim = readLocalPointer(claimKey, isValidClaim) + const completion = readLocalPointer(completionKey, isValidCompletion) + const sameScopePeer = + currentClaim?.scope === scope + ? currentClaim.nonce !== claim.nonce + : completion?.scope === scope && + completion.sourceUpdatedAt === claim.sourceUpdatedAt && + completion.nonce !== claim.nonce + if (!sameScopePeer) { + restoreStorageSnapshot(destinationSnapshot, migrationArtifacts) } + releaseClaimIfOwned(claimKey, claim) } function ownsClaim(claimKey: string, claim: MigrationClaim): boolean {