LCOV - code coverage report
Current view: top level - src/platform/remoteConfig - refreshRemoteConfig.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 50.0 % 138 69
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { delay } from 'es-toolkit'
       2              : 
       3              : import { resolveUnifiedWebSession } from '@comfyorg/account-core/webSessionFlag'
       4              : 
       5              : import { hasServerFirebaseConfig } from '@/config/firebase'
       6              : import { isCloud } from '@/platform/distribution/types'
       7              : import { reportError } from '@comfyorg/telemetry/reportError'
       8              : import { isLoopbackHost } from '@/utils/hostWhitelist'
       9              : 
      10              : import {
      11              :   authenticatedRemoteConfigState,
      12              :   remoteConfig,
      13              :   remoteConfigErrorStatus,
      14              :   remoteConfigRevision,
      15              :   remoteConfigState,
      16              :   sessionAgentGrant,
      17              :   sessionAgentGrantValidUntil,
      18              :   useRemoteConfigCache
      19              : } from './remoteConfig'
      20              : 
      21              : // Cap the bootstrap fetch so a wedged /features endpoint can never block app.mount indefinitely.
      22              : // A same-origin GET against the local comfyui server should resolve in well under a second;
      23              : // on timeout consumers retain the last known config or use build-time defaults.
      24         2356 : const FEATURES_FETCH_TIMEOUT_MS = 5_000
      25         2356 : const AGENT_GRANT_FALLBACK_MS = 15 * 60_000
      26              : 
      27              : interface RefreshRemoteConfigOptions {
      28              :   /**
      29              :    * Whether to use authenticated API (default: true).
      30              :    * Set to false during bootstrap before auth is initialized.
      31              :    */
      32              :   useAuth?: boolean
      33              :   signal?: AbortSignal
      34              : }
      35              : 
      36         2356 : let refreshGeneration = 0
      37         2356 : let authenticatedLoadingGeneration: number | undefined
      38         2356 : let agentGrantExpiryTimer: ReturnType<typeof setTimeout> | undefined
      39         2356 : const activeRefreshControllers = new Set<AbortController>()
      40              : 
      41         2359 : function clearSessionAgentGrant(): void {
      42         2359 :   clearTimeout(agentGrantExpiryTimer)
      43         2359 :   agentGrantExpiryTimer = undefined
      44         2359 :   sessionAgentGrant.value = undefined
      45         2359 :   sessionAgentGrantValidUntil.value = undefined
      46              : }
      47              : 
      48            0 : function cacheSessionAgentGrant(granted: boolean): void {
      49            0 :   clearTimeout(agentGrantExpiryTimer)
      50            0 :   sessionAgentGrant.value = granted
      51            0 :   const validUntil = Date.now() + AGENT_GRANT_FALLBACK_MS
      52            0 :   sessionAgentGrantValidUntil.value = validUntil
      53            0 :   agentGrantExpiryTimer = setTimeout(() => {
      54            0 :     if (sessionAgentGrantValidUntil.value !== validUntil) return
      55            0 :     clearSessionAgentGrant()
      56              :   }, AGENT_GRANT_FALLBACK_MS)
      57              : }
      58              : 
      59            1 : export function invalidateRemoteConfig(): void {
      60            1 :   refreshGeneration++
      61            1 :   authenticatedLoadingGeneration = undefined
      62            1 :   for (const controller of activeRefreshControllers) controller.abort()
      63            1 :   activeRefreshControllers.clear()
      64            1 :   const { comfy_api_base_url, comfy_cloud_base_url, comfy_platform_base_url } =
      65              :     remoteConfig.value
      66            1 :   const retainedConfig = {
      67              :     ...(comfy_api_base_url && { comfy_api_base_url }),
      68              :     ...(comfy_cloud_base_url && { comfy_cloud_base_url }),
      69              :     ...(comfy_platform_base_url && { comfy_platform_base_url })
      70              :   }
      71            1 :   window.__CONFIG__ = retainedConfig
      72            1 :   remoteConfig.value = retainedConfig
      73            1 :   remoteConfigErrorStatus.value = null
      74            1 :   remoteConfigState.value = 'unloaded'
      75            1 :   authenticatedRemoteConfigState.value = 'unloaded'
      76            1 :   clearSessionAgentGrant()
      77              : }
      78              : 
      79         2358 : async function fetchRemoteConfig(
      80              :   useAuth: boolean,
      81              :   signal?: AbortSignal
      82              : ): Promise<{ response: Response; authenticated: boolean }> {
      83         2358 :   const { api } = await import('@/scripts/api')
      84         2358 :   if (!useAuth) {
      85         2358 :     return {
      86              :       response: await fetch(api.apiURL('/features'), {
      87              :         cache: 'no-store',
      88              :         signal
      89              :       }),
      90              :       authenticated: false
      91              :     }
      92              :   }
      93            0 :   let authenticated = false
      94              :   const response = await api.fetchApi('/features', {
      95              :     cache: 'no-store',
      96              :     signal,
      97              :     onAuthHeader: (attached) => {
      98            0 :       authenticated = attached
      99              :     }
     100              :   })
     101            0 :   return { response, authenticated }
     102              : }
     103              : 
     104         2358 : function commitRemoteConfigSuccess(
     105              :   config: Record<string, unknown>,
     106              :   useAuth: boolean
     107              : ): void {
     108         2358 :   window.__CONFIG__ = config
     109         2358 :   remoteConfig.value = config
     110         2358 :   remoteConfigErrorStatus.value = null
     111         2358 :   remoteConfigState.value = useAuth ? 'authenticated' : 'anonymous'
     112         2358 :   if (useAuth) {
     113            0 :     authenticatedRemoteConfigState.value = 'authenticated'
     114            0 :     authenticatedLoadingGeneration = undefined
     115            0 :     const cache = useRemoteConfigCache()
     116            0 :     cache.cachedBillingControlEnabled.value = Boolean(
     117              :       config.billing_control_enabled
     118              :     )
     119            0 :     cache.cachedV1PaymentRecovery.value = Boolean(config.v1_payment_recovery)
     120            0 :     cacheSessionAgentGrant(config['agent-in-app-experience'] === true)
     121              :   } else {
     122         2358 :     authenticatedRemoteConfigState.value = 'unloaded'
     123         2358 :     authenticatedLoadingGeneration = undefined
     124         2358 :     clearSessionAgentGrant()
     125              :   }
     126         2358 :   remoteConfigRevision.value++
     127              : }
     128              : 
     129              : /**
     130              :  * The anonymous document answers `unified_web_session` false for a cookie-only
     131              :  * caller; only a credentialed read that names its client is authoritative.
     132              :  */
     133         2358 : async function readCredentialedWebSessionFlag(
     134              :   config: Record<string, unknown>,
     135              :   generation: number
     136              : ): Promise<void> {
     137              :   if (!isCloud || config.web_session_probe !== true) return
     138              :   const enabled = await resolveUnifiedWebSession({
     139              :     cloudBaseUrl: window.location.origin,
     140              :     fetchImpl: (...args) => fetch(...args),
     141              :     probe: async () => true
     142              :   })
     143              :   if (generation !== refreshGeneration) return
     144              :   const merged: Record<string, unknown> = {
     145              :     ...config,
     146              :     unified_web_session: enabled
     147              :   }
     148              :   window.__CONFIG__ = merged
     149              :   remoteConfig.value = merged
     150              :   remoteConfigRevision.value++
     151              : }
     152              : 
     153            0 : function commitRemoteConfigFailure(response: Response, useAuth: boolean): void {
     154            0 :   console.warn('Failed to load remote config:', response.statusText)
     155            0 :   if (response.status === 401 || response.status === 403) {
     156            0 :     if (useAuth) {
     157            0 :       remoteConfigErrorStatus.value = response.status
     158            0 :       window.__CONFIG__ = {}
     159            0 :       remoteConfig.value = {}
     160            0 :       clearSessionAgentGrant()
     161              :     } else {
     162            0 :       remoteConfigErrorStatus.value = null
     163              :     }
     164              :   } else {
     165            0 :     remoteConfigErrorStatus.value = null
     166              :   }
     167            0 :   if (useAuth) {
     168            0 :     authenticatedRemoteConfigState.value = 'error'
     169            0 :     authenticatedLoadingGeneration = undefined
     170              :   }
     171            0 :   remoteConfigState.value = 'error'
     172            0 :   remoteConfigRevision.value++
     173              : }
     174              : 
     175            0 : function commitRemoteConfigException(error: unknown, useAuth: boolean): void {
     176            0 :   console.error('Failed to fetch remote config:', error)
     177            0 :   remoteConfigErrorStatus.value = null
     178            0 :   if (useAuth) {
     179            0 :     authenticatedRemoteConfigState.value = 'error'
     180            0 :     authenticatedLoadingGeneration = undefined
     181              :   }
     182            0 :   remoteConfigState.value = 'error'
     183            0 :   remoteConfigRevision.value++
     184              : }
     185              : 
     186              : /**
     187              :  * Loads remote configuration from the backend /features endpoint
     188              :  * and updates the reactive remoteConfig ref.
     189              :  *
     190              :  * Sets remoteConfigState to:
     191              :  * - 'anonymous' when loaded without auth
     192              :  * - 'authenticated' when loaded with auth
     193              :  * - 'error' when load fails
     194              :  */
     195         2358 : export async function refreshRemoteConfig(
     196              :   options: RefreshRemoteConfigOptions = {}
     197              : ): Promise<void> {
     198         2358 :   const { useAuth = true, signal } = options
     199         2358 :   const generation = ++refreshGeneration
     200         2358 :   const previousAuthenticatedState = authenticatedRemoteConfigState.value
     201         2358 :   if (useAuth && previousAuthenticatedState !== 'authenticated') {
     202            0 :     authenticatedRemoteConfigState.value = 'loading'
     203            0 :     authenticatedLoadingGeneration = generation
     204              :   }
     205         2358 :   const controller = new AbortController()
     206         2358 :   activeRefreshControllers.add(controller)
     207         2358 :   const abort = () => controller.abort()
     208         2358 :   signal?.addEventListener('abort', abort, { once: true })
     209         2358 :   if (signal?.aborted) abort()
     210              : 
     211         2358 :   const timeoutId = setTimeout(
     212              :     () => controller.abort(),
     213              :     FEATURES_FETCH_TIMEOUT_MS
     214              :   )
     215              : 
     216         2358 :   try {
     217         2358 :     const { response, authenticated } = await fetchRemoteConfig(
     218              :       useAuth,
     219              :       controller.signal
     220              :     )
     221         2358 :     if (generation !== refreshGeneration) return
     222         2358 :     if (signal?.aborted) return
     223              : 
     224         2358 :     if (response.ok) {
     225         2358 :       const config = await response.json()
     226         2358 :       if (generation !== refreshGeneration) return
     227         2358 :       if (signal?.aborted) return
     228         2358 :       if (useAuth && !authenticated) {
     229            0 :         authenticatedRemoteConfigState.value = 'error'
     230            0 :         authenticatedLoadingGeneration = undefined
     231            0 :         remoteConfigErrorStatus.value = null
     232            0 :         remoteConfigState.value = 'error'
     233            0 :         console.warn(
     234              :           'Rejected authenticated remote config response without credentials'
     235              :         )
     236            0 :         remoteConfigRevision.value++
     237            0 :         return
     238              :       }
     239         2358 :       commitRemoteConfigSuccess(config, useAuth)
     240         2358 :       if (!useAuth) await readCredentialedWebSessionFlag(config, generation)
     241         2358 :       return
     242              :     }
     243            0 :     commitRemoteConfigFailure(response, useAuth)
     244              :   } catch (error) {
     245            0 :     if (generation !== refreshGeneration) return
     246            0 :     if (signal?.aborted) return
     247            0 :     commitRemoteConfigException(error, useAuth)
     248              :   } finally {
     249         2358 :     if (authenticatedLoadingGeneration === generation) {
     250            0 :       authenticatedRemoteConfigState.value = previousAuthenticatedState
     251            0 :       authenticatedLoadingGeneration = undefined
     252              :     }
     253         2358 :     clearTimeout(timeoutId)
     254         2358 :     signal?.removeEventListener('abort', abort)
     255         2358 :     activeRefreshControllers.delete(controller)
     256              :   }
     257              : }
     258              : 
     259         2356 : const BOOTSTRAP_RETRY_BASE_MS = 1_000
     260         2356 : const BOOTSTRAP_RETRY_MAX_MS = 10_000
     261         2356 : const BOOTSTRAP_UNNAMED_PROJECT_READS = 1
     262              : 
     263            0 : function servesLocalCloud(): boolean {
     264            0 :   return isLoopbackHost(window.location.hostname)
     265              : }
     266              : 
     267              : /**
     268              :  * Blocks until the server names the Firebase project; a loopback harness,
     269              :  * whose server never sends one, stops after a further read instead.
     270              :  */
     271            0 : export async function loadRemoteConfigUntilReady(): Promise<void> {
     272            0 :   let unnamedProjectReads = 0
     273            0 :   for (let attempt = 0; ; attempt++) {
     274            0 :     await refreshRemoteConfig({ useAuth: false })
     275            0 :     if (remoteConfigState.value !== 'error') {
     276            0 :       if (hasServerFirebaseConfig()) return
     277            0 :       unnamedProjectReads++
     278            0 :       if (unnamedProjectReads === 1) {
     279            0 :         reportError(
     280              :           new Error(
     281              :             'Startup read answered without naming the Firebase project'
     282              :           ),
     283              :           {
     284              :             surface: 'workspace',
     285              :             errorType: 'startup_remote_config_without_firebase_project',
     286              :             level: 'warning',
     287              :             context: { localCloud: servesLocalCloud() }
     288              :           }
     289              :         )
     290              :       }
     291            0 :       if (
     292              :         servesLocalCloud() &&
     293              :         unnamedProjectReads > BOOTSTRAP_UNNAMED_PROJECT_READS
     294              :       )
     295            0 :         return
     296              :     }
     297            0 :     await delay(
     298              :       Math.min(BOOTSTRAP_RETRY_BASE_MS * 2 ** attempt, BOOTSTRAP_RETRY_MAX_MS)
     299              :     )
     300              :   }
     301              : }
        

Generated by: LCOV version 2.0-1