From 8b2a2fecb927488b391b955b13d25982dfd7b673 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Mon, 14 Sep 2026 16:26:26 +0530 Subject: [PATCH 1/6] refactor(website): adopt the bounded-operation primitive in workshop session state --- .../src/config/workshop-session-state.test.ts | 27 ++++++++++++ .../src/config/workshop-session-state.ts | 42 ++++++++----------- 2 files changed, 45 insertions(+), 24 deletions(-) diff --git a/apps/website/src/config/workshop-session-state.test.ts b/apps/website/src/config/workshop-session-state.test.ts index bf250dbd3ae..ff806fefbe9 100644 --- a/apps/website/src/config/workshop-session-state.test.ts +++ b/apps/website/src/config/workshop-session-state.test.ts @@ -424,4 +424,31 @@ describe('useWorkshopSession', () => { }) ) }) + + it('does not resurrect a torn-down session when a restore resolves after the flag turns off', async () => { + window.localStorage.setItem( + 'workshop:workspace', + JSON.stringify({ uid: 'user-1', workspaceId: 'team-9' }) + ) + let releaseRemint!: (value: unknown) => void + h.remint.mockImplementation( + () => new Promise((resolve) => (releaseRemint = resolve)) + ) + const s = await importFresh() + + h.publish(authenticatedSnapshot()) + await vi.waitFor(() => expect(h.remint).toHaveBeenCalledOnce()) + + h.flag!.value = false + await vi.waitFor(() => expect(s.settled.value).toBe(false)) + + releaseRemint({ status: 'error', code: 'TOKEN_EXCHANGE_FAILED' }) + await Promise.resolve() + await Promise.resolve() + + expect( + s.session.value, + 'a restore the flag flip abandoned must not publish for a lifecycle that no longer owns the outcome' + ).toBeUndefined() + }) }) diff --git a/apps/website/src/config/workshop-session-state.ts b/apps/website/src/config/workshop-session-state.ts index a58eb82d97d..e4bce406859 100644 --- a/apps/website/src/config/workshop-session-state.ts +++ b/apps/website/src/config/workshop-session-state.ts @@ -15,11 +15,13 @@ import { z } from 'zod' import type { User } from 'firebase/auth' -import { computed, effectScope, shallowRef, watch } from 'vue' -import type { EffectScope } from 'vue' +import { computed, shallowRef, watch } from 'vue' +import type { OperationHandle } from '@comfyorg/account/boundedOperation' +import { createBoundedOperation } from '@comfyorg/account/boundedOperation' import type { SessionSnapshot } from '@comfyorg/account/session' import { isPermanentSessionError } from '@comfyorg/account/session' +import { createLifecycleScope } from '@comfyorg/account/vue' import { identifyWorkshopUser, useWorkshopAuthFlag } from '../scripts/posthog' import { @@ -39,10 +41,9 @@ const PENDING: SessionSnapshot = { } const snapshot = shallowRef>(PENDING) -let started = false let running = false -let lifecycle: EffectScope | undefined -let generation = 0 +const lifecycle = createLifecycleScope() +const operation = createBoundedOperation() let detachIdentity: (() => void) | undefined let stopSnapshot: (() => void) | undefined let stopTelemetry: (() => void) | undefined @@ -168,7 +169,7 @@ async function settleFailedWorkspaceRestore( async function restoreRememberedWorkspace( next: AuthenticatedSnapshot, remembered: string, - restoreGeneration: number + attempt: OperationHandle ): Promise { let result: Awaited> try { @@ -179,7 +180,7 @@ async function restoreRememberedWorkspace( } catch { return } - if (result?.status !== 'error' || generation !== restoreGeneration) return + if (result?.status !== 'error' || !attempt.live()) return await settleFailedWorkspaceRestore(next, isPermanentSessionError(result.code)) } @@ -206,14 +207,13 @@ function holdsForRestore(next: SessionSnapshot): boolean { restoredForUid = uid const remembered = rememberedWorkspace(uid) if (!remembered || remembered === workspace.id) return false - const restoreGeneration = generation - void restoreRememberedWorkspace(next, remembered, restoreGeneration) + void restoreRememberedWorkspace(next, remembered, operation.capture()) return true } -async function begin(expectedGeneration: number): Promise { +async function begin(attempt: OperationHandle): Promise { const firebase = await import('./workshop-firebase') - if (generation !== expectedGeneration) return + if (!attempt.live()) return running = true stopSnapshot = workshopSessionClient.subscribe((next) => { @@ -237,18 +237,14 @@ async function begin(expectedGeneration: number): Promise { } function start(): void { - if (started || typeof window === 'undefined') return - started = true - // This detached scope gives the module singleton its own lifetime instead - // of binding its watcher to whichever component calls this first. - lifecycle = effectScope(true) - const enabled = useWorkshopAuthFlag() - lifecycle.run(() => { + lifecycle.start(() => { + const enabled = useWorkshopAuthFlag() watch( enabled, (on) => { if (on && running) return - const expectedGeneration = ++generation + operation.abandon() + const attempt = operation.capture() stopListeners() snapshot.value = PENDING if (!on) { @@ -256,15 +252,13 @@ function start(): void { workshopSessionClient.clearStoredCredential() return } - void begin(expectedGeneration).catch((error: unknown) => { - if (generation !== expectedGeneration) return + void begin(attempt).catch((error: unknown) => { + if (!attempt.live()) return console.error('Workshop auth initialization failed', error) // Nothing half-installed survives, and the latch opens again so // the next caller retries instead of waiting out the timeout. stopListeners() - lifecycle?.stop() - lifecycle = undefined - started = false + lifecycle.stop() }) }, { immediate: true } From 29edccc05c99cc481d5c5d8da5ce2d62cf0133a8 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Mon, 14 Sep 2026 18:42:43 +0530 Subject: [PATCH 2/6] test(website): await a deferred remint-started signal instead of a mock call count --- .../src/config/workshop-session-state.test.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/website/src/config/workshop-session-state.test.ts b/apps/website/src/config/workshop-session-state.test.ts index ff806fefbe9..b9b566926e4 100644 --- a/apps/website/src/config/workshop-session-state.test.ts +++ b/apps/website/src/config/workshop-session-state.test.ts @@ -430,14 +430,22 @@ describe('useWorkshopSession', () => { 'workshop:workspace', JSON.stringify({ uid: 'user-1', workspaceId: 'team-9' }) ) + let signalRemintStarted!: () => void + const remintStarted = new Promise((resolve) => { + signalRemintStarted = resolve + }) let releaseRemint!: (value: unknown) => void h.remint.mockImplementation( - () => new Promise((resolve) => (releaseRemint = resolve)) + () => + new Promise((resolve) => { + signalRemintStarted() + releaseRemint = resolve + }) ) const s = await importFresh() h.publish(authenticatedSnapshot()) - await vi.waitFor(() => expect(h.remint).toHaveBeenCalledOnce()) + await remintStarted h.flag!.value = false await vi.waitFor(() => expect(s.settled.value).toBe(false)) From 1637defb52387228ebf3d2aaef128ea1db790a91 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Tue, 15 Sep 2026 11:23:10 +0530 Subject: [PATCH 3/6] fix(website): abandon the operation on failed workshop begin The error-catch teardown tore down listeners and the scope but never abandoned the operation, so a workspace restore captured synchronously inside begin (the subscribe callback fires before begin's later awaits) could still resolve and publish. Abandon it there, matching the flag-off path. --- apps/website/src/config/workshop-session-state.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/website/src/config/workshop-session-state.ts b/apps/website/src/config/workshop-session-state.ts index e4bce406859..a0e85c65b9f 100644 --- a/apps/website/src/config/workshop-session-state.ts +++ b/apps/website/src/config/workshop-session-state.ts @@ -255,8 +255,10 @@ function start(): void { void begin(attempt).catch((error: unknown) => { if (!attempt.live()) return console.error('Workshop auth initialization failed', error) - // Nothing half-installed survives, and the latch opens again so - // the next caller retries instead of waiting out the timeout. + // Nothing half-installed survives: abandon invalidates a restore + // captured before begin threw, and the latch reopens so the next + // caller retries instead of waiting out the timeout. + operation.abandon() stopListeners() lifecycle.stop() }) From f2760ad4148fc125f8631f009f8806cc5f15ce47 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Tue, 15 Sep 2026 14:16:30 +0530 Subject: [PATCH 4/6] test(website): narrow the workshop auth flag instead of asserting non-null --- apps/website/src/config/workshop-session-state.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/website/src/config/workshop-session-state.test.ts b/apps/website/src/config/workshop-session-state.test.ts index b9b566926e4..28960af5433 100644 --- a/apps/website/src/config/workshop-session-state.test.ts +++ b/apps/website/src/config/workshop-session-state.test.ts @@ -447,7 +447,9 @@ describe('useWorkshopSession', () => { h.publish(authenticatedSnapshot()) await remintStarted - h.flag!.value = false + const flag = h.flag + if (!flag) throw new Error('workshop auth flag was not initialized') + flag.value = false await vi.waitFor(() => expect(s.settled.value).toBe(false)) releaseRemint({ status: 'error', code: 'TOKEN_EXCHANGE_FAILED' }) From 3c248a6978e350d5edf78a71d098c6178e878e77 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Tue, 15 Sep 2026 16:50:20 +0530 Subject: [PATCH 5/6] test(website): prove begin's failure abandons an in-flight workspace restore Seed a differing remembered workspace so the synchronous authenticated emit captures a restore handle mid-begin, then throw from attachIdentity. Without the catch's operation.abandon() the settled re-mint republishes the held boot session; the test now fails when that line is removed. --- .../workshop-session-state.failure.test.ts | 92 ++++++++++++++++--- 1 file changed, 77 insertions(+), 15 deletions(-) diff --git a/apps/website/src/config/workshop-session-state.failure.test.ts b/apps/website/src/config/workshop-session-state.failure.test.ts index 18d61b7f7ab..c554548e165 100644 --- a/apps/website/src/config/workshop-session-state.failure.test.ts +++ b/apps/website/src/config/workshop-session-state.failure.test.ts @@ -1,8 +1,20 @@ -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { WorkshopSession } from './workshop-session-state' + +const SIGNED_OUT = { + phase: 'signed-out', + user: null, + session: undefined, + settled: false +} as const const h = vi.hoisted(() => ({ attachIdentity: vi.fn<() => () => void>(), - subscribers: new Set<(snapshot: unknown) => void>() + remint: vi.fn(), + subscribers: new Set<(snapshot: unknown) => void>(), + emit: undefined as unknown, + live: undefined as unknown })) vi.mock(import('../scripts/posthog'), async () => { @@ -28,29 +40,44 @@ vi.mock(import('./workshop-account'), () => ({ workshopSessionClient: { subscribe: (listener: (snapshot: unknown) => void) => { h.subscribers.add(listener) - listener({ - phase: 'signed-out', - user: null, - session: undefined, - settled: false - }) + listener(h.emit) return () => h.subscribers.delete(listener) }, attachIdentity: h.attachIdentity, ensureFresh: vi.fn(), - remint: vi.fn(), + remint: h.remint, clearStoredCredential: vi.fn(), - getSnapshot: () => ({ - phase: 'signed-out', - user: null, - session: undefined, - settled: false - }), + getSnapshot: () => h.live, getToken: vi.fn() }, subscribeAuthRefreshTelemetry: () => () => undefined })) +const bootSession: WorkshopSession = { + token: 'jwt', + permissions: ['workspace:read'], + expiresAt: Date.now() + 3_600_000, + uid: 'user-1', + workspace: { id: 'ws', name: 'Personal', type: 'personal' }, + role: 'owner' +} + +const authenticated = { + phase: 'authenticated', + user: { uid: 'user-1' }, + session: bootSession +} + +beforeEach(() => { + vi.resetModules() + window.localStorage.removeItem('workshop:workspace') + h.subscribers.clear() + h.attachIdentity.mockReset() + h.remint.mockReset() + h.emit = SIGNED_OUT + h.live = SIGNED_OUT +}) + describe('useWorkshopSession initialization failure', () => { it('cleans up and retries on the next use instead of latching the failure', async () => { h.attachIdentity @@ -79,4 +106,39 @@ describe('useWorkshopSession initialization failure', () => { expect(h.subscribers.size).toBe(1) errorSpy.mockRestore() }) + + it('abandons an in-flight workspace restore captured before begin threw', async () => { + // A remembered workspace that differs from the boot session makes the + // synchronous authenticated emit capture a restore handle mid-begin. + window.localStorage.setItem( + 'workshop:workspace', + JSON.stringify({ uid: 'user-1', workspaceId: 'team-9' }) + ) + h.emit = authenticated + h.live = authenticated + let finishRestore!: (value: { status: string; code: string }) => void + h.remint.mockImplementation( + () => new Promise((resolve) => (finishRestore = resolve)) + ) + h.attachIdentity.mockImplementation(() => { + throw new Error('attach exploded') + }) + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const mod = await import('./workshop-session-state') + + const s = mod.useWorkshopSession() + await vi.waitFor(() => expect(h.remint).toHaveBeenCalledOnce()) + await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledOnce()) + + // The restore's re-mint settles only now, after begin threw and abandoned. + finishRestore({ status: 'error', code: 'TOKEN_EXCHANGE_FAILED' }) + await new Promise((resolve) => setTimeout(resolve)) + + expect( + s.session.value, + 'a restore captured before begin threw must not publish after teardown' + ).toBeUndefined() + expect(s.signedIn.value).toBe(false) + errorSpy.mockRestore() + }) }) From fbb8684b31081fe9d82d98f3bc3f7f16a1ba0601 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Tue, 15 Sep 2026 16:54:08 +0530 Subject: [PATCH 6/6] test(website): give the failure-test mocks descriptive names --- .../workshop-session-state.failure.test.ts | 62 +++++++++---------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/apps/website/src/config/workshop-session-state.failure.test.ts b/apps/website/src/config/workshop-session-state.failure.test.ts index c554548e165..f8bc882061e 100644 --- a/apps/website/src/config/workshop-session-state.failure.test.ts +++ b/apps/website/src/config/workshop-session-state.failure.test.ts @@ -9,12 +9,12 @@ const SIGNED_OUT = { settled: false } as const -const h = vi.hoisted(() => ({ +const mocks = vi.hoisted(() => ({ attachIdentity: vi.fn<() => () => void>(), remint: vi.fn(), subscribers: new Set<(snapshot: unknown) => void>(), - emit: undefined as unknown, - live: undefined as unknown + emittedSnapshot: undefined as unknown, + liveSnapshot: undefined as unknown })) vi.mock(import('../scripts/posthog'), async () => { @@ -39,15 +39,15 @@ vi.mock(import('./workshop-firebase'), async () => { vi.mock(import('./workshop-account'), () => ({ workshopSessionClient: { subscribe: (listener: (snapshot: unknown) => void) => { - h.subscribers.add(listener) - listener(h.emit) - return () => h.subscribers.delete(listener) + mocks.subscribers.add(listener) + listener(mocks.emittedSnapshot) + return () => mocks.subscribers.delete(listener) }, - attachIdentity: h.attachIdentity, + attachIdentity: mocks.attachIdentity, ensureFresh: vi.fn(), - remint: h.remint, + remint: mocks.remint, clearStoredCredential: vi.fn(), - getSnapshot: () => h.live, + getSnapshot: () => mocks.liveSnapshot, getToken: vi.fn() }, subscribeAuthRefreshTelemetry: () => () => undefined @@ -62,7 +62,7 @@ const bootSession: WorkshopSession = { role: 'owner' } -const authenticated = { +const authenticatedSnapshot = { phase: 'authenticated', user: { uid: 'user-1' }, session: bootSession @@ -71,39 +71,39 @@ const authenticated = { beforeEach(() => { vi.resetModules() window.localStorage.removeItem('workshop:workspace') - h.subscribers.clear() - h.attachIdentity.mockReset() - h.remint.mockReset() - h.emit = SIGNED_OUT - h.live = SIGNED_OUT + mocks.subscribers.clear() + mocks.attachIdentity.mockReset() + mocks.remint.mockReset() + mocks.emittedSnapshot = SIGNED_OUT + mocks.liveSnapshot = SIGNED_OUT }) describe('useWorkshopSession initialization failure', () => { it('cleans up and retries on the next use instead of latching the failure', async () => { - h.attachIdentity + mocks.attachIdentity .mockImplementationOnce(() => { throw new Error('attach exploded') }) .mockImplementation(() => () => undefined) const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const mod = await import('./workshop-session-state') + const sessionModule = await import('./workshop-session-state') - mod.useWorkshopSession() + sessionModule.useWorkshopSession() await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledOnce()) expect( - h.subscribers.size, + mocks.subscribers.size, 'a partial subscription from the failed attempt must not stay installed' ).toBe(0) - mod.useWorkshopSession() + sessionModule.useWorkshopSession() await vi.waitFor(() => expect( - h.attachIdentity, + mocks.attachIdentity, 'the latch must reopen so a later caller retries the attachment' ).toHaveBeenCalledTimes(2) ) - expect(h.subscribers.size).toBe(1) + expect(mocks.subscribers.size).toBe(1) errorSpy.mockRestore() }) @@ -114,20 +114,20 @@ describe('useWorkshopSession initialization failure', () => { 'workshop:workspace', JSON.stringify({ uid: 'user-1', workspaceId: 'team-9' }) ) - h.emit = authenticated - h.live = authenticated + mocks.emittedSnapshot = authenticatedSnapshot + mocks.liveSnapshot = authenticatedSnapshot let finishRestore!: (value: { status: string; code: string }) => void - h.remint.mockImplementation( + mocks.remint.mockImplementation( () => new Promise((resolve) => (finishRestore = resolve)) ) - h.attachIdentity.mockImplementation(() => { + mocks.attachIdentity.mockImplementation(() => { throw new Error('attach exploded') }) const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - const mod = await import('./workshop-session-state') + const sessionModule = await import('./workshop-session-state') - const s = mod.useWorkshopSession() - await vi.waitFor(() => expect(h.remint).toHaveBeenCalledOnce()) + const session = sessionModule.useWorkshopSession() + await vi.waitFor(() => expect(mocks.remint).toHaveBeenCalledOnce()) await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledOnce()) // The restore's re-mint settles only now, after begin threw and abandoned. @@ -135,10 +135,10 @@ describe('useWorkshopSession initialization failure', () => { await new Promise((resolve) => setTimeout(resolve)) expect( - s.session.value, + session.session.value, 'a restore captured before begin threw must not publish after teardown' ).toBeUndefined() - expect(s.signedIn.value).toBe(false) + expect(session.signedIn.value).toBe(false) errorSpy.mockRestore() }) })