Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
49b829c
test: cover storage scope resolution
christian-byrne Sep 9, 2026
078e3c3
fix: resolve workflow storage scope from user and workspace
christian-byrne Sep 9, 2026
5680f8f
test: cover scoped workflow storage gate and wipe
christian-byrne Sep 9, 2026
561b277
fix: gate workflow storage on resolved identity and scope wipes
christian-byrne Sep 9, 2026
baa46b2
test: cover moving workspace drafts into a user scope
christian-byrne Sep 9, 2026
41ca6df
fix: move workspace drafts into the resolved user scope
christian-byrne Sep 9, 2026
05fe3ee
test: cover scoped draft and tab pointer storage
christian-byrne Sep 9, 2026
41eec65
fix: key drafts and tab pointers by resolved storage scope
christian-byrne Sep 9, 2026
ba25a54
test: cover identity-scoped workflow persistence
christian-byrne Sep 9, 2026
d147de7
fix: fence and scope workflow persistence on resolved identity
christian-byrne Sep 9, 2026
72300a2
test: cover scoped workflow wipe on cloud logout
christian-byrne Sep 9, 2026
11ede87
fix: wipe only the departing identity scope on cloud logout
christian-byrne Sep 9, 2026
494dd07
docs: add ADR for identity-scoped workflow persistence
christian-byrne Sep 9, 2026
4d245cc
test: defer draft writes while the cloud workspace is unresolved
christian-byrne Sep 10, 2026
ab9386d
fix: defer draft writes until the cloud workspace is resolved
christian-byrne Sep 10, 2026
6a67422
test: fence draft writes on the initial identity resolution
christian-byrne Sep 10, 2026
979c3d4
fix: fence draft writes on the initial identity resolution
christian-byrne Sep 10, 2026
c5f474e
test: roll back and converge the workspace-to-scope migration
christian-byrne Sep 10, 2026
2008ff3
fix: roll back and converge the workspace-to-scope migration
christian-byrne Sep 10, 2026
e8ce7ed
docs: record migration rollback and multi-tab deferrals in ADR 0031
christian-byrne Sep 10, 2026
239ae91
test: cover review findings for scoped draft migration and deferred w…
christian-byrne Sep 10, 2026
bb9ac33
fix: keep scope restore pointers and flush edits deferred during iden…
christian-byrne Sep 10, 2026
3004beb
test: sort storage keys with an explicit comparator
christian-byrne Sep 10, 2026
2100c7e
test: cover readWorkspaceId null and storage failures
christian-byrne Sep 10, 2026
a150c65
test: expose cross-identity draft adoption
ampagent Sep 10, 2026
9000422
test: preserve resolved deferred draft writes
ampagent Sep 10, 2026
0bdd0b4
fix: retain draft persistence ownership
ampagent Sep 10, 2026
9c57686
test: narrow draft payload before parsing
christian-byrne Sep 11, 2026
374c03b
fix: claim workspace drafts before migrating them
christian-byrne Sep 11, 2026
ec101ab
refactor: name scope parameters in draft storage keys
christian-byrne Sep 11, 2026
ef682d6
docs: narrow identity-scoping guarantee in ADR 0031
christian-byrne Sep 11, 2026
1a9ca0b
test: use global testing Pinia for draft scope
christian-byrne Sep 11, 2026
f38db4d
fix: make legacy draft migration claim exclusive and preserve newer s…
christian-byrne Sep 11, 2026
3a482e0
fix: compensate lost migration publication
christian-byrne Sep 11, 2026
c6706f5
fix: preserve same-scope migration winner
christian-byrne Sep 11, 2026
b329e4a
fix: preserve concurrently saved source payloads
christian-byrne Sep 11, 2026
5322140
fix: preserve concurrent scoped draft writes
christian-byrne Sep 11, 2026
c8e9541
fix: bind migration completion to source generation
christian-byrne Sep 11, 2026
af589db
fix: compare source artifacts before cleanup
christian-byrne Sep 11, 2026
a1338da
fix(persistence): keep source when migration completion write fails
christian-byrne Sep 11, 2026
9efc0b8
fix(persistence): bind completion validity to source generation
christian-byrne Sep 11, 2026
9349abf
fix(persistence): avoid destructive migration cleanup races
christian-byrne Sep 11, 2026
23f75c8
test(persistence): ignore completion records from other scopes
christian-byrne Sep 11, 2026
68986e1
test(persistence): verify migration rerun idempotence
christian-byrne Sep 11, 2026
26599fd
test(persistence): honor write gate during migration
christian-byrne Sep 11, 2026
8a22252
test(persistence): cover migration rollback errors
christian-byrne Sep 11, 2026
abd625e
docs: record migration completion key lifetime
christian-byrne Sep 11, 2026
54880b9
test: drop vacuous void comparison in migration test
christian-byrne Sep 12, 2026
8f03d14
test: always cancel write-gate transition in migration test
christian-byrne Sep 12, 2026
05673ad
docs: describe migration completion record lifetime
christian-byrne Sep 12, 2026
04cb018
docs: narrow post-cleanup single-copy claim
christian-byrne Sep 12, 2026
03c3161
refactor: simplify identity draft migration
christian-byrne Sep 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 44 additions & 11 deletions browser_tests/fixtures/workflowDraftForeignWindowSignInFixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,21 +105,35 @@ class WorkflowDraftForeignWindowSignInHelper {
)
}

async triggerForeignWindowAuthChange(): Promise<void> {
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<boolean> {
return this.page.evaluate(
(storageKey) => localStorage.getItem(storageKey) !== null,
key
)
}

async logout(): Promise<void> {
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<void> {
await mockCloudBoot(page, {
features: BOOT_FEATURES,
Expand All @@ -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({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This duplicates the existing typed mockPersonalWorkspace fixture field for field, while the session key strings already have an owner in WORKSPACE_STORAGE_KEYS. Import those contracts and pass the typed value into page.evaluate; otherwise a generated workspace-contract change can leave this test compiling with stale session data.

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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This direct seed no longer proves cross-window or resolved-identity isolation. One page inserts an arbitrary foreign-looking key and then performs ordinary logout; the test still passes if two real users incorrectly resolve to the same scope. Restore the second-page auth flow and have both identities persist through production, or keep this as a separately named logout test without deleting the foreign-window regression. The fixture and describe names, plus several now-unused helper members, should match whichever behavior remains.

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)
})
})
1 change: 1 addition & 0 deletions docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
227 changes: 227 additions & 0 deletions docs/adr/WORKFLOW-PERSISTENCE-0031-identity-scoped-draft-storage.md
Original file line number Diff line number Diff line change
@@ -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`:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This absolute ownership claim contradicts the deferred-decisions section, which records useNewUserService.ts reading the literal DraftIndex.v2:personal key. Narrow this to scoped-key computation and name the existing non-cloud exception.

- `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:<workspaceId>` 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This rationale is factually false at the current head. The PR adds 653 lines of production TypeScript, and migrateWorkspaceToScope.ts alone is 387 lines. Please split identity scoping/write gating from the legacy migration protocol, or replace this budget claim with the actual tradeoff.

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:<uid>:<workspaceId>
Comfy.Workflow.Draft.v2:<uid>:<workspaceId>:<hashedPath>
Comfy.Workflow.LastActivePath:<uid>:<workspaceId>
Comfy.Workflow.LastOpenPaths:<uid>:<workspaceId>
```

Non-cloud builds keep `personal` as the scope, so their keys are unchanged.
Loading
Loading