From 533792911732caa61fc82451be38603d85a7dd65 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 13 Sep 2026 21:55:47 +0000 Subject: [PATCH 1/2] refactor: make refresh results represent valid states Amp-Thread-ID: https://ampcode.com/threads/T-01a09a73-1b67-70f6-8958-8a1832bbb241 Co-authored-by: Amp --- packages/account/src/core/refreshScheduler.ts | 12 ++-- .../src/core/session.scheduler.test.ts | 68 ++++++++++++------- packages/account/src/core/session.ts | 1 + packages/account/src/core/sessionContracts.ts | 37 ++++++---- .../workspace/stores/workspaceAuthStore.ts | 17 ++--- 5 files changed, 83 insertions(+), 52 deletions(-) diff --git a/packages/account/src/core/refreshScheduler.ts b/packages/account/src/core/refreshScheduler.ts index b8df7fdd08d..7e727eaedd9 100644 --- a/packages/account/src/core/refreshScheduler.ts +++ b/packages/account/src/core/refreshScheduler.ts @@ -247,7 +247,7 @@ export function createRefreshScheduler( const committed = host.commitExpired(expiring) if (!committed) return stopScheduledRefresh() - reportOutcome?.('expired', committed) + reportOutcome?.({ outcome: 'expired', failure: committed }) }, Math.max(0, expiring.expiresAt - now) ) @@ -279,18 +279,18 @@ export function createRefreshScheduler( if (result.status === 'ok') { const rejected = host.commitRefreshed(result.session) if (rejected) { - reportOutcome?.('permanent_failure', rejected) + reportOutcome?.({ outcome: 'permanent_failure', failure: rejected }) return } clearExpiry() armScheduledRefresh(result.session.expiresAt, host.now()) publishToSiblings(result.session) - reportOutcome?.('succeeded') + reportOutcome?.({ outcome: 'succeeded' }) return } if (isPermanentSessionError(result.code)) { host.commitPermanentFailure(result) - reportOutcome?.('permanent_failure', result) + reportOutcome?.({ outcome: 'permanent_failure', failure: result }) return } if (scheduledRetryCount >= maxRetries) { @@ -301,7 +301,7 @@ export function createRefreshScheduler( // adopt what that sibling mints or be promoted back if nobody does. teardownCoordination() ensureCoordination() - reportOutcome?.('retries_exhausted') + reportOutcome?.({ outcome: 'retries_exhausted' }) return } const delay = retryBaseMs * 2 ** scheduledRetryCount @@ -311,7 +311,7 @@ export function createRefreshScheduler( scheduledTimer = undefined void runScheduledRefresh() }, delay) - reportOutcome?.('retry_scheduled') + reportOutcome?.({ outcome: 'retry_scheduled' }) } return { diff --git a/packages/account/src/core/session.scheduler.test.ts b/packages/account/src/core/session.scheduler.test.ts index 46b1b1c695a..7126d3b0fb5 100644 --- a/packages/account/src/core/session.scheduler.test.ts +++ b/packages/account/src/core/session.scheduler.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest' import type { AccountCredential, @@ -6,6 +6,7 @@ import type { CredentialStorage, CrossTabRefreshPort, SessionClientOptions, + SessionRefreshResult, SessionSnapshot } from './session.js' import { createTestIdentity } from '../testing.js' @@ -73,6 +74,20 @@ beforeEach(() => { }) describe('opt-in refresh scheduler', () => { + it('represents only valid scheduled refresh results', () => { + expectTypeOf<{ + outcome: 'permanent_failure' + }>().not.toMatchTypeOf() + expectTypeOf<{ + outcome: 'succeeded' + failure: { status: 'error'; code: 'TOKEN_EXCHANGE_FAILED' } + }>().not.toMatchTypeOf() + expectTypeOf<{ + outcome: 'expired' + failure: { status: 'error'; code: 'TOKEN_EXCHANGE_FAILED' } + }>().toMatchTypeOf() + }) + it('arms a refresh at expiry minus the buffer and re-mints through the same snapshot', async () => { let minted = 0 const fetchImpl = vi.fn(async () => @@ -134,7 +149,7 @@ describe('opt-in refresh scheduler', () => { const client = makeClient({ fetchImpl, refreshScheduler: { - onScheduledOutcome: (outcome) => outcomes.push(outcome) + onScheduledOutcome: ({ outcome }) => outcomes.push(outcome) } }) const identity = manualIdentity() @@ -311,7 +326,7 @@ describe('opt-in refresh scheduler', () => { }) it('reports each scheduled outcome to the host hook, and only scheduled ones', async () => { - const outcomes: string[] = [] + const results: SessionRefreshResult[] = [] const fetchImpl = vi .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) @@ -321,7 +336,7 @@ describe('opt-in refresh scheduler', () => { const client = makeClient({ fetchImpl, refreshScheduler: { - onScheduledOutcome: (outcome) => outcomes.push(outcome) + onScheduledOutcome: (result) => results.push(result) } }) const identity = manualIdentity() @@ -332,26 +347,32 @@ describe('opt-in refresh scheduler', () => { expect(client.getToken()).toBe('jwt-1') }) expect( - outcomes, + results, 'the login mint is not a scheduled refresh; cloud does not track it' ).toEqual([]) await vi.advanceTimersByTimeAsync( NINETY_MINUTES_MS - DEFAULT_BUFFER_MS + 10 ) - expect(outcomes).toEqual(['retry_scheduled']) + expect(results).toEqual([{ outcome: 'retry_scheduled' }]) await vi.advanceTimersByTimeAsync(5000 + 10) - expect(outcomes).toEqual(['retry_scheduled', 'succeeded']) + expect(results).toEqual([ + { outcome: 'retry_scheduled' }, + { outcome: 'succeeded' } + ]) await vi.advanceTimersByTimeAsync(NINETY_MINUTES_MS * 10) - expect(outcomes).toEqual([ - 'retry_scheduled', - 'succeeded', - 'retry_scheduled', - 'retry_scheduled', - 'retry_scheduled', - 'retries_exhausted', - 'expired' + expect(results).toEqual([ + { outcome: 'retry_scheduled' }, + { outcome: 'succeeded' }, + { outcome: 'retry_scheduled' }, + { outcome: 'retry_scheduled' }, + { outcome: 'retry_scheduled' }, + { outcome: 'retries_exhausted' }, + { + outcome: 'expired', + failure: { status: 'error', code: 'TOKEN_EXCHANGE_FAILED' } + } ]) }) @@ -364,8 +385,7 @@ describe('opt-in refresh scheduler', () => { const client = makeClient({ fetchImpl, refreshScheduler: { - onScheduledOutcome: (outcome, failure) => - reported.push([outcome, failure]) + onScheduledOutcome: (result) => reported.push(result) } }) const identity = manualIdentity() @@ -377,10 +397,10 @@ describe('opt-in refresh scheduler', () => { await vi.advanceTimersByTimeAsync(NINETY_MINUTES_MS) - expect(reported.at(-1)).toEqual([ - 'permanent_failure', - { status: 'error', code: 'ACCESS_DENIED', httpStatus: 403 } - ]) + expect(reported.at(-1)).toEqual({ + outcome: 'permanent_failure', + failure: { status: 'error', code: 'ACCESS_DENIED', httpStatus: 403 } + }) }) it('reports a permanent scheduled failure to the host hook', async () => { @@ -392,7 +412,7 @@ describe('opt-in refresh scheduler', () => { const client = makeClient({ fetchImpl, refreshScheduler: { - onScheduledOutcome: (outcome) => outcomes.push(outcome) + onScheduledOutcome: ({ outcome }) => outcomes.push(outcome) } }) const identity = manualIdentity() @@ -769,7 +789,7 @@ describe('cross-tab refresh coordination', () => { fetchImpl, refreshScheduler: { crossTab: { port }, - onScheduledOutcome: (outcome) => outcomes.push(outcome) + onScheduledOutcome: ({ outcome }) => outcomes.push(outcome) } }) const identity = manualIdentity() @@ -936,7 +956,7 @@ describe('cross-tab refresh coordination', () => { fetchImpl, refreshScheduler: { crossTab: { port }, - onScheduledOutcome: (outcome) => outcomes.push(outcome) + onScheduledOutcome: ({ outcome }) => outcomes.push(outcome) } }) const identity = manualIdentity() diff --git a/packages/account/src/core/session.ts b/packages/account/src/core/session.ts index 8612c36a576..957678fb278 100644 --- a/packages/account/src/core/session.ts +++ b/packages/account/src/core/session.ts @@ -49,6 +49,7 @@ export type { SessionErrorCode, SessionFailure, SessionRefreshOutcome, + SessionRefreshResult, SessionResult } from './sessionContracts.js' export { isPermanentSessionError } from './sessionContracts.js' diff --git a/packages/account/src/core/sessionContracts.ts b/packages/account/src/core/sessionContracts.ts index faeb1c21758..04e5703b16a 100644 --- a/packages/account/src/core/sessionContracts.ts +++ b/packages/account/src/core/sessionContracts.ts @@ -50,14 +50,6 @@ export function isPermanentSessionError(code: SessionErrorCode): boolean { return PERMANENT_ERROR_CODES.has(code) } -export type SessionRefreshOutcome = - | 'succeeded' - | 'retry_scheduled' - | 'retries_exhausted' - | 'permanent_failure' - /** The credential reached its expiry after retries ran out; the client failed closed. */ - | 'expired' - export type SessionResult = | { readonly status: 'ok'; readonly session: AccountCredential } | { @@ -69,6 +61,30 @@ export type SessionResult = export type SessionFailure = Extract +export type SessionRefreshResult = + | { + readonly outcome: 'succeeded' + readonly failure?: never + } + | { + readonly outcome: 'retry_scheduled' + readonly failure?: never + } + | { + readonly outcome: 'retries_exhausted' + readonly failure?: never + } + | { + readonly outcome: 'permanent_failure' + readonly failure: SessionFailure + } + | { + readonly outcome: 'expired' + readonly failure: SessionFailure + } + +export type SessionRefreshOutcome = SessionRefreshResult['outcome'] + export interface MintHandle { readonly mintId: number readonly response: Promise @@ -131,8 +147,5 @@ export interface RefreshSchedulerOptions { * expiry carry the failure the client committed, so the host never has * to read it back out of the snapshot. */ - readonly onScheduledOutcome?: ( - outcome: SessionRefreshOutcome, - failure?: SessionFailure - ) => void + readonly onScheduledOutcome?: (result: SessionRefreshResult) => void } diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index 62ef01e3dc9..3092a42209f 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -7,7 +7,7 @@ import { fromZodError } from 'zod-validation-error' import type { SessionErrorCode, - SessionFailure + SessionRefreshResult } from '@comfyorg/account/session' import { createWebCrossTabRefreshPort } from '@comfyorg/account/web' import { @@ -791,11 +791,8 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { ) } - function handleScheduledRefreshOutcome( - outcome: UnifiedAuthRefreshOutcome, - scheduledFailure?: SessionFailure - ): void { - if (outcome === 'succeeded') { + function handleScheduledRefreshOutcome(result: SessionRefreshResult): void { + if (result.outcome === 'succeeded') { unifiedScheduledRetryCount = 0 // Only re-mints rotate the session cookie; the initial login mint and // workspace switches establish it themselves. @@ -803,20 +800,20 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { trackUnifiedRefresh('succeeded') return } - if (outcome === 'retry_scheduled') { + if (result.outcome === 'retry_scheduled') { unifiedScheduledRetryCount += 1 trackUnifiedRefresh('retry_scheduled') console.warn('Unified token refresh failed; retrying shortly') return } - if (outcome === 'retries_exhausted') { + if (result.outcome === 'retries_exhausted') { trackUnifiedRefresh('retries_exhausted') console.warn( 'Unified token refresh failed; retries exhausted, the session ends at expiry unless a reactive re-mint lands first' ) return } - if (outcome === 'expired') { + if (result.outcome === 'expired') { // The legacy rail's clear-at-expiry: nothing refreshed the token in // time, so the workspace session ends rather than serving a dead JWT. trackUnifiedRefresh('expired') @@ -824,7 +821,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { return } trackUnifiedRefresh('permanent_failure') - const code = scheduledFailure?.code ?? 'TOKEN_EXCHANGE_FAILED' + const code = result.failure.code surfaceUnifiedPermanentFailure(code) endWorkspaceSession( unifiedSelectionInvalid(code) From ae357ee1f4ec0ba27b232d9902aec3efeecec447 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 00:26:06 +0000 Subject: [PATCH 2/2] refactor(account): make the invalid scheduled-refresh report unrepresentable The union named which outcomes carry a failure but did not stop one being attached to an outcome that should not have it. Excess-property checking rejected a bad object literal, so every producer in refreshScheduler.ts was already covered, but a report built in a variable or returned from a helper assigned cleanly. Restore failure?: never on the three non-failure variants, which is what the contract comment's 'structurally cannot' already claimed. Cover the path the existing test could not reach: its successWithFailure case is an object literal, so it passes with or without the guard. --- .../account/src/core/session.scheduler.test.ts | 14 ++++++++++++++ packages/account/src/core/sessionContracts.ts | 11 ++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/account/src/core/session.scheduler.test.ts b/packages/account/src/core/session.scheduler.test.ts index 2d9bb8c8afb..4aa9a3731d1 100644 --- a/packages/account/src/core/session.scheduler.test.ts +++ b/packages/account/src/core/session.scheduler.test.ts @@ -443,6 +443,20 @@ describe('opt-in refresh scheduler', () => { ).toEqual(['ACCESS_DENIED', 'permanent_failure', 'succeeded']) }) + it('rejects a success carrying a failure that reaches the contract through a variable', () => { + const builtElsewhere = { + outcome: 'succeeded' as const, + failure: { status: 'error' as const, code: 'ACCESS_DENIED' as const } + } + // @ts-expect-error a success cannot carry a failure payload + const laundered: ScheduledRefreshReport = builtElsewhere + + expect( + laundered.outcome, + 'the @ts-expect-error above is the coverage, and only failure?: never earns it; excess-property checking accepts an invalid report once it is no longer a fresh object literal' + ).toBe('succeeded') + }) + it('reports a permanent scheduled failure to the host hook', async () => { const outcomes: string[] = [] const fetchImpl = vi diff --git a/packages/account/src/core/sessionContracts.ts b/packages/account/src/core/sessionContracts.ts index 2ef59584d50..575a558d53c 100644 --- a/packages/account/src/core/sessionContracts.ts +++ b/packages/account/src/core/sessionContracts.ts @@ -66,11 +66,16 @@ export type SessionFailure = Extract * outcomes that committed a failure carry it and the rest structurally cannot, * so a permanent failure without its error — or a success with one — cannot be * represented. + * + * `failure?: never` is what makes "structurally cannot" true rather than + * aspirational. Without it, excess-property checking still rejects a bad + * object literal, but a report built in a variable or returned from a helper + * assigns cleanly. */ export type ScheduledRefreshReport = - | { readonly outcome: 'succeeded' } - | { readonly outcome: 'retry_scheduled' } - | { readonly outcome: 'retries_exhausted' } + | { readonly outcome: 'succeeded'; readonly failure?: never } + | { readonly outcome: 'retry_scheduled'; readonly failure?: never } + | { readonly outcome: 'retries_exhausted'; readonly failure?: never } | { readonly outcome: 'permanent_failure'; readonly failure: SessionFailure } /** Retries ran out and the credential reached expiry; the client failed closed. */ | { readonly outcome: 'expired'; readonly failure: SessionFailure }