From fc3dfe7db3fe7835b99b235d7acc2efe2cca61f4 Mon Sep 17 00:00:00 2001 From: Ashish Soni Date: Mon, 5 Oct 2026 08:11:29 +0530 Subject: [PATCH 1/3] test(auth): wait on the retry button and retrying assertion in the force-retry gate test --- .../workspace/auth/WorkspaceAuthGate.test.ts | 26 +++++ .../workspace/auth/WorkspaceAuthGate.vue | 12 ++- .../stores/teamWorkspaceStore.test.ts | 37 +++++++- .../workspace/stores/teamWorkspaceStore.ts | 24 ++++- .../__tests__/authTokenPriority.test.ts | 10 +- .../authTokenRemoteOriginFallback.test.ts | 94 +++++++++++++++++++ src/stores/authStore.ts | 8 +- 7 files changed, 200 insertions(+), 11 deletions(-) create mode 100644 src/stores/__tests__/authTokenRemoteOriginFallback.test.ts diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index 11aba74ee40..acdf86d49cc 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -581,6 +581,32 @@ describe('WorkspaceAuthGate', () => { expect(useTeamWorkspaceStore().initialize).toHaveBeenCalledTimes(2) }) + it('passes force to the store retry from the retry button', async () => { + const user = userEvent.setup() + const initialize = vi.mocked(useTeamWorkspaceStore().initialize) + initialize + .mockImplementationOnce(async () => { + Object.assign(useTeamWorkspaceStore(), { initState: 'error' }) + throw new Error('Workspace init failed') + }) + .mockImplementationOnce(async () => { + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + }) + + mountComponent() + const retryButton = await screen.findByRole('button', { + name: 'Try again' + }) + await user.click(retryButton) + + // The boot init is implicit (no options); the retry button must pass + // { force: true } so the store's post-failure cooldown cannot turn the + // click into an instant re-throw of the old error. + await vi.waitFor(() => + expect(initialize).toHaveBeenNthCalledWith(2, { force: true }) + ) + }) + it('keeps the retry action named while retrying', async () => { const user = userEvent.setup() let resolveRetry: (() => void) | undefined diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index c7ef4d69ada..3449fba3cdc 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -106,7 +106,7 @@ function cancelInitialization(): void { backgroundInitializationUserId = undefined } -async function initialize(): Promise { +async function initialize(options?: { forceRetry?: boolean }): Promise { if (!isCloud) { void initializeWorkspacesInBackground() return @@ -168,7 +168,7 @@ async function initialize(): Promise { } } - await initializeWorkspaceMode() + await initializeWorkspaceMode(options?.forceRetry === true) if (generation !== initializationGeneration) return void billingCapabilities.initialize(controller.signal) if (needsUnifiedToken && !workspaceAuthStore.getUnifiedToken()) { @@ -207,7 +207,7 @@ function isRetryableInitializationError(error: unknown): boolean { async function retryInitialization(): Promise { initializationState.value = 'retrying' - await initialize() + await initialize({ forceRetry: true }) } async function handleSignOut(): Promise { @@ -215,7 +215,9 @@ async function handleSignOut(): Promise { await useAuthActions().logout() } -async function initializeWorkspaceMode(): Promise { +async function initializeWorkspaceMode( + forceRetry: boolean = false +): Promise { // Initialize the full workspace store which handles: // - Restoring workspace token from session (fast path for refresh) // - Fetching workspace list @@ -226,7 +228,7 @@ async function initializeWorkspaceMode(): Promise { workspaceStore.initState === 'uninitialized' || workspaceStore.initState === 'error' ) { - await workspaceStore.initialize() + await workspaceStore.initialize({ force: forceRetry }) } if ( workspaceStore.initState !== 'ready' || diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index 54ca6835c47..8f7fccfd678 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -8,7 +8,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' -import { sortWorkspaces, useTeamWorkspaceStore } from './teamWorkspaceStore' +import { + INIT_RETRY_COOLDOWN_MS, + sortWorkspaces, + useTeamWorkspaceStore +} from './teamWorkspaceStore' const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true })) @@ -354,6 +358,14 @@ describe('useTeamWorkspaceStore', () => { await expect(store.initialize()).rejects.toThrow( 'No workspaces available' ) + // The failed init starts a 30s cooldown; a retry inside it rejects + // immediately instead of re-running the full cycle. + await expect(store.initialize()).rejects.toThrow( + 'No workspaces available' + ) + expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(INIT_RETRY_COOLDOWN_MS) await store.initialize() expect(store.initState).toBe('ready') @@ -361,6 +373,29 @@ describe('useTeamWorkspaceStore', () => { expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(2) }) + it('an explicit retry bypasses the cooldown after a failure', async () => { + mockWorkspaceApi.list.mockResolvedValueOnce({ workspaces: [] }) + const store = useTeamWorkspaceStore() + + await expect(store.initialize()).rejects.toThrow( + 'No workspaces available' + ) + // An implicit retry inside the cooldown still rejects immediately... + await expect(store.initialize()).rejects.toThrow( + 'No workspaces available' + ) + expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(1) + + // ...but an explicit retry (e.g. the WorkspaceAuthGate retry button) + // starts a new initialization right away instead of re-throwing the + // old error for the rest of the cooldown. + await store.initialize({ force: true }) + + expect(store.initState).toBe('ready') + expect(store.activeWorkspaceId).toBe(mockPersonalWorkspace.id) + expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(2) + }) + it('can initialize the next user after identity state is reset', async () => { const store = useTeamWorkspaceStore() await store.initialize() diff --git a/src/platform/workspace/stores/teamWorkspaceStore.ts b/src/platform/workspace/stores/teamWorkspaceStore.ts index fd8fc905f61..18e27465219 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.ts @@ -159,6 +159,9 @@ function clearLastWorkspaceId(): void { const MAX_OWNED_WORKSPACES = 10 const MAX_INIT_RETRIES = 3 const BASE_RETRY_DELAY_MS = 1000 +// After a failed init, reject immediate re-init attempts for this long so +// repeated token requests don't each re-run the full retry/backoff cycle. +export const INIT_RETRY_COOLDOWN_MS = 30_000 export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { const initState = ref('uninitialized') @@ -179,6 +182,7 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { let identityGeneration = 0 let initializationPromise: Promise | null = null let pendingWorkspaceSwitch: Promise | null = null + let lastInitFailureAt: number | null = null function isStaleIdentity(generation: number): boolean { return generation !== identityGeneration @@ -447,6 +451,7 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { ) { error.value = e instanceof Error ? e : new Error('Unknown error') initState.value = 'error' + lastInitFailureAt = Date.now() isFetchingWorkspaces.value = false throw e } @@ -466,12 +471,28 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { isFetchingWorkspaces.value = false } - function initialize(): Promise { + function initialize(options?: { force?: boolean }): Promise { if (initializationPromise) return initializationPromise if (initState.value !== 'uninitialized' && initState.value !== 'error') { return Promise.resolve() } + // Cooldown after a failed init: re-running the full retry/backoff cycle + // on every token request would stall each submission behind up to + // MAX_INIT_RETRIES doomed attempts. Reject until the cooldown expires; + // initState stays 'error', so callers fall back to their error path. + // An explicit retry (e.g. the WorkspaceAuthGate retry button) bypasses + // the cooldown: the user decided to retry now, and the gate is already + // showing the error rather than blocking a submission behind a cycle. + if ( + !options?.force && + initState.value === 'error' && + lastInitFailureAt !== null && + Date.now() - lastInitFailureAt < INIT_RETRY_COOLDOWN_MS + ) { + return Promise.reject(error.value ?? new Error('Workspace init failed')) + } + const promise = performInitialization() initializationPromise = promise void promise.then( @@ -1023,6 +1044,7 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { mutableWorkspaceTransitionGeneration.value++ pendingWorkspaceSwitch = null initializationPromise = null + lastInitFailureAt = null initState.value = 'uninitialized' workspaces.value = [] mutableActiveWorkspaceId.value = null diff --git a/src/stores/__tests__/authTokenPriority.test.ts b/src/stores/__tests__/authTokenPriority.test.ts index c3b99ed4188..c6ac0404526 100644 --- a/src/stores/__tests__/authTokenPriority.test.ts +++ b/src/stores/__tests__/authTokenPriority.test.ts @@ -327,15 +327,19 @@ describe('auth token priority chain', () => { expect(mockUser.getIdToken).not.toHaveBeenCalled() }) - it('fails queue authentication closed after workspace initialization errors', async () => { + it('falls back to the Firebase token when workspace initialization errors', async () => { + // On a remote non-Cloud origin the workspaces request is CORS-blocked + // (#17271); queue execution must still carry a credential so the + // backend can resolve the user's personal workspace instead of 401ing. mockDistributionTypes.isCloud = false useTeamWorkspaceStore().initState = 'uninitialized' vi.mocked(useTeamWorkspaceStore().initialize).mockRejectedValue( new Error('Network error') ) - await expect(store.getWorkspaceAuthToken()).resolves.toBeUndefined() - expect(mockUser.getIdToken).not.toHaveBeenCalled() + await expect(store.getWorkspaceAuthToken()).resolves.toBe( + 'firebase-token' + ) expect( vi.mocked(useWorkspaceAuthStore().ensureWorkspaceToken) ).not.toHaveBeenCalled() diff --git a/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts b/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts new file mode 100644 index 00000000000..92d536f64c9 --- /dev/null +++ b/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts @@ -0,0 +1,94 @@ +import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { fromPartial } from '@total-typescript/shoehorn' +import type { User } from 'firebase/auth' +import * as firebaseAuth from 'firebase/auth' +import type { Mock } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { useAuthStore } from '@/stores/authStore' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' + +const { mockDistributionTypes } = vi.hoisted(() => ({ + mockDistributionTypes: { + isCloud: true, + isDesktop: true + } +})) + +vi.mock(import('@/composables/useFeatureFlags')) + +vi.mock(import('firebase/auth')) + +vi.mock(import('@/platform/telemetry')) + +vi.mock(import('@/services/dialogService')) + +vi.mock(import('@/platform/distribution/types'), () => mockDistributionTypes) + +type MockUser = Omit & { + getIdToken: Mock +} + +/** + * Regression coverage for #17271: on a remote non-Cloud origin (e.g. a + * RunPod HTTPS proxy) the browser CORS-blocks GET cloud.comfy.org/api/workspaces, + * so teamWorkspaceStore.initialize() rejects and getWorkspaceAuthToken must + * still hand queue execution a usable credential — the Firebase ID token — + * instead of failing closed and 401ing the backend. + */ +describe('getWorkspaceAuthToken remote-origin workspace init failure', () => { + let store: ReturnType + + const mockUser = fromPartial({ + uid: 'test-user-id', + email: 'test@example.com', + getIdToken: vi.fn().mockResolvedValue('firebase-token') + }) + + beforeEach(() => { + mockDistributionTypes.isCloud = false + stubFirebaseAuthHarness() + const authStateObservers: Array<(user: User | null) => void> = [] + vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( + (_, callback) => { + const observer = callback as (user: User | null) => void + authStateObservers.push(observer) + observer(mockUser) + return vi.fn() + } + ) + store = useAuthStore() + useWorkspaceAuthStore().destroy() + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: null }) + useTeamWorkspaceStore().initState = 'uninitialized' + vi.mocked(useWorkspaceAuthStore().ensureWorkspaceToken).mockResolvedValue( + null + ) + vi.mocked( + useTeamWorkspaceStore().resetForIdentityChange + ).mockImplementation(() => {}) + vi.mocked(useApiKeyAuthStore().getAuthHeader).mockReturnValue(null) + Object.assign(useApiKeyAuthStore(), { isAuthenticated: false }) + mockUser.getIdToken.mockClear() + mockUser.getIdToken.mockResolvedValue('firebase-token') + }) + + it('falls back to the Firebase token when workspace init fails with a network error', async () => { + vi.mocked(useTeamWorkspaceStore().initialize).mockRejectedValue( + new Error('Network Error') + ) + + await expect(store.getWorkspaceAuthToken()).resolves.toBe('firebase-token') + }) + + it('still falls back when a previous boot left the store in the error state', async () => { + useTeamWorkspaceStore().initState = 'error' + vi.mocked(useTeamWorkspaceStore().initialize).mockRejectedValue( + new Error('Network Error') + ) + + await expect(store.getWorkspaceAuthToken()).resolves.toBe('firebase-token') + }) +}) diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index 2320cf5144b..d40e070556f 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -454,7 +454,13 @@ export const useAuthStore = defineStore('auth', () => { try { await teamWorkspaceStore.initialize() } catch { - return undefined + // A remote non-Cloud origin (e.g. a proxied self-hosted instance) + // cannot reach cloud.comfy.org/api/workspaces: the browser blocks the + // cross-origin request, so workspace discovery fails regardless of + // retries. The signed-in user still has a valid Firebase ID token and + // the backend resolves the personal workspace from it, so fall back + // to it rather than sending no credential and 401ing node execution. + return (await getIdToken()) ?? undefined } } From beef7451df144f683a675ec2ab12609dc723b946 Mon Sep 17 00:00:00 2001 From: Ashish Soni Date: Sat, 10 Oct 2026 22:11:27 +0000 Subject: [PATCH 2/3] fix(auth): scope the workspace init cooldown to token requests and guard account switches Addresses the open CodeRabbit findings on this PR: - The 30 s failure cooldown in teamWorkspaceStore.initialize() is now opt-in (honorFailureCooldown). Only getWorkspaceAuthToken uses it, so other callers (agentConsentStore.ensureScope, the auth gate's retry button) keep retrying immediately. This makes the gate's force-retry plumbing unnecessary, so WorkspaceAuthGate is back to its main version. - getWorkspaceAuthToken records the requesting identity before awaiting workspace init. If the account changed meanwhile, it returns no credential instead of falling back to the new account's Firebase token. Tests cover the opt-in cooldown, that the token path opts in, and the account switch during init (fails without the guard). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01M27ZsC9mkQUbZV9d7wqhBK --- .../workspace/auth/WorkspaceAuthGate.test.ts | 26 --------------- .../workspace/auth/WorkspaceAuthGate.vue | 12 +++---- .../stores/teamWorkspaceStore.test.ts | 26 +++++---------- .../workspace/stores/teamWorkspaceStore.ts | 24 +++++++------- .../authTokenRemoteOriginFallback.test.ts | 32 ++++++++++++++++++- src/stores/authStore.ts | 7 +++- 6 files changed, 63 insertions(+), 64 deletions(-) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index acdf86d49cc..11aba74ee40 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -581,32 +581,6 @@ describe('WorkspaceAuthGate', () => { expect(useTeamWorkspaceStore().initialize).toHaveBeenCalledTimes(2) }) - it('passes force to the store retry from the retry button', async () => { - const user = userEvent.setup() - const initialize = vi.mocked(useTeamWorkspaceStore().initialize) - initialize - .mockImplementationOnce(async () => { - Object.assign(useTeamWorkspaceStore(), { initState: 'error' }) - throw new Error('Workspace init failed') - }) - .mockImplementationOnce(async () => { - Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) - }) - - mountComponent() - const retryButton = await screen.findByRole('button', { - name: 'Try again' - }) - await user.click(retryButton) - - // The boot init is implicit (no options); the retry button must pass - // { force: true } so the store's post-failure cooldown cannot turn the - // click into an instant re-throw of the old error. - await vi.waitFor(() => - expect(initialize).toHaveBeenNthCalledWith(2, { force: true }) - ) - }) - it('keeps the retry action named while retrying', async () => { const user = userEvent.setup() let resolveRetry: (() => void) | undefined diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index 3449fba3cdc..c7ef4d69ada 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -106,7 +106,7 @@ function cancelInitialization(): void { backgroundInitializationUserId = undefined } -async function initialize(options?: { forceRetry?: boolean }): Promise { +async function initialize(): Promise { if (!isCloud) { void initializeWorkspacesInBackground() return @@ -168,7 +168,7 @@ async function initialize(options?: { forceRetry?: boolean }): Promise { } } - await initializeWorkspaceMode(options?.forceRetry === true) + await initializeWorkspaceMode() if (generation !== initializationGeneration) return void billingCapabilities.initialize(controller.signal) if (needsUnifiedToken && !workspaceAuthStore.getUnifiedToken()) { @@ -207,7 +207,7 @@ function isRetryableInitializationError(error: unknown): boolean { async function retryInitialization(): Promise { initializationState.value = 'retrying' - await initialize({ forceRetry: true }) + await initialize() } async function handleSignOut(): Promise { @@ -215,9 +215,7 @@ async function handleSignOut(): Promise { await useAuthActions().logout() } -async function initializeWorkspaceMode( - forceRetry: boolean = false -): Promise { +async function initializeWorkspaceMode(): Promise { // Initialize the full workspace store which handles: // - Restoring workspace token from session (fast path for refresh) // - Fetching workspace list @@ -228,7 +226,7 @@ async function initializeWorkspaceMode( workspaceStore.initState === 'uninitialized' || workspaceStore.initState === 'error' ) { - await workspaceStore.initialize({ force: forceRetry }) + await workspaceStore.initialize() } if ( workspaceStore.initState !== 'ready' || diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index 8f7fccfd678..c4158afa2ef 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -358,14 +358,6 @@ describe('useTeamWorkspaceStore', () => { await expect(store.initialize()).rejects.toThrow( 'No workspaces available' ) - // The failed init starts a 30s cooldown; a retry inside it rejects - // immediately instead of re-running the full cycle. - await expect(store.initialize()).rejects.toThrow( - 'No workspaces available' - ) - expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(1) - - await vi.advanceTimersByTimeAsync(INIT_RETRY_COOLDOWN_MS) await store.initialize() expect(store.initState).toBe('ready') @@ -373,26 +365,24 @@ describe('useTeamWorkspaceStore', () => { expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(2) }) - it('an explicit retry bypasses the cooldown after a failure', async () => { + it('rejects opted-in retries during the failure cooldown', async () => { mockWorkspaceApi.list.mockResolvedValueOnce({ workspaces: [] }) const store = useTeamWorkspaceStore() await expect(store.initialize()).rejects.toThrow( 'No workspaces available' ) - // An implicit retry inside the cooldown still rejects immediately... - await expect(store.initialize()).rejects.toThrow( - 'No workspaces available' - ) + // A per-submission token request inside the cooldown rejects at once + // instead of re-running the full retry/backoff cycle. + await expect( + store.initialize({ honorFailureCooldown: true }) + ).rejects.toThrow('No workspaces available') expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(1) - // ...but an explicit retry (e.g. the WorkspaceAuthGate retry button) - // starts a new initialization right away instead of re-throwing the - // old error for the rest of the cooldown. - await store.initialize({ force: true }) + await vi.advanceTimersByTimeAsync(INIT_RETRY_COOLDOWN_MS) + await store.initialize({ honorFailureCooldown: true }) expect(store.initState).toBe('ready') - expect(store.activeWorkspaceId).toBe(mockPersonalWorkspace.id) expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(2) }) diff --git a/src/platform/workspace/stores/teamWorkspaceStore.ts b/src/platform/workspace/stores/teamWorkspaceStore.ts index 18e27465219..47e958acc75 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.ts @@ -159,8 +159,9 @@ function clearLastWorkspaceId(): void { const MAX_OWNED_WORKSPACES = 10 const MAX_INIT_RETRIES = 3 const BASE_RETRY_DELAY_MS = 1000 -// After a failed init, reject immediate re-init attempts for this long so -// repeated token requests don't each re-run the full retry/backoff cycle. +// After a failed init, callers that opt in reject immediate re-init attempts +// for this long so repeated token requests don't each re-run the full +// retry/backoff cycle. export const INIT_RETRY_COOLDOWN_MS = 30_000 export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { @@ -471,21 +472,22 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { isFetchingWorkspaces.value = false } - function initialize(options?: { force?: boolean }): Promise { + function initialize(options?: { + honorFailureCooldown?: boolean + }): Promise { if (initializationPromise) return initializationPromise if (initState.value !== 'uninitialized' && initState.value !== 'error') { return Promise.resolve() } - // Cooldown after a failed init: re-running the full retry/backoff cycle - // on every token request would stall each submission behind up to - // MAX_INIT_RETRIES doomed attempts. Reject until the cooldown expires; - // initState stays 'error', so callers fall back to their error path. - // An explicit retry (e.g. the WorkspaceAuthGate retry button) bypasses - // the cooldown: the user decided to retry now, and the gate is already - // showing the error rather than blocking a submission behind a cycle. + // Opt-in cooldown after a failed init, for per-submission token requests: + // re-running the full retry/backoff cycle on every submission would stall + // each one behind up to MAX_INIT_RETRIES doomed attempts. Reject until the + // cooldown expires; initState stays 'error', so the caller takes its + // fallback path. Other callers (the auth gate's retry button, agent + // consent) keep retrying immediately. if ( - !options?.force && + options?.honorFailureCooldown && initState.value === 'error' && lastInitFailureAt !== null && Date.now() - lastInitFailureAt < INIT_RETRY_COOLDOWN_MS diff --git a/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts b/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts index 92d536f64c9..cb392ba3cc0 100644 --- a/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts +++ b/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts @@ -40,6 +40,7 @@ type MockUser = Omit & { */ describe('getWorkspaceAuthToken remote-origin workspace init failure', () => { let store: ReturnType + let authStateObservers: Array<(user: User | null) => void> const mockUser = fromPartial({ uid: 'test-user-id', @@ -50,7 +51,7 @@ describe('getWorkspaceAuthToken remote-origin workspace init failure', () => { beforeEach(() => { mockDistributionTypes.isCloud = false stubFirebaseAuthHarness() - const authStateObservers: Array<(user: User | null) => void> = [] + authStateObservers = [] vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( (_, callback) => { const observer = callback as (user: User | null) => void @@ -83,6 +84,35 @@ describe('getWorkspaceAuthToken remote-origin workspace init failure', () => { await expect(store.getWorkspaceAuthToken()).resolves.toBe('firebase-token') }) + it('asks the store to honor its failure cooldown', async () => { + vi.mocked(useTeamWorkspaceStore().initialize).mockRejectedValue( + new Error('Network Error') + ) + + await store.getWorkspaceAuthToken() + + expect(useTeamWorkspaceStore().initialize).toHaveBeenCalledWith({ + honorFailureCooldown: true + }) + }) + + it('returns no credential when the account changes during workspace init', async () => { + const otherUser = fromPartial({ + uid: 'other-user-id', + email: 'other@example.com', + getIdToken: vi.fn().mockResolvedValue('other-firebase-token') + }) + vi.mocked(useTeamWorkspaceStore().initialize).mockImplementation( + async () => { + for (const observer of authStateObservers) observer(otherUser) + throw new Error('Network Error') + } + ) + + await expect(store.getWorkspaceAuthToken()).resolves.toBeUndefined() + expect(otherUser.getIdToken).not.toHaveBeenCalled() + }) + it('still falls back when a previous boot left the store in the error state', async () => { useTeamWorkspaceStore().initState = 'error' vi.mocked(useTeamWorkspaceStore().initialize).mockRejectedValue( diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index d40e070556f..f8f84bffb34 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -451,9 +451,14 @@ export const useAuthStore = defineStore('auth', () => { teamWorkspaceStore.initState === 'loading' || teamWorkspaceStore.initState === 'error') ) { + const requestingIdentity = currentUserCredentialIdentity() try { - await teamWorkspaceStore.initialize() + await teamWorkspaceStore.initialize({ honorFailureCooldown: true }) } catch { + // The account may have changed while initialization was in flight; + // never hand this request another account's credential. + if (currentUserCredentialIdentity() !== requestingIdentity) + return undefined // A remote non-Cloud origin (e.g. a proxied self-hosted instance) // cannot reach cloud.comfy.org/api/workspaces: the browser blocks the // cross-origin request, so workspace discovery fails regardless of From c530d00d1cc6a0e9401560fde33d3471aba78372 Mon Sep 17 00:00:00 2001 From: Ashish Soni Date: Sun, 11 Oct 2026 17:27:04 +0000 Subject: [PATCH 3/3] fix(auth): only fall back to the Firebase token when workspace discovery fails Re-check the requesting account after workspace init on the success path too, and limit the Firebase ID token fallback to failures while listing workspaces. A failed workspace switch or token exchange now sends no credential, as before this PR. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01M27ZsC9mkQUbZV9d7wqhBK --- .../stores/teamWorkspaceStore.test.ts | 3 ++ .../workspace/stores/teamWorkspaceStore.ts | 19 ++++++++++ .../__tests__/authTokenPriority.test.ts | 3 ++ .../authTokenRemoteOriginFallback.test.ts | 35 +++++++++++++++++++ src/stores/authStore.ts | 14 +++++--- 5 files changed, 70 insertions(+), 4 deletions(-) diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index c4158afa2ef..fd160d6c4b2 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -319,6 +319,7 @@ describe('useTeamWorkspaceStore', () => { expect(store.error).toBeInstanceOf(Error) // Should have been called 4 times (initial + 3 retries) expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(4) + expect(store.initFailedAtDiscovery()).toBe(true) }) it('does not reinitialize if already initialized', async () => { @@ -465,6 +466,7 @@ describe('useTeamWorkspaceStore', () => { 'No workspaces available' ) expect(store.initState).toBe('error') + expect(store.initFailedAtDiscovery()).toBe(false) }) it('does not activate a workspace when token exchange fails', async () => { @@ -483,6 +485,7 @@ describe('useTeamWorkspaceStore', () => { expect(store.initState).toBe('error') expect(store.activeWorkspaceId).toBeNull() expect(store.error).toEqual(new Error('Token exchange failed')) + expect(store.initFailedAtDiscovery()).toBe(false) }) }) diff --git a/src/platform/workspace/stores/teamWorkspaceStore.ts b/src/platform/workspace/stores/teamWorkspaceStore.ts index 47e958acc75..db86d21ee30 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.ts @@ -184,6 +184,9 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { let initializationPromise: Promise | null = null let pendingWorkspaceSwitch: Promise | null = null let lastInitFailureAt: number | null = null + // Whether the last failed init failed while listing workspaces, before any + // workspace was resolved or activated. + let lastInitFailedAtDiscovery = false function isStaleIdentity(generation: number): boolean { return generation !== identityGeneration @@ -326,6 +329,7 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { const isApiKeySession = useCurrentUser().isApiKeyLogin.value for (let attempt = 0; attempt <= MAX_INIT_RETRIES; attempt++) { + let discovering = false try { // An API-key credential is bound to exactly one workspace on the // server. There is no discovery, switching, or token exchange for it: @@ -351,7 +355,9 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { if (hasValidSession && workspaceAuthStore.currentWorkspace) { // Valid session exists - fetch workspace list and verify access + discovering = true const response = await workspaceApi.list() + discovering = false if (isStaleIdentity(generation)) return workspaces.value = sortWorkspaces( response.workspaces.map(createWorkspaceState) @@ -393,7 +399,9 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { } // 2. No valid session - fetch workspaces and pick default + discovering = true const response = await workspaceApi.list() + discovering = false if (isStaleIdentity(generation)) return workspaces.value = sortWorkspaces( response.workspaces.map(createWorkspaceState) @@ -453,6 +461,7 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { error.value = e instanceof Error ? e : new Error('Unknown error') initState.value = 'error' lastInitFailureAt = Date.now() + lastInitFailedAtDiscovery = discovering isFetchingWorkspaces.value = false throw e } @@ -508,6 +517,14 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { return promise } + /** + * Whether the last failed initialize() failed while listing workspaces, + * as opposed to an empty list, the workspace switch or its token exchange. + */ + function initFailedAtDiscovery(): boolean { + return initState.value === 'error' && lastInitFailedAtDiscovery + } + /** * Re-fetch workspaces from API without changing active workspace. */ @@ -1047,6 +1064,7 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { pendingWorkspaceSwitch = null initializationPromise = null lastInitFailureAt = null + lastInitFailedAtDiscovery = false initState.value = 'uninitialized' workspaces.value = [] mutableActiveWorkspaceId.value = null @@ -1094,6 +1112,7 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { // Initialization & Cleanup initialize, + initFailedAtDiscovery, destroy, resetForIdentityChange, refreshWorkspaces, diff --git a/src/stores/__tests__/authTokenPriority.test.ts b/src/stores/__tests__/authTokenPriority.test.ts index c6ac0404526..261833d30ee 100644 --- a/src/stores/__tests__/authTokenPriority.test.ts +++ b/src/stores/__tests__/authTokenPriority.test.ts @@ -336,6 +336,9 @@ describe('auth token priority chain', () => { vi.mocked(useTeamWorkspaceStore().initialize).mockRejectedValue( new Error('Network error') ) + vi.mocked(useTeamWorkspaceStore().initFailedAtDiscovery).mockReturnValue( + true + ) await expect(store.getWorkspaceAuthToken()).resolves.toBe( 'firebase-token' diff --git a/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts b/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts index cb392ba3cc0..8374eb89eed 100644 --- a/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts +++ b/src/stores/__tests__/authTokenRemoteOriginFallback.test.ts @@ -64,6 +64,9 @@ describe('getWorkspaceAuthToken remote-origin workspace init failure', () => { useWorkspaceAuthStore().destroy() Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: null }) useTeamWorkspaceStore().initState = 'uninitialized' + vi.mocked(useTeamWorkspaceStore().initFailedAtDiscovery).mockReturnValue( + true + ) vi.mocked(useWorkspaceAuthStore().ensureWorkspaceToken).mockResolvedValue( null ) @@ -113,6 +116,38 @@ describe('getWorkspaceAuthToken remote-origin workspace init failure', () => { expect(otherUser.getIdToken).not.toHaveBeenCalled() }) + it('sends no credential when init fails after workspace discovery', async () => { + vi.mocked(useTeamWorkspaceStore().initialize).mockRejectedValue( + new Error('Token exchange failed') + ) + vi.mocked(useTeamWorkspaceStore().initFailedAtDiscovery).mockReturnValue( + false + ) + + await expect(store.getWorkspaceAuthToken()).resolves.toBeUndefined() + expect(mockUser.getIdToken).not.toHaveBeenCalled() + }) + + it('returns no credential when the account changes during a successful init', async () => { + const otherUser = fromPartial({ + uid: 'other-user-id', + email: 'other@example.com', + getIdToken: vi.fn().mockResolvedValue('other-firebase-token') + }) + vi.mocked(useTeamWorkspaceStore().initialize).mockImplementation( + async () => { + for (const observer of authStateObservers) observer(otherUser) + Object.assign(useTeamWorkspaceStore(), { + activeWorkspaceId: 'other-workspace' + }) + } + ) + + await expect(store.getWorkspaceAuthToken()).resolves.toBeUndefined() + expect(useWorkspaceAuthStore().ensureWorkspaceToken).not.toHaveBeenCalled() + expect(otherUser.getIdToken).not.toHaveBeenCalled() + }) + it('still falls back when a previous boot left the store in the error state', async () => { useTeamWorkspaceStore().initState = 'error' vi.mocked(useTeamWorkspaceStore().initialize).mockRejectedValue( diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index f8f84bffb34..1a53a215766 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -452,19 +452,25 @@ export const useAuthStore = defineStore('auth', () => { teamWorkspaceStore.initState === 'error') ) { const requestingIdentity = currentUserCredentialIdentity() + let initFailed = false try { await teamWorkspaceStore.initialize({ honorFailureCooldown: true }) } catch { - // The account may have changed while initialization was in flight; - // never hand this request another account's credential. - if (currentUserCredentialIdentity() !== requestingIdentity) - return undefined + initFailed = true + } + // The account may have changed while initialization was in flight; + // never hand this request another account's credential. + if (currentUserCredentialIdentity() !== requestingIdentity) + return undefined + if (initFailed) { // A remote non-Cloud origin (e.g. a proxied self-hosted instance) // cannot reach cloud.comfy.org/api/workspaces: the browser blocks the // cross-origin request, so workspace discovery fails regardless of // retries. The signed-in user still has a valid Firebase ID token and // the backend resolves the personal workspace from it, so fall back // to it rather than sending no credential and 401ing node execution. + // Any later failure (switch or token exchange) sends no credential. + if (!teamWorkspaceStore.initFailedAtDiscovery()) return undefined return (await getIdToken()) ?? undefined } }