From b2f278e7889a93aa22f0e32ba584e08041c5d20e Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 28 Sep 2026 11:04:38 -0700 Subject: [PATCH 1/2] Fix agent gate auth lifecycle (#19219) Closes FE-3060. Follow-up to #19074. --- src/composables/auth/useCurrentUser.ts | 2 + src/composables/useFeatureFlags.ts | 14 +- src/extensions/core/agentPanel.ts | 54 +++-- .../remoteConfig/refreshRemoteConfig.test.ts | 188 +++++++++++++++--- .../remoteConfig/refreshRemoteConfig.ts | 164 +++++++++++---- src/platform/remoteConfig/remoteConfig.ts | 11 +- src/scripts/api.fetchApi.test.ts | 29 +++ src/scripts/api.ts | 11 +- src/stores/authStore.test.ts | 8 +- 9 files changed, 398 insertions(+), 83 deletions(-) diff --git a/src/composables/auth/useCurrentUser.ts b/src/composables/auth/useCurrentUser.ts index 99af552b023..5173eb7f08b 100644 --- a/src/composables/auth/useCurrentUser.ts +++ b/src/composables/auth/useCurrentUser.ts @@ -21,6 +21,7 @@ export const useCurrentUser = () => { const isLoggedIn = computed( () => isApiKeyLogin.value || firebaseUser.value !== null ) + const isAuthInitialized = computed(() => authStore.isInitialized) const resolvedUserInfo = computed(() => { if (isApiKeyLogin.value && apiKeyStore.currentUser) { @@ -118,6 +119,7 @@ export const useCurrentUser = () => { return { loading: authStore.loading, + isAuthInitialized, isLoggedIn, isApiKeyLogin, isEmailProvider, diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index b79b733d881..9fa4c655100 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -8,7 +8,8 @@ import { cachedV1PaymentRecovery, isAuthenticatedConfigLoaded, remoteConfig, - sessionAgentGrant + sessionAgentGrant, + sessionAgentGrantValidUntil } from '@/platform/remoteConfig/remoteConfig' import { useTelemetry } from '@/platform/telemetry' import { api } from '@/scripts/api' @@ -115,7 +116,8 @@ function resolveFailClosedBooleanFlag(flagKey: string): boolean { function resolveWhitelistFlag( flagKey: string, remoteConfigValue: boolean | undefined, - grantedThisSession: Ref + grantedThisSession: Ref, + grantValidUntil: Ref ): boolean { const sessionOverride = getSessionOverride(flagKey) if (sessionOverride !== undefined) return sessionOverride @@ -125,7 +127,10 @@ function resolveWhitelistFlag( if (!isCloud) return false if (!isAuthenticatedConfigLoaded.value) - return grantedThisSession.value === true + return ( + grantedThisSession.value === true && + (grantValidUntil.value ?? 0) > Date.now() + ) return remoteConfigValue === true } @@ -327,7 +332,8 @@ export function useFeatureFlags() { return resolveWhitelistFlag( ServerFeatureFlag.AGENT_IN_APP_EXPERIENCE, remoteConfig.value['agent-in-app-experience'], - sessionAgentGrant + sessionAgentGrant, + sessionAgentGrantValidUntil ) } }) diff --git a/src/extensions/core/agentPanel.ts b/src/extensions/core/agentPanel.ts index 74abfb0a4de..20cab818ccd 100644 --- a/src/extensions/core/agentPanel.ts +++ b/src/extensions/core/agentPanel.ts @@ -5,7 +5,10 @@ import { computed, ref, watch } from 'vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useOnboardingTourStore } from '@/platform/onboarding/onboardingTourStore' -import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' +import { + authenticatedRemoteConfigState, + remoteConfigRevision +} from '@/platform/remoteConfig/remoteConfig' import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' import type { AgentConsentNotOfferedReason } from '@/platform/telemetry/types' @@ -173,7 +176,8 @@ export function registerAgentPanelExtension(): void { const consentStore = useAgentConsentStore() const { enabled } = storeToRefs(agentPanelStore) const workspaceStore = useTeamWorkspaceStore() - const { resolvedUserInfo, isLoggedIn } = useCurrentUser() + const { resolvedUserInfo, isAuthInitialized, isLoggedIn } = + useCurrentUser() const { withConsent } = useAgentConsent() const { firstRunTookScreen, whenStartupDecided } = useFirstRunEntry() const onboardingTourStore = useOnboardingTourStore() @@ -330,20 +334,29 @@ export function registerAgentPanelExtension(): void { loadConsentIfEligible() } ) - setupFlagGate(loadConsentIfEligible) + setupFlagGate( + loadConsentIfEligible, + () => isAuthInitialized.value && resolvedUserInfo.value === null + ) } }) } -function setupFlagGate(loadConsentIfEligible: () => void): void { +function setupFlagGate( + loadConsentIfEligible: () => void, + isSignedOut: () => boolean +): void { const agentPanelStore = useAgentPanelStore() const { flags } = useFeatureFlags() watch( () => - import.meta.env.MODE === 'development' || - flags.agentInAppExperienceEnabled, - (enabled) => { + [ + import.meta.env.MODE === 'development' || + flags.agentInAppExperienceEnabled, + remoteConfigRevision.value + ] as const, + ([enabled]) => { agentPanelStore.enabled = enabled loadConsentIfEligible() if (!enabled) { @@ -358,15 +371,30 @@ function setupFlagGate(loadConsentIfEligible: () => void): void { const settle = (): void => { agentPanelStore.gateSettled = true } + let settleTimer: ReturnType | undefined + const clearSettleTimer = (): void => { + clearTimeout(settleTimer) + settleTimer = undefined + } + const scheduleSignedOutFallback = (): void => { + clearSettleTimer() + settleTimer = setTimeout(() => { + if (isSignedOut()) settle() + }, GATE_SETTLE_TIMEOUT_MS) + } watch( () => - import.meta.env.MODE === 'development' || - remoteConfigState.value === 'authenticated' || - remoteConfigState.value === 'error', - (decided) => { - if (decided) settle() + [ + import.meta.env.MODE === 'development' || + authenticatedRemoteConfigState.value === 'authenticated' || + authenticatedRemoteConfigState.value === 'error', + isSignedOut() + ] as const, + ([decided, signedOut]) => { + agentPanelStore.gateSettled = decided + clearSettleTimer() + if (!decided && signedOut) scheduleSignedOutFallback() }, { immediate: true } ) - setTimeout(settle, GATE_SETTLE_TIMEOUT_MS) } diff --git a/src/platform/remoteConfig/refreshRemoteConfig.test.ts b/src/platform/remoteConfig/refreshRemoteConfig.test.ts index f5692cd3b69..37f9a7c294b 100644 --- a/src/platform/remoteConfig/refreshRemoteConfig.test.ts +++ b/src/platform/remoteConfig/refreshRemoteConfig.test.ts @@ -7,11 +7,14 @@ import { refreshRemoteConfig } from './refreshRemoteConfig' import { + authenticatedRemoteConfigState, cachedLegacyBillingMigrationEnabled, - sessionAgentGrant, remoteConfig, remoteConfigErrorStatus, - remoteConfigState + remoteConfigRevision, + remoteConfigState, + sessionAgentGrant, + sessionAgentGrantValidUntil } from './remoteConfig' vi.mock('@/scripts/api', () => ({ @@ -45,6 +48,13 @@ describe('refreshRemoteConfig', () => { } as Response } + function mockAuthenticatedFetch(response: Response): void { + vi.mocked(api.fetchApi).mockImplementation(async (_route, options) => { + options?.onAuthHeader?.(true) + return response + }) + } + beforeEach(() => { vi.mocked(api.apiURL).mockImplementation( (route: string) => `/ComfyUI/api${route}` @@ -53,8 +63,11 @@ describe('refreshRemoteConfig', () => { remoteConfig.value = {} remoteConfigErrorStatus.value = null remoteConfigState.value = 'unloaded' + authenticatedRemoteConfigState.value = 'unloaded' + remoteConfigRevision.value = 0 cachedLegacyBillingMigrationEnabled.value = undefined sessionAgentGrant.value = undefined + sessionAgentGrantValidUntil.value = undefined window.__CONFIG__ = {} }) @@ -76,11 +89,13 @@ describe('refreshRemoteConfig', () => { }) expect(window.__CONFIG__).toEqual(remoteConfig.value) expect(remoteConfigState.value).toBe('unloaded') + expect(authenticatedRemoteConfigState.value).toBe('unloaded') + expect(sessionAgentGrantValidUntil.value).toBeUndefined() }) describe('with auth (default)', () => { it('uses api.fetchApi when useAuth is true', async () => { - vi.mocked(api.fetchApi).mockResolvedValue(mockSuccessResponse()) + mockAuthenticatedFetch(mockSuccessResponse()) await refreshRemoteConfig({ useAuth: true }) @@ -94,7 +109,7 @@ describe('refreshRemoteConfig', () => { }) it('uses api.fetchApi by default', async () => { - vi.mocked(api.fetchApi).mockResolvedValue(mockSuccessResponse()) + mockAuthenticatedFetch(mockSuccessResponse()) await refreshRemoteConfig() @@ -102,8 +117,45 @@ describe('refreshRemoteConfig', () => { expect(global.fetch).not.toHaveBeenCalled() }) + it('rejects a successful response when no auth header was attached', async () => { + remoteConfig.value = { subscription_required: true } + window.__CONFIG__ = remoteConfig.value + vi.mocked(api.fetchApi).mockImplementation(async (_route, options) => { + options?.onAuthHeader?.(false) + return mockSuccessResponse({ 'agent-in-app-experience': true }) + }) + + await refreshRemoteConfig() + + expect(remoteConfig.value).toEqual({ subscription_required: true }) + expect(authenticatedRemoteConfigState.value).toBe('error') + expect(remoteConfigState.value).toBe('error') + expect(remoteConfigRevision.value).toBe(1) + }) + + it('restores the prior state when the caller cancels the refresh', async () => { + authenticatedRemoteConfigState.value = 'error' + vi.mocked(api.fetchApi).mockImplementation( + (_route, options) => + new Promise((_, reject) => { + options?.signal?.addEventListener('abort', () => { + reject(new DOMException('Aborted', 'AbortError')) + }) + }) + ) + const controller = new AbortController() + + const refresh = refreshRemoteConfig({ signal: controller.signal }) + expect(authenticatedRemoteConfigState.value).toBe('loading') + await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledOnce()) + controller.abort() + await refresh + + expect(authenticatedRemoteConfigState.value).toBe('error') + }) + it('caches authenticated legacy billing migration eligibility', async () => { - vi.mocked(api.fetchApi).mockResolvedValue( + mockAuthenticatedFetch( mockSuccessResponse({ legacy_billing_migration_enabled: true }) ) @@ -113,7 +165,7 @@ describe('refreshRemoteConfig', () => { }) it('passes an AbortSignal on the authenticated branch', async () => { - vi.mocked(api.fetchApi).mockResolvedValue(mockSuccessResponse()) + mockAuthenticatedFetch(mockSuccessResponse()) await refreshRemoteConfig({ useAuth: true }) @@ -125,14 +177,16 @@ describe('refreshRemoteConfig', () => { let resolveFirst: ((response: Response) => void) | undefined vi.mocked(api.fetchApi) .mockImplementationOnce( - () => + (_route, options) => new Promise((resolve) => { + options?.onAuthHeader?.(true) resolveFirst = resolve }) ) - .mockResolvedValueOnce( - mockSuccessResponse({ subscription_required: true }) - ) + .mockImplementationOnce(async (_route, options) => { + options?.onAuthHeader?.(true) + return mockSuccessResponse({ subscription_required: true }) + }) const firstRefresh = refreshRemoteConfig({ useAuth: true }) await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledTimes(1)) @@ -154,6 +208,7 @@ describe('refreshRemoteConfig', () => { vi.mocked(api.fetchApi).mockImplementation( (_route, options) => new Promise((_, reject) => { + options?.onAuthHeader?.(true) if (options?.signal?.aborted) { reject(new DOMException('Aborted', 'AbortError')) return @@ -177,6 +232,25 @@ describe('refreshRemoteConfig', () => { expect(remoteConfigErrorStatus.value).toBe(500) expect(window.__CONFIG__).toEqual(existingConfig) }) + + it('keeps authenticated state settled while polling', async () => { + authenticatedRemoteConfigState.value = 'authenticated' + let resolveRefresh: ((response: Response) => void) | undefined + vi.mocked(api.fetchApi).mockImplementation( + (_route, options) => + new Promise((resolve) => { + options?.onAuthHeader?.(true) + resolveRefresh = resolve + }) + ) + + const refresh = refreshRemoteConfig() + + expect(authenticatedRemoteConfigState.value).toBe('authenticated') + await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledOnce()) + resolveRefresh?.(mockSuccessResponse()) + await refresh + }) }) describe('without auth', () => { @@ -196,6 +270,64 @@ describe('refreshRemoteConfig', () => { expect(window.__CONFIG__).toEqual(mockConfig) expect(cachedLegacyBillingMigrationEnabled.value).toBe(true) }) + + it('clears authenticated state and its grant when anonymous config commits', async () => { + authenticatedRemoteConfigState.value = 'authenticated' + sessionAgentGrant.value = true + sessionAgentGrantValidUntil.value = Date.now() + 60_000 + vi.mocked(global.fetch).mockResolvedValue(mockSuccessResponse()) + + await refreshRemoteConfig({ useAuth: false }) + + expect(authenticatedRemoteConfigState.value).toBe('unloaded') + expect(sessionAgentGrant.value).toBeUndefined() + expect(sessionAgentGrantValidUntil.value).toBeUndefined() + }) + + it('keeps anonymous state after an older authenticated refresh settles', async () => { + authenticatedRemoteConfigState.value = 'error' + let resolveAuthenticated: ((response: Response) => void) | undefined + vi.mocked(api.fetchApi).mockImplementation( + (_route, options) => + new Promise((resolve) => { + options?.onAuthHeader?.(true) + resolveAuthenticated = resolve + }) + ) + vi.mocked(global.fetch).mockResolvedValue(mockSuccessResponse()) + + const authenticatedRefresh = refreshRemoteConfig() + await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledOnce()) + await refreshRemoteConfig({ useAuth: false }) + resolveAuthenticated?.(mockSuccessResponse()) + await authenticatedRefresh + + expect(authenticatedRemoteConfigState.value).toBe('unloaded') + expect(remoteConfigState.value).toBe('anonymous') + }) + + it('does not erase authenticated config or its grant on an anonymous 401', async () => { + const existingConfig = { + subscription_required: false, + 'agent-in-app-experience': true + } + remoteConfig.value = existingConfig + window.__CONFIG__ = existingConfig + authenticatedRemoteConfigState.value = 'authenticated' + sessionAgentGrant.value = true + sessionAgentGrantValidUntil.value = Date.now() + 60_000 + vi.mocked(global.fetch).mockResolvedValue( + mockErrorResponse(401, 'Unauthorized') + ) + + await refreshRemoteConfig({ useAuth: false }) + + expect(remoteConfig.value).toEqual(existingConfig) + expect(window.__CONFIG__).toEqual(existingConfig) + expect(sessionAgentGrant.value).toBe(true) + expect(authenticatedRemoteConfigState.value).toBe('authenticated') + expect(remoteConfigErrorStatus.value).toBeNull() + }) }) describe('timeout', () => { @@ -223,9 +355,7 @@ describe('refreshRemoteConfig', () => { describe('error handling', () => { it('clears config on 401 response', async () => { cachedLegacyBillingMigrationEnabled.value = true - vi.mocked(api.fetchApi).mockResolvedValue( - mockErrorResponse(401, 'Unauthorized') - ) + mockAuthenticatedFetch(mockErrorResponse(401, 'Unauthorized')) await refreshRemoteConfig() @@ -238,22 +368,34 @@ describe('refreshRemoteConfig', () => { sessionAgentGrant.value = undefined const localStorageBefore = storageEntries(localStorage) const sessionStorageBefore = storageEntries(sessionStorage) - vi.mocked(api.fetchApi).mockResolvedValue( + mockAuthenticatedFetch( mockSuccessResponse({ 'agent-in-app-experience': true }) ) await refreshRemoteConfig() expect(sessionAgentGrant.value).toBe(true) + expect(sessionAgentGrantValidUntil.value).toBeGreaterThan(Date.now()) expect(storageEntries(localStorage)).toEqual(localStorageBefore) expect(storageEntries(sessionStorage)).toEqual(sessionStorageBefore) }) + it('reactively expires the transient session grant', async () => { + vi.useFakeTimers() + mockAuthenticatedFetch( + mockSuccessResponse({ 'agent-in-app-experience': true }) + ) + + await refreshRemoteConfig() + await vi.advanceTimersByTimeAsync(15 * 60_000) + + expect(sessionAgentGrant.value).toBeUndefined() + expect(sessionAgentGrantValidUntil.value).toBeUndefined() + }) + it('keeps this session granted when the poll fails transiently', async () => { sessionAgentGrant.value = true - vi.mocked(api.fetchApi).mockResolvedValue( - mockErrorResponse(503, 'Service Unavailable') - ) + mockAuthenticatedFetch(mockErrorResponse(503, 'Service Unavailable')) await refreshRemoteConfig() @@ -262,9 +404,7 @@ describe('refreshRemoteConfig', () => { it('drops the grant when auth itself is rejected', async () => { sessionAgentGrant.value = true - vi.mocked(api.fetchApi).mockResolvedValue( - mockErrorResponse(401, 'Unauthorized') - ) + mockAuthenticatedFetch(mockErrorResponse(401, 'Unauthorized')) await refreshRemoteConfig() @@ -272,9 +412,7 @@ describe('refreshRemoteConfig', () => { }) it('clears config on 403 response', async () => { - vi.mocked(api.fetchApi).mockResolvedValue( - mockErrorResponse(403, 'Forbidden') - ) + mockAuthenticatedFetch(mockErrorResponse(403, 'Forbidden')) await refreshRemoteConfig() @@ -304,9 +442,7 @@ describe('refreshRemoteConfig', () => { remoteConfig.value = existingConfig window.__CONFIG__ = existingConfig - vi.mocked(api.fetchApi).mockResolvedValue( - mockErrorResponse(500, 'Internal Server Error') - ) + mockAuthenticatedFetch(mockErrorResponse(500, 'Internal Server Error')) await refreshRemoteConfig() diff --git a/src/platform/remoteConfig/refreshRemoteConfig.ts b/src/platform/remoteConfig/refreshRemoteConfig.ts index 6af460f98ba..f8696b326a0 100644 --- a/src/platform/remoteConfig/refreshRemoteConfig.ts +++ b/src/platform/remoteConfig/refreshRemoteConfig.ts @@ -1,17 +1,21 @@ import { + authenticatedRemoteConfigState, cachedBillingControlEnabled, cachedLegacyBillingMigrationEnabled, cachedV1PaymentRecovery, remoteConfig, remoteConfigErrorStatus, + remoteConfigRevision, remoteConfigState, - sessionAgentGrant + sessionAgentGrant, + sessionAgentGrantValidUntil } from './remoteConfig' // Cap the bootstrap fetch so a wedged /features endpoint can never block app.mount indefinitely. // A same-origin GET against the local comfyui server should resolve in well under a second; // on timeout consumers retain the last known config or use build-time defaults. const FEATURES_FETCH_TIMEOUT_MS = 5_000 +const AGENT_GRANT_FALLBACK_MS = 15 * 60_000 interface RefreshRemoteConfigOptions { /** @@ -23,10 +27,31 @@ interface RefreshRemoteConfigOptions { } let refreshGeneration = 0 +let authenticatedLoadingGeneration: number | undefined +let agentGrantExpiryTimer: ReturnType | undefined const activeRefreshControllers = new Set() +function clearSessionAgentGrant(): void { + clearTimeout(agentGrantExpiryTimer) + agentGrantExpiryTimer = undefined + sessionAgentGrant.value = undefined + sessionAgentGrantValidUntil.value = undefined +} + +function cacheSessionAgentGrant(granted: boolean): void { + clearTimeout(agentGrantExpiryTimer) + sessionAgentGrant.value = granted + const validUntil = Date.now() + AGENT_GRANT_FALLBACK_MS + sessionAgentGrantValidUntil.value = validUntil + agentGrantExpiryTimer = setTimeout(() => { + if (sessionAgentGrantValidUntil.value !== validUntil) return + clearSessionAgentGrant() + }, AGENT_GRANT_FALLBACK_MS) +} + export function invalidateRemoteConfig(): void { refreshGeneration++ + authenticatedLoadingGeneration = undefined for (const controller of activeRefreshControllers) controller.abort() activeRefreshControllers.clear() const { comfy_api_base_url, comfy_cloud_base_url, comfy_platform_base_url } = @@ -40,19 +65,94 @@ export function invalidateRemoteConfig(): void { remoteConfig.value = retainedConfig remoteConfigErrorStatus.value = null remoteConfigState.value = 'unloaded' + authenticatedRemoteConfigState.value = 'unloaded' cachedLegacyBillingMigrationEnabled.value = undefined - sessionAgentGrant.value = undefined + clearSessionAgentGrant() } async function fetchRemoteConfig( useAuth: boolean, signal?: AbortSignal -): Promise { +): Promise<{ response: Response; authenticated: boolean }> { const { api } = await import('@/scripts/api') if (!useAuth) { - return fetch(api.apiURL('/features'), { cache: 'no-store', signal }) + return { + response: await fetch(api.apiURL('/features'), { + cache: 'no-store', + signal + }), + authenticated: false + } + } + let authenticated = false + const response = await api.fetchApi('/features', { + cache: 'no-store', + signal, + onAuthHeader: (attached) => { + authenticated = attached + } + }) + return { response, authenticated } +} + +function commitRemoteConfigSuccess( + config: Record, + useAuth: boolean +): void { + window.__CONFIG__ = config + remoteConfig.value = config + remoteConfigErrorStatus.value = null + remoteConfigState.value = useAuth ? 'authenticated' : 'anonymous' + if (useAuth) { + authenticatedRemoteConfigState.value = 'authenticated' + authenticatedLoadingGeneration = undefined + cachedBillingControlEnabled.value = Boolean(config.billing_control_enabled) + cachedLegacyBillingMigrationEnabled.value = Boolean( + config.legacy_billing_migration_enabled + ) + cachedV1PaymentRecovery.value = Boolean(config.v1_payment_recovery) + cacheSessionAgentGrant(config['agent-in-app-experience'] === true) + } else { + authenticatedRemoteConfigState.value = 'unloaded' + authenticatedLoadingGeneration = undefined + clearSessionAgentGrant() } - return api.fetchApi('/features', { cache: 'no-store', signal }) + remoteConfigRevision.value++ +} + +function commitRemoteConfigFailure(response: Response, useAuth: boolean): void { + console.warn('Failed to load remote config:', response.statusText) + if (response.status === 401 || response.status === 403) { + if (useAuth) { + remoteConfigErrorStatus.value = response.status + window.__CONFIG__ = {} + remoteConfig.value = {} + clearSessionAgentGrant() + } else { + remoteConfigErrorStatus.value = null + } + } else { + remoteConfigErrorStatus.value = null + } + if (useAuth) cachedLegacyBillingMigrationEnabled.value = undefined + if (useAuth) { + authenticatedRemoteConfigState.value = 'error' + authenticatedLoadingGeneration = undefined + } + remoteConfigState.value = 'error' + remoteConfigRevision.value++ +} + +function commitRemoteConfigException(error: unknown, useAuth: boolean): void { + console.error('Failed to fetch remote config:', error) + remoteConfigErrorStatus.value = null + if (useAuth) cachedLegacyBillingMigrationEnabled.value = undefined + if (useAuth) { + authenticatedRemoteConfigState.value = 'error' + authenticatedLoadingGeneration = undefined + } + remoteConfigState.value = 'error' + remoteConfigRevision.value++ } /** @@ -69,6 +169,11 @@ export async function refreshRemoteConfig( ): Promise { const { useAuth = true, signal } = options const generation = ++refreshGeneration + const previousAuthenticatedState = authenticatedRemoteConfigState.value + if (useAuth && previousAuthenticatedState !== 'authenticated') { + authenticatedRemoteConfigState.value = 'loading' + authenticatedLoadingGeneration = generation + } const controller = new AbortController() activeRefreshControllers.add(controller) const abort = () => controller.abort() @@ -81,7 +186,10 @@ export async function refreshRemoteConfig( ) try { - const response = await fetchRemoteConfig(useAuth, controller.signal) + const { response, authenticated } = await fetchRemoteConfig( + useAuth, + controller.signal + ) if (generation !== refreshGeneration) return if (signal?.aborted) return @@ -89,42 +197,30 @@ export async function refreshRemoteConfig( const config = await response.json() if (generation !== refreshGeneration) return if (signal?.aborted) return - window.__CONFIG__ = config - remoteConfig.value = config - remoteConfigErrorStatus.value = null - remoteConfigState.value = useAuth ? 'authenticated' : 'anonymous' - if (useAuth) { - cachedBillingControlEnabled.value = Boolean( - config.billing_control_enabled - ) - cachedLegacyBillingMigrationEnabled.value = Boolean( - config.legacy_billing_migration_enabled + if (useAuth && !authenticated) { + authenticatedRemoteConfigState.value = 'error' + authenticatedLoadingGeneration = undefined + remoteConfigErrorStatus.value = null + remoteConfigState.value = 'error' + console.warn( + 'Rejected authenticated remote config response without credentials' ) - cachedV1PaymentRecovery.value = Boolean(config.v1_payment_recovery) - sessionAgentGrant.value = config['agent-in-app-experience'] === true + remoteConfigRevision.value++ + return } + commitRemoteConfigSuccess(config, useAuth) return } - - console.warn('Failed to load remote config:', response.statusText) - if (response.status === 401 || response.status === 403) { - window.__CONFIG__ = {} - remoteConfig.value = {} - remoteConfigErrorStatus.value = response.status - sessionAgentGrant.value = undefined - } else { - remoteConfigErrorStatus.value = null - } - if (useAuth) cachedLegacyBillingMigrationEnabled.value = undefined - remoteConfigState.value = 'error' + commitRemoteConfigFailure(response, useAuth) } catch (error) { if (generation !== refreshGeneration) return if (signal?.aborted) return - console.error('Failed to fetch remote config:', error) - remoteConfigErrorStatus.value = null - if (useAuth) cachedLegacyBillingMigrationEnabled.value = undefined - remoteConfigState.value = 'error' + commitRemoteConfigException(error, useAuth) } finally { + if (authenticatedLoadingGeneration === generation) { + authenticatedRemoteConfigState.value = previousAuthenticatedState + authenticatedLoadingGeneration = undefined + } clearTimeout(timeoutId) signal?.removeEventListener('abort', abort) activeRefreshControllers.delete(controller) diff --git a/src/platform/remoteConfig/remoteConfig.ts b/src/platform/remoteConfig/remoteConfig.ts index 4b97d5303e1..136d656002b 100644 --- a/src/platform/remoteConfig/remoteConfig.ts +++ b/src/platform/remoteConfig/remoteConfig.ts @@ -26,17 +26,25 @@ import type { RemoteConfig } from './types' * - 'error': Failed to load config */ type RemoteConfigState = 'unloaded' | 'anonymous' | 'authenticated' | 'error' +export type AuthenticatedRemoteConfigState = + | 'unloaded' + | 'loading' + | 'authenticated' + | 'error' /** * Current load state of remote configuration */ export const remoteConfigState = ref('unloaded') +export const authenticatedRemoteConfigState = + ref('unloaded') +export const remoteConfigRevision = ref(0) export const remoteConfigErrorStatus = ref(null) /** Whether the authenticated config has been loaded. */ export const isAuthenticatedConfigLoaded = computed( - () => remoteConfigState.value === 'authenticated' + () => authenticatedRemoteConfigState.value === 'authenticated' ) /** @@ -68,6 +76,7 @@ export const cachedLegacyBillingMigrationEnabled = ref() * disagree for one account (PM-1707). */ export const sessionAgentGrant = ref() +export const sessionAgentGrantValidUntil = ref() export const cachedV1PaymentRecovery = useStorage( 'v1_payment_recovery' satisfies `${ServerFeatureFlag.V1_PAYMENT_RECOVERY}`, diff --git a/src/scripts/api.fetchApi.test.ts b/src/scripts/api.fetchApi.test.ts index 5df1ed89582..507c28a9635 100644 --- a/src/scripts/api.fetchApi.test.ts +++ b/src/scripts/api.fetchApi.test.ts @@ -77,11 +77,40 @@ function mockPendingFetch() { describe('api.fetchApi', () => { beforeEach(() => { vi.stubGlobal('fetch', vi.fn()) + mockDistribution.isCloud = false // Reset api state api.user = 'test-user' }) describe('header handling', () => { + it('reports that no auth header was attached off-cloud', async () => { + vi.mocked(global.fetch).mockResolvedValue(new Response()) + const onAuthHeader = vi.fn() + + await api.fetchApi('/test', { onAuthHeader }) + + expect(onAuthHeader).toHaveBeenCalledExactlyOnceWith(false) + expect(vi.mocked(global.fetch).mock.calls[0][1]).not.toHaveProperty( + 'onAuthHeader' + ) + }) + + it('reports when a cloud auth header was attached', async () => { + mockDistribution.isCloud = true + vi.spyOn(firebaseIdentity, 'onUserChanged').mockReturnValue(() => {}) + vi.spyOn(firebaseIdentity, 'onTokenChanged').mockReturnValue(() => {}) + useAuthStore().isInitialized = true + vi.mocked(useAuthStore().getAuthHeader).mockResolvedValue({ + Authorization: 'Bearer tokenA' + }) + vi.mocked(global.fetch).mockResolvedValue(new Response()) + const onAuthHeader = vi.fn() + + await api.fetchApi('/test', { onAuthHeader }) + + expect(onAuthHeader).toHaveBeenCalledExactlyOnceWith(true) + }) + it('should add Comfy-User header with plain object headers', async () => { const mockFetch = vi .mocked(global.fetch) diff --git a/src/scripts/api.ts b/src/scripts/api.ts index 0a7a19239a8..dd1b71e6b54 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -137,6 +137,7 @@ const FETCH_RESPONSE_HEADERS_TIMEOUT_MS = 60_000 interface FetchApiOptions extends RequestInit { timeoutMs?: number | null + onAuthHeader?: (attached: boolean) => void } const FETCH_ROUTE_GROUPS = new Set([ @@ -545,8 +546,11 @@ export class ComfyApi extends EventTarget { } async fetchApi(route: string, options?: FetchApiOptions) { - const { timeoutMs = FETCH_RESPONSE_HEADERS_TIMEOUT_MS, ...requestOptions } = - options ?? {} + const { + timeoutMs = FETCH_RESPONSE_HEADERS_TIMEOUT_MS, + onAuthHeader, + ...requestOptions + } = options ?? {} const headers: HeadersInit = requestOptions.headers ?? {} let unifiedRetryOn401 = false @@ -565,6 +569,7 @@ export class ComfyApi extends EventTarget { } const authHeader = await getAuthHeaderIfAvailable() + onAuthHeader?.(authHeader !== null) if (authHeader) { for (const [key, value] of Object.entries(authHeader)) { @@ -572,6 +577,8 @@ export class ComfyApi extends EventTarget { } unifiedRetryOn401 = await shouldRemintCloudRequest() } + } else { + onAuthHeader?.(false) } addHeaderEntry(headers, 'Comfy-User', this.user) diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index 64f0119ac7b..b42922d25a2 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -2166,15 +2166,17 @@ describe('useAuthStore', () => { (_route, options) => new Promise((resolve) => { accountASignal = options?.signal ?? undefined + options?.onAuthHeader?.(true) resolveAccountA = resolve }) ) - .mockResolvedValueOnce( - new Response( + .mockImplementationOnce(async (_route, options) => { + options?.onAuthHeader?.(true) + return new Response( JSON.stringify({ legacy_billing_migration_enabled: false }), { status: 200 } ) - ) + }) const accountARefresh = refreshRemoteConfig() await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledTimes(1)) From 7623892c69a408012621b71632a9a6659df27dcd Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Mon, 28 Sep 2026 18:10:27 +0000 Subject: [PATCH 2/2] Fix core/1.54 test compatibility --- src/scripts/api.fetchApi.test.ts | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/src/scripts/api.fetchApi.test.ts b/src/scripts/api.fetchApi.test.ts index 507c28a9635..5df1ed89582 100644 --- a/src/scripts/api.fetchApi.test.ts +++ b/src/scripts/api.fetchApi.test.ts @@ -77,40 +77,11 @@ function mockPendingFetch() { describe('api.fetchApi', () => { beforeEach(() => { vi.stubGlobal('fetch', vi.fn()) - mockDistribution.isCloud = false // Reset api state api.user = 'test-user' }) describe('header handling', () => { - it('reports that no auth header was attached off-cloud', async () => { - vi.mocked(global.fetch).mockResolvedValue(new Response()) - const onAuthHeader = vi.fn() - - await api.fetchApi('/test', { onAuthHeader }) - - expect(onAuthHeader).toHaveBeenCalledExactlyOnceWith(false) - expect(vi.mocked(global.fetch).mock.calls[0][1]).not.toHaveProperty( - 'onAuthHeader' - ) - }) - - it('reports when a cloud auth header was attached', async () => { - mockDistribution.isCloud = true - vi.spyOn(firebaseIdentity, 'onUserChanged').mockReturnValue(() => {}) - vi.spyOn(firebaseIdentity, 'onTokenChanged').mockReturnValue(() => {}) - useAuthStore().isInitialized = true - vi.mocked(useAuthStore().getAuthHeader).mockResolvedValue({ - Authorization: 'Bearer tokenA' - }) - vi.mocked(global.fetch).mockResolvedValue(new Response()) - const onAuthHeader = vi.fn() - - await api.fetchApi('/test', { onAuthHeader }) - - expect(onAuthHeader).toHaveBeenCalledExactlyOnceWith(true) - }) - it('should add Comfy-User header with plain object headers', async () => { const mockFetch = vi .mocked(global.fetch)