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..f8bc882061e 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' -const h = vi.hoisted(() => ({ +import type { WorkshopSession } from './workshop-session-state' + +const SIGNED_OUT = { + phase: 'signed-out', + user: null, + session: undefined, + settled: false +} as const + +const mocks = vi.hoisted(() => ({ attachIdentity: vi.fn<() => () => void>(), - subscribers: new Set<(snapshot: unknown) => void>() + remint: vi.fn(), + subscribers: new Set<(snapshot: unknown) => void>(), + emittedSnapshot: undefined as unknown, + liveSnapshot: undefined as unknown })) vi.mock(import('../scripts/posthog'), async () => { @@ -27,56 +39,106 @@ vi.mock(import('./workshop-firebase'), async () => { 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 - }) - 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: vi.fn(), + remint: mocks.remint, clearStoredCredential: vi.fn(), - getSnapshot: () => ({ - phase: 'signed-out', - user: null, - session: undefined, - settled: false - }), + getSnapshot: () => mocks.liveSnapshot, 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 authenticatedSnapshot = { + phase: 'authenticated', + user: { uid: 'user-1' }, + session: bootSession +} + +beforeEach(() => { + vi.resetModules() + window.localStorage.removeItem('workshop:workspace') + 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() + }) + + 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' }) + ) + mocks.emittedSnapshot = authenticatedSnapshot + mocks.liveSnapshot = authenticatedSnapshot + let finishRestore!: (value: { status: string; code: string }) => void + mocks.remint.mockImplementation( + () => new Promise((resolve) => (finishRestore = resolve)) + ) + mocks.attachIdentity.mockImplementation(() => { + throw new Error('attach exploded') + }) + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const sessionModule = await import('./workshop-session-state') + + 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. + finishRestore({ status: 'error', code: 'TOKEN_EXCHANGE_FAILED' }) + await new Promise((resolve) => setTimeout(resolve)) + + expect( + session.session.value, + 'a restore captured before begin threw must not publish after teardown' + ).toBeUndefined() + expect(session.signedIn.value).toBe(false) errorSpy.mockRestore() }) }) diff --git a/apps/website/src/config/workshop-session-state.test.ts b/apps/website/src/config/workshop-session-state.test.ts index bf250dbd3ae..28960af5433 100644 --- a/apps/website/src/config/workshop-session-state.test.ts +++ b/apps/website/src/config/workshop-session-state.test.ts @@ -424,4 +424,41 @@ 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 signalRemintStarted!: () => void + const remintStarted = new Promise((resolve) => { + signalRemintStarted = resolve + }) + let releaseRemint!: (value: unknown) => void + h.remint.mockImplementation( + () => + new Promise((resolve) => { + signalRemintStarted() + releaseRemint = resolve + }) + ) + const s = await importFresh() + + h.publish(authenticatedSnapshot()) + await remintStarted + + 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' }) + 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..a0e85c65b9f 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,15 @@ 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. + // 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() - lifecycle = undefined - started = false + lifecycle.stop() }) }, { immediate: true }