Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
114 changes: 88 additions & 26 deletions apps/website/src/config/workshop-session-state.failure.test.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>(import('../scripts/posthog'), async () => {
Expand All @@ -27,56 +39,106 @@ vi.mock<unknown>(import('./workshop-firebase'), async () => {
vi.mock<unknown>(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()
})
})
37 changes: 37 additions & 0 deletions apps/website/src/config/workshop-session-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>((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()
})
})
48 changes: 22 additions & 26 deletions apps/website/src/config/workshop-session-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -39,10 +41,9 @@ const PENDING: SessionSnapshot<User> = {
}

const snapshot = shallowRef<SessionSnapshot<User>>(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
Expand Down Expand Up @@ -168,7 +169,7 @@ async function settleFailedWorkspaceRestore(
async function restoreRememberedWorkspace(
next: AuthenticatedSnapshot,
remembered: string,
restoreGeneration: number
attempt: OperationHandle
): Promise<void> {
let result: Awaited<ReturnType<typeof workshopSessionClient.remint>>
try {
Expand All @@ -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))
}

Expand All @@ -206,14 +207,13 @@ function holdsForRestore(next: SessionSnapshot<User>): 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<void> {
async function begin(attempt: OperationHandle): Promise<void> {
const firebase = await import('./workshop-firebase')
if (generation !== expectedGeneration) return
if (!attempt.live()) return

running = true
stopSnapshot = workshopSessionClient.subscribe((next) => {
Expand All @@ -237,34 +237,30 @@ async function begin(expectedGeneration: number): Promise<void> {
}

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) {
restoredForUid = undefined
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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion (non-blocking): this operation.abandon() is the one line in the PR that is new behavior rather than a rename, and nothing asserts it.

Everything else here maps one-for-one onto the old generation counter, but the old catch did not bump the generation — it only did stopListeners() / lifecycle.stop() / started = false. So the case this now covers is real and previously leaked: begin installs subscribe(...), the client publishes an authenticated snapshot synchronously, holdsForRestore captures a handle, and then a later step in begin (attachIdentity, subscribeAuthRefreshTelemetry) throws — leaving that restore live against a lifecycle that is being torn down.

workshop-session-state.failure.test.ts covers the throw path for the latch-and-cleanup half, but it does not have a remembered workspace in play, so it never captures a restore and would pass with this line deleted.

Given the parsimonious-testing convention I would not ask for a whole new file — but if the existing failure test can be extended to seed workshop:workspace and assert the in-flight restore stays unpublished, that would make this line mutation-killing instead of trusting the comment above it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Extended the existing failure test in 0f55f1c rather than adding a file. The new case seeds workshop:workspace with a differing id, makes subscribe emit an authenticated snapshot synchronously so holdsForRestore captures a restore handle mid-begin, then throws from attachIdentity. A gated re-mint settles only after the catch runs, and the test asserts the held boot session never publishes (session stays undefined). Verified it is mutation-killing: deleting the catch's operation.abandon() turns it red (the settled re-mint republishes the held snapshot), restoring it turns it green.

stopListeners()
lifecycle?.stop()
lifecycle = undefined
started = false
lifecycle.stop()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion (non-blocking): this is the one teardown path that does not abandon the operation, so it cannot enforce the invariant the new test pins.

workshopSessionClient.subscribe() emits synchronously — packages/account/src/core/session.ts:710-713 calls listener(getSnapshot()) before returning — so holdsForRestore can capture a live handle inside begin, before attachIdentity, subscribeAuthRefreshTelemetry, or addEventListener have run. If one of those throws synchronously, begin rejects with that restore still in flight, and this catch runs stopListeners() and lifecycle.stop() while attempt.live() is still true. The restore can then resolve into settleFailedWorkspaceRestore -> publishTransientWorkspaceRestore and republish a session for a lifecycle that was already torn down — the exact thing workshop-session-state.test.ts:471 says must not happen.

To be clear, this is pre-existing and not a regression from this PR: the old catch did not bump generation either, so the behavior is unchanged. I am raising it only because this PR is what makes the fix a one-liner, and because it is the same invariant the PR now documents:

stopListeners()
operation.abandon()
lifecycle.stop()

Entirely reasonable to leave for a follow-up if you would rather keep this PR strictly behavior-preserving — that is a fair call for a refactor stack. Would you prefer that?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed: the error-catch teardown now calls operation.abandon() before stopListeners/lifecycle.stop, so a restore captured synchronously inside begin is invalidated too, matching the flag-off path.

})
},
{ immediate: true }
Expand Down
Loading