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/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..17a888ead49 --- /dev/null +++ b/docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md @@ -0,0 +1,227 @@ +# 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 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. + +`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 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. 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. 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 + +`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 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 +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. 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 +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. +- 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 + +- **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 + +- 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 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. +- One more key segment in `localStorage`, plus one persistent migration + 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 + +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. 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/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.test.ts b/src/platform/workflow/persistence/base/storageIO.test.ts index a4105d8e6f7..722ce158ef9 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,21 @@ 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']) + Object.keys(localStorage).toSorted((a, b) => a.localeCompare(b)) + ).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 +324,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 +349,7 @@ describe('storageIO', () => { const isolatedStorageIO = await import('./storageIO') isolatedStorageIO.prepareWorkflowLogoutTransition() - isolatedStorageIO.clearAllWorkflowStorage() + isolatedStorageIO.clearWorkflowStorageForScope('ws-1') expect(isolatedStorageIO.isStorageAvailable()).toBe(false) expect( @@ -377,7 +385,7 @@ describe('storageIO', () => { sessionStorage.setItem('Comfy.Workflow.ActivePath:client-1', '{}') markStorageUnavailable() - clearAllWorkflowStorage() + clearWorkflowStorageForScope('personal') expect( localStorage.getItem('Comfy.Workflow.LastActivePath:personal') @@ -388,6 +396,96 @@ 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 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') + + 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') diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index dede097a90f..ce103024312 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -10,9 +10,14 @@ import type { DraftPayloadV2, OpenPathsPointer } from './draftTypes' -import { StorageKeys } from './storageKeys' +import { + StorageKeys, + readWorkspaceId, + resolveStorageScope +} from './storageKeys' type StorageAvailability = 'available' | 'unavailable' +type StorageWriteGate = 'open' | 'deferred' | 'closed' type WorkflowStorageState = | { status: 'ready'; availability: StorageAvailability } | { @@ -31,8 +36,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, readWorkspaceId()) +} + +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 +71,7 @@ function flushPendingWorkflowPersistence(): void { } export function isStorageAvailable(): boolean { - return ( - workflowStorageState.status === 'ready' && - workflowStorageState.availability === 'available' - ) + return getStorageWriteGate() === 'open' } export function markStorageUnavailable(): void { @@ -100,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 @@ -120,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) { @@ -137,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 @@ -157,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) { @@ -176,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 @@ -188,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 { @@ -221,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++ } } @@ -238,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++) { @@ -257,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 @@ -273,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 { @@ -287,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 @@ -314,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) @@ -350,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. } @@ -366,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) @@ -421,7 +435,7 @@ function isValidOpenPathsPointer(value: unknown): value is OpenPathsPointer { ) } -function readLocalPointer( +export function readLocalPointer( key: string, validate: (value: unknown) => value is T ): T | null { @@ -435,13 +449,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 } } @@ -469,7 +489,7 @@ const sessionRestoreKeys = [ 'Comfy.ActiveWorkflowIndex' ] -function removeStorageKeys( +export function removeStorageKeys( storage: Storage, keys: string[], prefixes: string[] = [] @@ -552,16 +572,17 @@ export function completeWorkflowLogoutTransition(): void { } } -export function clearAllWorkflowStorage(): void { - const localPrefixes = [ - StorageKeys.prefixes.draftIndex, - StorageKeys.prefixes.draftPayload, - StorageKeys.prefixes.lastActivePath, - StorageKeys.prefixes.lastOpenPaths, - 'Comfy.Workflow.Drafts:', - 'Comfy.Workflow.DraftOrder:' +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, legacyLocalRestoreKeys, localPrefixes) + removeStorageKeys(localStorage, localKeys, localPrefixes) removeStorageKeys(sessionStorage, sessionRestoreKeys, sessionRestorePrefixes) } diff --git a/src/platform/workflow/persistence/base/storageKeys.test.ts b/src/platform/workflow/persistence/base/storageKeys.test.ts index d6c28c3631d..dd4e8a9c525 100644 --- a/src/platform/workflow/persistence/base/storageKeys.test.ts +++ b/src/platform/workflow/persistence/base/storageKeys.test.ts @@ -4,105 +4,148 @@ 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('StorageKeys', () => { - it('generates draftIndex key with workspace scope', async () => { - const { StorageKeys } = await import('./storageKeys') + describe('readWorkspaceId', () => { + it('returns null in cloud until a workspace is stored', () => { + expect(readWorkspaceId()).toBeNull() + }) + + it('returns null in cloud when the stored workspace is unreadable', () => { + setCurrentWorkspace('invalid-json') + 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') + }) + + 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', () => { + mockDistributionTypes.isCloud = false + setCurrentWorkspace({ type: 'team', id: 'workspace-a' }) + expect(readWorkspaceId()).toBe('personal') + }) + }) + + describe('resolveStorageScope', () => { + 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', () => { + expect(resolveStorageScope(null, 'ws-1')).toBeNull() + }) + + it('returns null in cloud until the workspace is resolved', () => { + expect(resolveStorageScope('user-a', null)).toBeNull() + }) + + it('ignores identity outside cloud', () => { + mockDistributionTypes.isCloud = false + expect(resolveStorageScope(null, 'ws-1')).toBe('personal') + expect(resolveStorageScope('user-a', 'ws-1')).toBe('personal') + }) + }) + + describe('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') @@ -110,23 +153,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/base/storageKeys.ts b/src/platform/workflow/persistence/base/storageKeys.ts index 83f9deca776..011c0a37e1b 100644 --- a/src/platform/workflow/persistence/base/storageKeys.ts +++ b/src/platform/workflow/persistence/base/storageKeys.ts @@ -4,34 +4,57 @@ 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 both are known. + */ +export function resolveStorageScope( + userId: string | null, + workspaceId: string | null +): string | null { + if (!isCloud) return 'personal' + return userId && workspaceId ? `${userId}:${workspaceId}` : null +} + /** * 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 = { @@ -39,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}` }, /** @@ -80,12 +103,20 @@ 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(scope: string): string { + return `Comfy.Workflow.LastOpenPaths:${scope}` + }, + + migrationClaim(workspaceId: string): string { + return `Comfy.Workflow.MigrationClaim:${workspaceId}` }, - lastOpenPaths(workspaceId: string): string { - return `Comfy.Workflow.LastOpenPaths:${workspaceId}` + migrationCompletion(workspaceId: string): string { + return `Comfy.Workflow.MigrationCompletion:${workspaceId}` }, /** @@ -97,6 +128,8 @@ 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:', + migrationCompletion: 'Comfy.Workflow.MigrationCompletion:' } } as const diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index e58c671b898..404446aeefa 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -7,11 +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 @@ -199,6 +219,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 }) }) @@ -705,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' } @@ -753,6 +775,15 @@ 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.graphChangedHandler?.() + await vi.runAllTimersAsync() mocks.state.currentGraph = { nodes: [], @@ -762,13 +793,14 @@ 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() + const payloadBeforeTransition = readDraftPayload(sourcePayloadKey) + expect(JSON.parse(payloadBeforeTransition.data)).toEqual({ initial: true }) const cancelTransition = storageIO.prepareWorkflowWorkspaceTransition() sessionStorage.setItem( @@ -782,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' } @@ -799,6 +831,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() @@ -807,8 +843,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 +943,7 @@ describe('useWorkflowPersistenceV2', () => { ) const destinationPayloadKey = StorageKeys.draftPayload( workflow.path, - destinationWorkspaceId + `user-b:${destinationWorkspaceId}` ) const personalPayloadKey = StorageKeys.draftPayload( workflow.path, @@ -937,4 +971,285 @@ 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 = readDraftPayload(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(readDraftPayload(userAPayloadKey).data).toBe(userAPayload.data) + const userBPayload = readDraftPayload(userBPayloadKey) + 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( + 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() + + 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() + + 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 () => { + 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(legacyIndex('Legacy.json')) + ) + 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( + readDraftPayload( + StorageKeys.draftPayload('Legacy.json', 'user-a:workspace-a') + ).data + ).toBe('{"marker":"legacy"}') + expect(useWorkflowDraftStoreV2().getDraft('Legacy.json')?.data).toBe( + '{"marker":"legacy"}' + ) + }) + + it('preserves unclaimed workspace drafts 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)).not.toBeNull() + expect(localStorage.getItem(workspacePayloadKey)).not.toBeNull() + expect(localStorage.getItem(scopedIndexKey)).toBe(scopedIndex) + }) + + it('does not adopt an ownerless edit when 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).toBeNull() + }) }) + +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/useWorkflowPersistenceV2.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts index 51e555aa89b..d36f09e91dd 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts @@ -32,12 +32,16 @@ import { import { PERSIST_DEBOUNCE_MS } from '../base/draftTypes' import type { StartupOutcome } from '../base/draftTypes' import { - clearAllWorkflowStorage, completeWorkflowLogoutTransition, + getStorageScope, + getStorageWriteGate, prepareWorkflowLogoutTransition, - registerWorkflowPersistenceFlush + 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 +71,19 @@ 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 + } + migrateV1toV2(workspaceId, clientId) + migrateWorkspaceToScope(workspaceId, scope) + } + + ensureScopedStorage(api.clientId ?? api.initialClientId ?? undefined) const ensureTemplateQueryFromIntent = async () => { hydratePreservedQuery(TEMPLATE_NAMESPACE) @@ -89,6 +104,8 @@ export function useWorkflowPersistenceV2() { ) const lastSavedJsonByPath = ref>({}) + let resolvedUserId: string | null = null + let pendingPersistenceOwnerId: string | null = null watch(workflowPersistenceEnabled, (enabled) => { if (!enabled) { @@ -98,16 +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, { @@ -138,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() } @@ -147,16 +185,38 @@ export function useWorkflowPersistenceV2() { ) window.addEventListener('pagehide', flushPendingPersistence) - onUserLogout(() => { - if (!isCloud) return + function fenceIdentityChange(): void { stopPendingWorkspaceReadinessWatcher() debouncedPersist.cancel() + pendingPersistenceOwnerId = null prepareWorkflowLogoutTransition() - clearAllWorkflowStorage() + lastSavedJsonByPath.value = {} + } + + function releaseIdentityFence(): void { + completeWorkflowLogoutTransition() + ensureScopedStorage() + if ( + pendingPersistenceOwnerId !== null && + pendingPersistenceOwnerId === resolvedUserId + ) { + debouncedPersist.cancel() + persistCurrentWorkflow() + } + } + + onUserLogout(() => { + if (!isCloud) return + fenceIdentityChange() + resolvedUserId = null + setStorageIdentity(null) }) - onUserResolved(() => { + onUserResolved((user) => { if (!isCloud) return + if (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 +227,7 @@ export function useWorkflowPersistenceV2() { teamWorkspaceStore.activeWorkspaceId !== null) || teamWorkspaceStore.initState === 'error' if (isWorkspaceInitConcluded()) { - completeWorkflowLogoutTransition() + releaseIdentityFence() return } @@ -175,7 +235,7 @@ export function useWorkflowPersistenceV2() { isWorkspaceInitConcluded, () => { stopWorkspaceReadinessWatcher = undefined - completeWorkflowLogoutTransition() + releaseIdentityFence() }, { once: true } ) @@ -304,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() diff --git a/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts b/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts index b55c0347e89..708f7c0fd58 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowTabState.test.ts @@ -9,45 +9,69 @@ 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() + setCurrentWorkspace('ws-1') + 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') - const { useWorkflowTabState: useWorkflowTabState2 } = - await import('./useWorkflowTabState') - const { getActivePath } = useWorkflowTabState2() + expect(getActivePath()).toBeNull() + }) + + 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 +79,14 @@ 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() + setCurrentWorkspace('ws-1') + const { getOpenPaths, setOpenPaths } = await loadTabState('user-a') const paths = ['workflows/a.json', 'workflows/b.json'] setOpenPaths(paths, 1) @@ -74,39 +97,44 @@ 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' }) - ) + setCurrentWorkspace('ws-2') + const { getOpenPaths } = await loadTabState('user-a') - const { useWorkflowTabState: useWorkflowTabState2 } = - await import('./useWorkflowTabState') - const { getOpenPaths } = useWorkflowTabState2() + 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 () => { - 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/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/migration/migrateWorkspaceToScope.test.ts b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts new file mode 100644 index 00000000000..7b543f0820d --- /dev/null +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.test.ts @@ -0,0 +1,948 @@ +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' + +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) + +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(() => { + localStorage.clear() + }) + + 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('finishes the source cleanup when the destination is already committed', () => { + seedSourceWorkspace() + const destinationIndex: DraftIndexV2 = { + v: 2, + updatedAt: 99, + order: [], + entries: {} + } + localStorage.setItem( + StorageKeys.draftIndex(destinationScope), + JSON.stringify(destinationIndex) + ) + localStorage.setItem( + StorageKeys.migrationClaim(sourceWorkspaceId), + JSON.stringify({ scope: destinationScope, sourceUpdatedAt: 10 }) + ) + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + expect(readJson(StorageKeys.draftIndex(destinationScope))).toEqual( + destinationIndex + ) + expect( + localStorage.getItem( + StorageKeys.draftPayload(draftPath, destinationScope) + ) + ).toBe(null) + 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) + expect( + localStorage.getItem(StorageKeys.migrationClaim(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('performs no storage mutations when a completed migration runs again', () => { + seedSourceWorkspace() + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + const setItemSpy = vi.spyOn(localStorage, 'setItem') + const removeItemSpy = vi.spyOn(localStorage, 'removeItem') + + migrateWorkspaceToScope(sourceWorkspaceId, destinationScope) + + 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), + 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('does not migrate drafts while workflow storage writes are deferred', () => { + seedSourceWorkspace() + const cancelTransition = prepareWorkflowWorkspaceTransition() + + 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) + } finally { + cancelTransition() + } + }) + + 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 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) + } + ) + + 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 + ) + }) + + 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) + 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) + ) + ).not.toBe(null) + expect( + localStorage.getItem(StorageKeys.lastActivePath(destinationScope)) + ).not.toBe(null) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect(readJson(StorageKeys.lastActivePath(sourceWorkspaceId))).toEqual({ + workspaceId: sourceWorkspaceId, + path: draftPath + }) + }) + + 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 = { + 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) + ) + ).not.toBe(null) + expect(readJson(StorageKeys.draftIndex(sourceWorkspaceId))).toEqual( + buildIndex() + ) + expect(readJson(StorageKeys.lastOpenPaths(sourceWorkspaceId))).toEqual({ + workspaceId: sourceWorkspaceId, + paths: [draftPath], + 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('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('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)).toEqual(buildIndex()) + 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('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' + }) + ) + 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)).toEqual({ + data: '{"nodes":[]}', + updatedAt: 10 + }) + }) + + 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) + 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('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) + 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) + 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 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 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 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( + 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 new file mode 100644 index 00000000000..320ae0d87c2 --- /dev/null +++ b/src/platform/workflow/persistence/migration/migrateWorkspaceToScope.ts @@ -0,0 +1,387 @@ +import { + getPayloadKeys, + readIndex, + readLocalPointer, + readPayload, + removeStorageKeys, + writeIndex, + writePayload, + writeStorage +} from '../base/storageIO' +import { StorageKeys } from '../base/storageKeys' + +type MigrationClaim = { + scope: string + sourceUpdatedAt: number + nonce?: string +} + +type MigrationCompletion = MigrationClaim & { nonce: string } + +type MigrationIndex = NonNullable> + +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' + ) +} + +function isValidCompletion(value: unknown): value is MigrationCompletion { + if (!isValidClaim(value)) return false + const candidate = value as Record + return typeof candidate.nonce === 'string' +} + +export function migrateWorkspaceToScope( + workspaceId: string, + scope: string +): void { + const index = readIndex(workspaceId) + if (!index) return + + const claimKey = StorageKeys.migrationClaim(workspaceId) + const completionKey = StorageKeys.migrationCompletion(workspaceId) + const existingClaim = readLocalPointer(claimKey, isValidClaim) + if (existingClaim && existingClaim.scope !== scope) return + + const draftKeys = getPayloadKeys(workspaceId) + const sourcePayloads = snapshotPayloads(workspaceId, draftKeys) + const sourceArtifacts = snapshotSourceArtifacts(workspaceId) + const destinationIndex = readIndex(scope) + + if (!shouldStartMigration(index, destinationIndex, existingClaim)) return + + const claim: MigrationClaim = { + scope, + sourceUpdatedAt: index.updatedAt, + nonce: crypto.randomUUID() + } + if (!writeStorage(localStorage, claimKey, JSON.stringify(claim))) return + if (!ownsClaim(claimKey, claim)) return + + if (canFinishExistingMigration(index, destinationIndex, existingClaim)) { + cleanupSourceIfCurrent( + workspaceId, + sourcePayloads, + sourceArtifacts, + claimKey, + claim + ) + return + } + + const missingPointerKeys = restorePointerKeys.filter( + (keyFor) => localStorage.getItem(keyFor(scope)) === null + ) + const destinationSnapshot = snapshotScopeArtifacts( + scope, + draftKeys, + missingPointerKeys + ) + const migrationArtifacts = snapshotMigrationArtifacts( + workspaceId, + scope, + index, + sourcePayloads, + missingPointerKeys + ) + + 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) { + completeMigration( + workspaceId, + sourcePayloads, + sourceArtifacts, + claimKey, + completionKey, + claim + ) + } else { + 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 { + 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, + sourcePayloads: Map, + sourceArtifacts: Map, + claimKey: string, + claim: MigrationClaim +): void { + if (!ownsClaim(claimKey, claim)) return + const currentSource = readIndex(workspaceId) + if ( + currentSource && + currentSource.updatedAt <= claim.sourceUpdatedAt && + ownsClaim(claimKey, claim) + ) { + for (const [draftKey, sourceRaw] of sourcePayloads) { + const key = payloadKey(workspaceId, draftKey) + removeStorageValueIfStable(key, sourceRaw) + } + for (const [key, sourceRaw] of sourceArtifacts) { + 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[], + pointerKeys: ((scope: string) => string)[] +): Map { + const keys = [ + StorageKeys.draftIndex(scope), + ...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 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, + 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, + 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 + localStorage.setItem(key, value) + } +} + +function copyPayload( + draftKey: string, + workspaceId: string, + scope: string, + sourceRaw: string | null +): boolean { + if (sourceRaw === null) return false + const payload = readPayload(workspaceId, draftKey) + if ( + !payload || + localStorage.getItem(payloadKey(workspaceId, draftKey)) !== sourceRaw + ) + return false + return writePayload(scope, draftKey, payload) +} + +function copyRestorePointer( + keyFor: (scope: string) => string, + workspaceId: string, + scope: string +): boolean { + try { + 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 }) + ) + } catch { + return false + } +} 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..54879a750cc --- /dev/null +++ b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.scope.test.ts @@ -0,0 +1,85 @@ +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' +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 } + +function setPersonalWorkspace() { + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ type: 'personal' }) + ) +} + +describe('workflowDraftStoreV2 storage scope', () => { + beforeEach(() => { + localStorage.clear() + sessionStorage.clear() + 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', () => { + setPersonalWorkspace() + 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', () => { + setPersonalWorkspace() + 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"}') + }) +}) diff --git a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.ts index da7a745c009..fb9241ba79a 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, @@ -49,57 +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>({}) - - /** - * Gets the current workspace ID fresh (not cached). - * This ensures operations use the correct workspace after switches. - */ - function currentWorkspaceId(): string { - return getWorkspaceId() - } + // 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 = currentWorkspaceId() + 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 = currentWorkspaceId() - indexCacheByWorkspace.value[workspaceId] = index - return writeIndex(workspaceId, index) + const scope = getStorageScope() + if (!scope) return false + indexCacheByScope.value[scope] = index + return writeIndex(scope, index) } /** @@ -107,9 +100,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 scope = getStorageScope() + if (!scope || !isStorageAvailable()) return false - const workspaceId = currentWorkspaceId() const draftKey = hashPath(path) const now = Date.now() @@ -119,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 }) @@ -136,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 } @@ -163,7 +156,8 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { data: string, meta: DraftMeta ): boolean { - const workspaceId = currentWorkspaceId() + const scope = getStorageScope() + if (!scope) return false const draftKey = hashPath(path) let currentIndex = loadIndex() @@ -182,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, @@ -195,7 +189,7 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { MAX_DRAFTS ) if (!persistIndex(finalIndex)) { - deletePayload(workspaceId, draftKey) + deletePayload(scope, draftKey) persistIndex(currentIndex) return false } @@ -259,12 +253,13 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Removes a draft. */ function removeDraft(path: string): void { - const workspaceId = currentWorkspaceId() + 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) } } @@ -273,24 +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 = currentWorkspaceId() + 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) } } } @@ -304,13 +300,14 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { isTemporary: boolean updatedAt: number } | null { - const workspaceId = currentWorkspaceId() + 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) @@ -418,8 +415,9 @@ export const useWorkflowDraftStoreV2 = defineStore('workflowDraftV2', () => { * Resets the store (clears in-memory cache for current workspace). */ function reset(): void { - const workspaceId = currentWorkspaceId() - delete indexCacheByWorkspace.value[workspaceId] + const scope = getStorageScope() + if (!scope) return + delete indexCacheByScope.value[scope] } return {