diff --git a/docs/FEATURE_FLAGS.md b/docs/FEATURE_FLAGS.md index b0afe21e626..269935966a6 100644 --- a/docs/FEATURE_FLAGS.md +++ b/docs/FEATURE_FLAGS.md @@ -289,7 +289,7 @@ They resolve in this order, first match wins: (`src/utils/sessionFeatureFlagOverride.ts`) 2. **Dev override** — `getDevOverride()` (`src/utils/devFeatureFlagOverride.ts`) -3. **Remote config** — the matching `remoteConfig.value.*` field, when the +3. **Remote config** — the matching `useRemoteConfigStore().config.*` field, when the getter passes one 4. **Server feature flag** — `api.getServerFeature(flagKey, defaultValue)` diff --git a/src/components/dialog/GlobalDialog.test.ts b/src/components/dialog/GlobalDialog.test.ts index d00069ad2b8..223338821e8 100644 --- a/src/components/dialog/GlobalDialog.test.ts +++ b/src/components/dialog/GlobalDialog.test.ts @@ -1,5 +1,6 @@ import { render, screen, waitFor, within } from '@testing-library/vue' import userEvent from '@testing-library/user-event' +import { getActivePinia } from 'pinia' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { computed, defineComponent, h, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' @@ -112,7 +113,7 @@ const Body = defineComponent({ function mountDialog() { return render(GlobalDialog, { - global: { plugins: [i18n] } + global: { plugins: [getActivePinia()!, i18n] } }) } diff --git a/src/components/dialog/content/SignInContent.test.ts b/src/components/dialog/content/SignInContent.test.ts index 02620e29a08..5bb6a258803 100644 --- a/src/components/dialog/content/SignInContent.test.ts +++ b/src/components/dialog/content/SignInContent.test.ts @@ -21,7 +21,6 @@ vi.mock(import('@/utils/hostWhitelist'), () => ({ isHostWhitelisted: () => true, normalizeHost: (host: string) => host })) -vi.mock(import('@/platform/remoteConfig/remoteConfig')) const inChina = vi.hoisted(() => ({ value: false, diff --git a/src/components/dialog/content/SignInContent.vue b/src/components/dialog/content/SignInContent.vue index 5a14b1faf6c..8689e89c3a7 100644 --- a/src/components/dialog/content/SignInContent.vue +++ b/src/components/dialog/content/SignInContent.vue @@ -194,8 +194,8 @@ import { useSocialSignIn } from '@/platform/auth/social/useSocialSignIn' import { getComfyPlatformBaseUrl } from '@/config/comfyApi' import { configValueOrDefault, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' + useRemoteConfigStore +} from '@/platform/remoteConfig/remoteConfigStore' import type { SignInData, SignUpData } from '@/schemas/signInSchema' import { desktopHostReportsSignInFailures, @@ -240,9 +240,10 @@ const signInWithDesktopHost = async () => { } toast.error(t('auth.desktopHost.signInFailed'), { duration: 6000 }) } +const remoteConfigStore = useRemoteConfigStore() const comfyPlatformBaseUrl = computed(() => configValueOrDefault( - remoteConfig.value, + remoteConfigStore.config, 'comfy_platform_base_url', getComfyPlatformBaseUrl() ) diff --git a/src/components/dialog/content/signin/ApiKeyForm.vue b/src/components/dialog/content/signin/ApiKeyForm.vue index 50217eb0873..46e88974767 100644 --- a/src/components/dialog/content/signin/ApiKeyForm.vue +++ b/src/components/dialog/content/signin/ApiKeyForm.vue @@ -78,18 +78,19 @@ import Input from '@comfyorg/design-system/input/Input' import { getComfyPlatformBaseUrl } from '@/config/comfyApi' import { configValueOrDefault, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' + useRemoteConfigStore +} from '@/platform/remoteConfig/remoteConfigStore' import { apiKeySchema } from '@/schemas/signInSchema' import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useAuthStore } from '@/stores/authStore' const authStore = useAuthStore() const apiKeyStore = useApiKeyAuthStore() +const remoteConfigStore = useRemoteConfigStore() const loading = computed(() => authStore.loading) const comfyPlatformBaseUrl = computed(() => configValueOrDefault( - remoteConfig.value, + remoteConfigStore.config, 'comfy_platform_base_url', getComfyPlatformBaseUrl() ) diff --git a/src/components/topbar/WorkflowTabs.test.ts b/src/components/topbar/WorkflowTabs.test.ts index e52ef63bd1e..dadb5c6a88f 100644 --- a/src/components/topbar/WorkflowTabs.test.ts +++ b/src/components/topbar/WorkflowTabs.test.ts @@ -2,14 +2,14 @@ import { render, screen, waitFor } from '@testing-library/vue' import userEvent from '@testing-library/user-event' import { fromPartial } from '@total-typescript/shoehorn' import { TabsTrigger } from 'reka-ui' -import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import type { Mock } from 'vitest' import type { PropType } from 'vue' import { computed, defineComponent, h, nextTick } from 'vue' import { createI18n } from 'vue-i18n' import { useCurrentUser } from '@/composables/auth/useCurrentUser' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import enMessages from '@/locales/en/main.json' with { type: 'json' } import { useSettingStore } from '@/platform/settings/settingStore' @@ -232,11 +232,11 @@ describe('WorkflowTabs profile button', () => { }) function setBillingNewUx(enabled: boolean) { - const previous = remoteConfig.value - remoteConfig.value = { ...previous, billing_new_ux_enabled: enabled } - onTestFinished(() => { - remoteConfig.value = previous - }) + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { ...remoteConfigStore.config, billing_new_ux_enabled: enabled }, + false + ) } it('keeps the profile button in the top bar while billing_new_ux_enabled is off', () => { diff --git a/src/composables/auth/useTurnstile.test.ts b/src/composables/auth/useTurnstile.test.ts index 5fcc0792cb4..5a0b2414766 100644 --- a/src/composables/auth/useTurnstile.test.ts +++ b/src/composables/auth/useTurnstile.test.ts @@ -2,11 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { useTurnstile } from '@/composables/auth/useTurnstile' import { getTurnstileSiteKey } from '@/config/turnstile' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { api } from '@/scripts/api' import { getDevOverride } from '@/utils/devFeatureFlagOverride' -vi.mock(import('@/platform/remoteConfig/remoteConfig')) vi.mock(import('@/scripts/api')) vi.mock(import('@/utils/devFeatureFlagOverride'), () => ({ getDevOverride: vi.fn() @@ -23,7 +22,6 @@ const mockedSiteKey = vi.mocked(getTurnstileSiteKey) // suite covers their binding to this app's config sources. describe('useTurnstile', () => { beforeEach(() => { - remoteConfig.value = {} mockedDevOverride.mockReturnValue(undefined) vi.mocked(api.getServerFeature).mockReturnValue('off') mockedSiteKey.mockReturnValue('site-key') @@ -32,14 +30,14 @@ describe('useTurnstile', () => { describe('mode precedence', () => { it('prefers the dev override over remote config and the server feature', () => { mockedDevOverride.mockReturnValue('enforce') - remoteConfig.value = { signup_turnstile: 'shadow' } + useRemoteConfigStore().acceptConfig({ signup_turnstile: 'shadow' }, false) vi.mocked(api.getServerFeature).mockReturnValue('off') expect(useTurnstile().mode.value).toBe('enforce') }) it('uses remote config when there is no dev override', () => { - remoteConfig.value = { signup_turnstile: 'shadow' } + useRemoteConfigStore().acceptConfig({ signup_turnstile: 'shadow' }, false) expect(useTurnstile().mode.value).toBe('shadow') }) @@ -55,9 +53,7 @@ describe('useTurnstile', () => { }) it('clamps an unknown remote-config value to off', () => { - remoteConfig.value = { - signup_turnstile: 'bogus' as unknown as 'shadow' - } + useRemoteConfigStore().acceptConfig({ signup_turnstile: 'bogus' }, false) expect(useTurnstile().mode.value).toBe('off') }) @@ -69,7 +65,7 @@ describe('useTurnstile', () => { describe('enabled / enforced', () => { it('is enabled but not enforced in shadow with a sitekey', () => { - remoteConfig.value = { signup_turnstile: 'shadow' } + useRemoteConfigStore().acceptConfig({ signup_turnstile: 'shadow' }, false) const { enabled, enforced } = useTurnstile() expect(enabled.value).toBe(true) @@ -77,7 +73,10 @@ describe('useTurnstile', () => { }) it('is enabled and enforced in enforce with a sitekey', () => { - remoteConfig.value = { signup_turnstile: 'enforce' } + useRemoteConfigStore().acceptConfig( + { signup_turnstile: 'enforce' }, + false + ) const { enabled, enforced } = useTurnstile() expect(enabled.value).toBe(true) @@ -85,7 +84,10 @@ describe('useTurnstile', () => { }) it('is neither enabled nor enforced without a sitekey, even in enforce', () => { - remoteConfig.value = { signup_turnstile: 'enforce' } + useRemoteConfigStore().acceptConfig( + { signup_turnstile: 'enforce' }, + false + ) mockedSiteKey.mockReturnValue('') const { enabled, enforced } = useTurnstile() diff --git a/src/composables/useFeatureFlags.test.ts b/src/composables/useFeatureFlags.test.ts index a777646646e..504d528ec86 100644 --- a/src/composables/useFeatureFlags.test.ts +++ b/src/composables/useFeatureFlags.test.ts @@ -18,14 +18,7 @@ import { setLocalBillingNewUxEnabled, setLocalBillingWebEnabled } from '@/platform/billing/localBillingWebEnabled' -import { - authenticatedRemoteConfigState, - remoteConfig, - remoteConfigState, - sessionAgentGrant, - sessionAgentGrantValidUntil, - useRemoteConfigCache -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { ServerFeatureFlag } from '@/platform/remoteConfig/serverFeatureFlag' import { useTelemetry } from '@comfyorg/telemetry' import { api } from '@/scripts/api' @@ -47,9 +40,6 @@ vi.mock(import('@/platform/distribution/types'), () => ({ vi.mock(import('@comfyorg/telemetry')) -const { cachedBillingControlEnabled, cachedV1PaymentRecovery } = - useRemoteConfigCache() - function persistFromAnotherTab(key: string, value: string) { localStorage.setItem(key, value) window.dispatchEvent( @@ -65,13 +55,6 @@ describe('useFeatureFlags', () => { afterEach(() => { vi.mocked(distributionTypes).isCloud = false vi.mocked(distributionTypes).isNightly = false - remoteConfig.value = {} - remoteConfigState.value = 'unloaded' - authenticatedRemoteConfigState.value = 'unloaded' - sessionAgentGrant.value = undefined - sessionAgentGrantValidUntil.value = undefined - cachedBillingControlEnabled.value = undefined - cachedV1PaymentRecovery.value = undefined }) describe('flags object', () => { @@ -207,11 +190,17 @@ describe('useFeatureFlags', () => { it('enables the hosted app only on the billing_web variant', () => { const { flags } = useFeatureFlags() - remoteConfig.value = { hosted_billing_destination: 'billing_web' } + useRemoteConfigStore().acceptConfig( + { hosted_billing_destination: 'billing_web' }, + false + ) expect(flags.hostedBillingDestination).toBe('billing_web') expect(flags.hostedBillingWebEnabled).toBe(true) - remoteConfig.value = { hosted_billing_destination: 'true' } + useRemoteConfigStore().acceptConfig( + { hosted_billing_destination: 'true' }, + false + ) expect(flags.hostedBillingDestination).toBe('stripe') expect(flags.hostedBillingWebEnabled).toBe(false) }) @@ -226,7 +215,7 @@ describe('useFeatureFlags', () => { ])( 'enables the 1.61 billing UX only for literal true ($label)', ({ value, enabled }) => { - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, false) vi.mocked(api.getServerFeature).mockReturnValue(value) expect(useFeatureFlags().flags.billingNewUxEnabled).toBe(enabled) @@ -234,7 +223,10 @@ describe('useFeatureFlags', () => { ) it('reads the billing rollout from /features', () => { - remoteConfig.value = { billing_new_ux_enabled: true } + useRemoteConfigStore().acceptConfig( + { billing_new_ux_enabled: true }, + false + ) vi.mocked(api.getServerFeature).mockReturnValue(false) expect(useFeatureFlags().flags.billingNewUxEnabled).toBe(true) @@ -466,7 +458,10 @@ describe('useFeatureFlags', () => { }) it('lets a remote config false turn off the nightly default', () => { - remoteConfig.value = { node_library_essentials_enabled: false } + useRemoteConfigStore().acceptConfig( + { node_library_essentials_enabled: false }, + false + ) vi.mocked(api.getServerFeature).mockImplementation( (_path, defaultValue) => defaultValue ) @@ -513,7 +508,10 @@ describe('useFeatureFlags', () => { 'follows a remote config $served over the dev=$dev default', ({ dev, served, expected }) => { vi.stubEnv('DEV', dev) - remoteConfig.value = { open_on_cloud_enabled: served } + useRemoteConfigStore().acceptConfig( + { open_on_cloud_enabled: served }, + false + ) expect(useFeatureFlags().flags.openOnCloudEnabled).toBe(expected) } @@ -527,10 +525,6 @@ describe('useFeatureFlags', () => { ) }) - afterEach(() => { - remoteConfig.value = {} - }) - it.for([false, true])('defaults off in dev=%s', (dev) => { vi.stubEnv('DEV', dev) @@ -546,7 +540,10 @@ describe('useFeatureFlags', () => { ])( 'uses only a boolean true from remote config: $served', ({ served, expected }) => { - remoteConfig.value = { open_on_cloud_use_local_agent_enabled: served } + useRemoteConfigStore().acceptConfig( + { open_on_cloud_use_local_agent_enabled: served }, + false + ) expect(useFeatureFlags().flags.openOnCloudUseLocalAgentEnabled).toBe( expected @@ -577,7 +574,10 @@ describe('useFeatureFlags', () => { describe('partnerNodeGovernanceEnabled', () => { it('uses the workspace eligibility flag', () => { - remoteConfig.value = { partner_node_governance_enabled: true } + useRemoteConfigStore().acceptConfig( + { partner_node_governance_enabled: true }, + false + ) const { flags } = useFeatureFlags() @@ -597,7 +597,10 @@ describe('useFeatureFlags', () => { describe('deploymentCompatibilityMarksEnabled', () => { it('turns on from remote config', () => { - remoteConfig.value = { deployment_compatibility_marks_enabled: true } + useRemoteConfigStore().acceptConfig( + { deployment_compatibility_marks_enabled: true }, + false + ) const { flags } = useFeatureFlags() @@ -627,7 +630,10 @@ describe('useFeatureFlags', () => { describe('runtimeLibraryModelsEnabled', () => { it('turns on from remote config', () => { - remoteConfig.value = { runtime_library_models_enabled: true } + useRemoteConfigStore().acceptConfig( + { runtime_library_models_enabled: true }, + false + ) const { flags } = useFeatureFlags() @@ -657,7 +663,10 @@ describe('useFeatureFlags', () => { describe('modelUploadFolders', () => { it('lists the folders the server accepts uploads into', () => { - remoteConfig.value = { model_upload_folders: ['checkpoints', 'loras'] } + useRemoteConfigStore().acceptConfig( + { model_upload_folders: ['checkpoints', 'loras'] }, + false + ) const { flags } = useFeatureFlags() @@ -757,8 +766,12 @@ describe('useFeatureFlags', () => { ) it('returns the cached session value during the auth window', () => { - cachedBillingControlEnabled.value = true - cachedV1PaymentRecovery.value = true + const store = useRemoteConfigStore() + store.acceptConfig( + { billing_control_enabled: true, v1_payment_recovery: true }, + true + ) + store.invalidate() const { flags } = useFeatureFlags() expect(flags.billingControlEnabled).toBe(true) @@ -772,12 +785,13 @@ describe('useFeatureFlags', () => { }) it('prefers authenticated remoteConfig over the server feature fallback', () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { - billing_control_enabled: false, - v1_payment_recovery: true - } + useRemoteConfigStore().acceptConfig( + { + billing_control_enabled: false, + v1_payment_recovery: true + }, + true + ) vi.mocked(api.getServerFeature).mockReturnValue(false) const { flags } = useFeatureFlags() @@ -786,9 +800,7 @@ describe('useFeatureFlags', () => { }) it('falls back to api.getServerFeature when authenticated config omits the flag', () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, true) vi.mocked(api.getServerFeature).mockImplementation( (path, defaultValue) => { if (path === ServerFeatureFlag.BILLING_CONTROL_ENABLED) return true @@ -834,7 +846,10 @@ describe('useFeatureFlags', () => { describe('supportsModelTypeTags', () => { it('uses the remote config value', () => { - remoteConfig.value = { supports_model_type_tags: true } + useRemoteConfigStore().acceptConfig( + { supports_model_type_tags: true }, + false + ) const { flags } = useFeatureFlags() @@ -872,9 +887,12 @@ describe('useFeatureFlags', () => { describe('feature flag telemetry', () => { it('synchronizes resolved values when their sources change', async () => { vi.mocked(distributionTypes).isCloud = true - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { partner_node_governance_enabled: false } + useRemoteConfigStore().acceptConfig( + { + partner_node_governance_enabled: false + }, + true + ) vi.mocked(api.getServerFeature).mockImplementation( (_path, defaultValue) => defaultValue ) @@ -893,7 +911,10 @@ describe('useFeatureFlags', () => { const currentTelemetry = useTelemetry() if (!currentTelemetry) throw new Error('Expected telemetry mock') vi.mocked(currentTelemetry.trackFeatureFlagEvaluation).mockClear() - remoteConfig.value = { partner_node_governance_enabled: true } + useRemoteConfigStore().acceptConfig( + { partner_node_governance_enabled: true }, + false + ) await nextTick() expect(useTelemetry()?.trackFeatureFlagEvaluation).toHaveBeenCalledWith( @@ -915,9 +936,10 @@ describe('useFeatureFlags', () => { : undefined ) vi.mocked(distributionTypes).isCloud = true - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { unified_web_session: served } + useRemoteConfigStore().acceptConfig( + { unified_web_session: served }, + true + ) vi.mocked(api.getServerFeature).mockImplementation( (_path, defaultValue) => defaultValue ) @@ -958,7 +980,7 @@ describe('useFeatureFlags', () => { describe('unifiedWebSessionEnabled', () => { beforeEach(() => { vi.mocked(distributionTypes).isCloud = true - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig({}, true) vi.mocked(api.getServerFeature).mockImplementation( (_path, defaultValue) => defaultValue ) @@ -967,34 +989,30 @@ describe('useFeatureFlags', () => { it.for([ { name: 'is off when /api/features lacks the flag', - state: 'authenticated', - config: {}, + arrange: (store: ReturnType) => + store.acceptConfig({}, true), expected: false }, { name: 'is off when remote config failed to load', - state: 'error', - config: {}, + arrange: (store: ReturnType) => + store.failLoad(true), expected: false }, { name: 'is on when the server sends true', - state: 'authenticated', - config: { unified_web_session: true }, + arrange: (store: ReturnType) => + store.acceptConfig({ unified_web_session: true }, true), expected: true } - ] as const)('$name', ({ state, config, expected }) => { - remoteConfigState.value = state - authenticatedRemoteConfigState.value = - state === 'authenticated' ? 'authenticated' : state - remoteConfig.value = config + ])('$name', ({ arrange, expected }) => { + arrange(useRemoteConfigStore()) expect(useFeatureFlags().flags.unifiedWebSessionEnabled).toBe(expected) }) it('ignores the server-feature fallback when /api/features lacks the flag', () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig({}, true) vi.mocked(api.getServerFeature).mockImplementation((path, defaultValue) => path === ServerFeatureFlag.UNIFIED_WEB_SESSION ? true : defaultValue ) @@ -1005,7 +1023,6 @@ describe('useFeatureFlags', () => { it.for(['"true"', '"false"', '1'])( 'is off for the malformed override value %s', (rawValue) => { - remoteConfigState.value = 'authenticated' localStorage.setItem( `ff:${ServerFeatureFlag.UNIFIED_WEB_SESSION}`, rawValue @@ -1016,8 +1033,7 @@ describe('useFeatureFlags', () => { ) it('lets a false ff: override turn off a server true', () => { - remoteConfigState.value = 'authenticated' - remoteConfig.value = { unified_web_session: true } + useRemoteConfigStore().acceptConfig({ unified_web_session: true }, true) localStorage.setItem( `ff:${ServerFeatureFlag.UNIFIED_WEB_SESSION}`, 'false' @@ -1027,8 +1043,7 @@ describe('useFeatureFlags', () => { }) it('lets a false ?ff= override beat a true ff: override and server value', () => { - remoteConfigState.value = 'authenticated' - remoteConfig.value = { unified_web_session: true } + useRemoteConfigStore().acceptConfig({ unified_web_session: true }, true) localStorage.setItem( `ff:${ServerFeatureFlag.UNIFIED_WEB_SESSION}`, 'true' @@ -1041,7 +1056,6 @@ describe('useFeatureFlags', () => { }) it('honours the ff: localStorage dev override', () => { - remoteConfigState.value = 'authenticated' localStorage.setItem( `ff:${ServerFeatureFlag.UNIFIED_WEB_SESSION}`, 'true' @@ -1051,7 +1065,6 @@ describe('useFeatureFlags', () => { }) it('honours the ?ff= session override', () => { - remoteConfigState.value = 'authenticated' vi.mocked(getSessionOverride).mockImplementation((flagKey) => flagKey === ServerFeatureFlag.UNIFIED_WEB_SESSION ? true : undefined ) @@ -1061,8 +1074,7 @@ describe('useFeatureFlags', () => { it('is off outside the cloud distribution', () => { vi.mocked(distributionTypes).isCloud = false - remoteConfigState.value = 'authenticated' - remoteConfig.value = { unified_web_session: true } + useRemoteConfigStore().acceptConfig({ unified_web_session: true }, true) expect(useFeatureFlags().flags.unifiedWebSessionEnabled).toBe(false) }) @@ -1077,7 +1089,7 @@ describe('useFeatureFlags', () => { `ff:${ServerFeatureFlag.SIGNUP_TURNSTILE}`, '"shadow"' ) - remoteConfig.value = { signup_turnstile: 'off' } + useRemoteConfigStore().acceptConfig({ signup_turnstile: 'off' }, false) vi.mocked(api.getServerFeature).mockReturnValue('off') const { flags } = useFeatureFlags() @@ -1102,7 +1114,10 @@ describe('useFeatureFlags', () => { ? false : undefined ) - remoteConfig.value = { node_library_essentials_enabled: true } + useRemoteConfigStore().acceptConfig( + { node_library_essentials_enabled: true }, + false + ) vi.mocked(api.getServerFeature).mockReturnValue(true) const { flags } = useFeatureFlags() @@ -1111,8 +1126,9 @@ describe('useFeatureFlags', () => { it('beats the auth-window fallback on auth-gated flags', () => { vi.mocked(distributionTypes).isCloud = true - remoteConfigState.value = 'unloaded' - cachedBillingControlEnabled.value = false + const store = useRemoteConfigStore() + store.acceptConfig({ billing_control_enabled: false }, true) + store.invalidate() vi.mocked(getSessionOverride).mockImplementation((flagKey) => flagKey === ServerFeatureFlag.BILLING_CONTROL_ENABLED ? true : undefined ) @@ -1128,77 +1144,76 @@ describe('useFeatureFlags', () => { it('is false off-cloud even when the authenticated config grants it', () => { vi.mocked(distributionTypes).isCloud = false - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { 'agent-in-app-experience': true } + useRemoteConfigStore().acceptConfig( + { 'agent-in-app-experience': true }, + true + ) const { flags } = useFeatureFlags() expect(flags.agentInAppExperienceEnabled).toBe(false) }) it('is false during the anonymous window even when the config already grants it', () => { - remoteConfigState.value = 'anonymous' - authenticatedRemoteConfigState.value = 'unloaded' - remoteConfig.value = { 'agent-in-app-experience': true } + useRemoteConfigStore().acceptConfig( + { 'agent-in-app-experience': true }, + false + ) const { flags } = useFeatureFlags() expect(flags.agentInAppExperienceEnabled).toBe(false) }) it('is true once the authenticated config grants it', () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { 'agent-in-app-experience': true } + useRemoteConfigStore().acceptConfig( + { 'agent-in-app-experience': true }, + true + ) const { flags } = useFeatureFlags() expect(flags.agentInAppExperienceEnabled).toBe(true) }) it('is false when the authenticated config omits the key', () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, true) const { flags } = useFeatureFlags() expect(flags.agentInAppExperienceEnabled).toBe(false) }) it('keeps this session granted when a later refresh fails transiently', () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { 'agent-in-app-experience': true } - sessionAgentGrant.value = true - sessionAgentGrantValidUntil.value = Date.now() + 60_000 + const store = useRemoteConfigStore() + store.acceptConfig({ 'agent-in-app-experience': true }, true) const { flags } = useFeatureFlags() expect(flags.agentInAppExperienceEnabled).toBe(true) - remoteConfigState.value = 'error' - authenticatedRemoteConfigState.value = 'error' + store.failLoad(true) expect(flags.agentInAppExperienceEnabled).toBe(true) }) it('expires the transient session grant after its bounded fallback window', () => { - remoteConfigState.value = 'error' - sessionAgentGrant.value = true - sessionAgentGrantValidUntil.value = Date.now() - 1 + const store = useRemoteConfigStore() + store.acceptConfig({ 'agent-in-app-experience': true }, true) + store.failLoad(true) + vi.advanceTimersByTime(15 * 60_000) const { flags } = useFeatureFlags() expect(flags.agentInAppExperienceEnabled).toBe(false) }) it('drops the grant when the session itself is gone', () => { - remoteConfigState.value = 'error' - remoteConfig.value = {} - sessionAgentGrant.value = undefined + const store = useRemoteConfigStore() + store.acceptConfig({ 'agent-in-app-experience': true }, true) + store.failLoad(true, 401) const { flags } = useFeatureFlags() expect(flags.agentInAppExperienceEnabled).toBe(false) }) it('treats an explicitly revoked grant as off during a refresh failure', () => { - remoteConfigState.value = 'error' - sessionAgentGrant.value = false + const store = useRemoteConfigStore() + store.acceptConfig({}, true) + store.failLoad(true) const { flags } = useFeatureFlags() expect(flags.agentInAppExperienceEnabled).toBe(false) diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index ac5d07db83f..e062e203f91 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -1,6 +1,6 @@ import type { GetFeaturesResponse } from '@comfyorg/ingest-types' +import { getActivePinia } from 'pinia' import { computed, reactive, readonly, watchEffect } from 'vue' -import type { Ref } from 'vue' import { normalizeHostedBillingDestination } from '@/platform/billing/billingWeb' import { @@ -8,13 +8,7 @@ import { showsCloudBillingNewUxOnLocal } from '@/platform/billing/localBillingWebEnabled' import { isCloud, isNightly } from '@/platform/distribution/types' -import { - isAuthenticatedConfigLoaded, - remoteConfig, - sessionAgentGrant, - sessionAgentGrantValidUntil, - useRemoteConfigCache -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { ServerFeatureFlag } from '@/platform/remoteConfig/serverFeatureFlag' import { useTelemetry } from '@comfyorg/telemetry' import { api } from '@/scripts/api' @@ -63,6 +57,8 @@ function resolveStrictBooleanFlag( } } +type RemoteConfigStore = ReturnType + /** * Resolves a per-user, Cloud-only flag that selects backend behavior. Off the * Cloud build it is always false; during the auth window it falls back to the @@ -70,9 +66,10 @@ function resolveStrictBooleanFlag( * the wrong backend before authenticated config confirms the flag. */ function resolveAuthGatedFlag( + store: RemoteConfigStore, flagKey: string, remoteConfigValue: boolean | undefined, - cachedValue: Ref + cachedValue: boolean | undefined ): boolean { const sessionOverride = getSessionOverride(flagKey) if (sessionOverride !== undefined) return sessionOverride @@ -81,7 +78,7 @@ function resolveAuthGatedFlag( if (override !== undefined) return override if (!isCloud) return false - if (!isAuthenticatedConfigLoaded.value) return cachedValue.value ?? false + if (!store.isAuthenticatedConfigLoaded) return cachedValue ?? false return remoteConfigValue ?? api.getServerFeature(flagKey, false) } @@ -95,10 +92,9 @@ function resolveAuthGatedFlag( * same account (PM-1707). */ function resolveWhitelistFlag( + store: RemoteConfigStore, flagKey: string, - remoteConfigValue: boolean | undefined, - grantedThisSession: Ref, - grantValidUntil: Ref + remoteConfigValue: boolean | undefined ): boolean { const sessionOverride = getSessionOverride(flagKey) if (sessionOverride !== undefined) return sessionOverride @@ -107,10 +103,10 @@ function resolveWhitelistFlag( if (override !== undefined) return override if (!isCloud) return false - if (!isAuthenticatedConfigLoaded.value) + if (!store.isAuthenticatedConfigLoaded) return ( - grantedThisSession.value === true && - (grantValidUntil.value ?? 0) > Date.now() + store.agentGrant === true && + (store.agentGrantValidUntil ?? 0) > Date.now() ) return remoteConfigValue === true @@ -120,11 +116,14 @@ function resolveWhitelistFlag( * Composable for reactive access to server-side feature flags */ export function useFeatureFlags() { + const ownerStore = getActivePinia() ? useRemoteConfigStore() : undefined + const remoteConfigStore = () => ownerStore ?? useRemoteConfigStore() + const remoteConfig = () => remoteConfigStore().config const hostedBillingDestination = () => normalizeHostedBillingDestination( resolveFlag( ServerFeatureFlag.HOSTED_BILLING_DESTINATION, - remoteConfig.value.hosted_billing_destination, + remoteConfig().hosted_billing_destination, 'stripe' ) ) @@ -150,7 +149,7 @@ export function useFeatureFlags() { get modelUploadButtonEnabled() { return resolveFlag( ServerFeatureFlag.MODEL_UPLOAD_BUTTON_ENABLED, - remoteConfig.value.model_upload_button_enabled, + remoteConfig().model_upload_button_enabled, false ) }, @@ -164,54 +163,54 @@ export function useFeatureFlags() { get privateModelsEnabled() { return resolveFlag( ServerFeatureFlag.PRIVATE_MODELS_ENABLED, - remoteConfig.value.private_models_enabled, + remoteConfig().private_models_enabled, false ) }, get onboardingSurveyEnabled() { return resolveFlag( ServerFeatureFlag.ONBOARDING_SURVEY_ENABLED, - remoteConfig.value.onboarding_survey_enabled, + remoteConfig().onboarding_survey_enabled, false ) }, get signedOutRerouteEnabled() { return resolveFlag( ServerFeatureFlag.SIGNED_OUT_REROUTE_ENABLED, - remoteConfig.value.signed_out_reroute_enabled, + remoteConfig().signed_out_reroute_enabled, false ) }, get partnerNodeGovernanceEnabled() { return resolveFlag( ServerFeatureFlag.PARTNER_NODE_GOVERNANCE_ENABLED, - remoteConfig.value.partner_node_governance_enabled, + remoteConfig().partner_node_governance_enabled, false ) }, get partnerRunGateEnabled() { return resolveFlag( ServerFeatureFlag.PARTNER_RUN_GATE_ENABLED, - remoteConfig.value.partner_run_gate_enabled, + remoteConfig().partner_run_gate_enabled, true ) }, get deploymentStartEnabled() { return resolveStrictBooleanFlag( ServerFeatureFlag.DEPLOYMENT_START_ENABLED, - remoteConfig.value.deployment_start_enabled + remoteConfig().deployment_start_enabled ) }, get partnerNodeTokenEnabled() { return resolveStrictBooleanFlag( ServerFeatureFlag.PARTNER_NODE_TOKEN, - remoteConfig.value.partner_node_token + remoteConfig().partner_node_token ) }, get userSecretsEnabled() { return resolveFlag( ServerFeatureFlag.USER_SECRETS_ENABLED, - remoteConfig.value.user_secrets_enabled, + remoteConfig().user_secrets_enabled, false ) }, @@ -221,7 +220,7 @@ export function useFeatureFlags() { get openOnCloudEnabled() { return resolveFlag( ServerFeatureFlag.OPEN_ON_CLOUD_ENABLED, - remoteConfig.value.open_on_cloud_enabled, + remoteConfig().open_on_cloud_enabled, import.meta.env.DEV ) }, @@ -229,7 +228,7 @@ export function useFeatureFlags() { return ( resolveFlag( ServerFeatureFlag.OPEN_ON_CLOUD_USE_LOCAL_AGENT_ENABLED, - remoteConfig.value.open_on_cloud_use_local_agent_enabled, + remoteConfig().open_on_cloud_use_local_agent_enabled, false ) === true ) @@ -240,35 +239,35 @@ export function useFeatureFlags() { get nodeLibraryEssentialsEnabled() { return resolveFlag( ServerFeatureFlag.NODE_LIBRARY_ESSENTIALS_ENABLED, - remoteConfig.value.node_library_essentials_enabled, + remoteConfig().node_library_essentials_enabled, isNightly || import.meta.env.DEV ) }, get comfyHubUploadEnabled() { return resolveFlag( ServerFeatureFlag.COMFYHUB_UPLOAD_ENABLED, - remoteConfig.value.comfyhub_upload_enabled, + remoteConfig().comfyhub_upload_enabled, false ) }, get comfyHubProfileGateEnabled() { return resolveFlag( ServerFeatureFlag.COMFYHUB_PROFILE_GATE_ENABLED, - remoteConfig.value.comfyhub_profile_gate_enabled, + remoteConfig().comfyhub_profile_gate_enabled, false ) }, get deploymentCompatibilityMarksEnabled() { return resolveFlag( ServerFeatureFlag.DEPLOYMENT_COMPATIBILITY_MARKS_ENABLED, - remoteConfig.value.deployment_compatibility_marks_enabled, + remoteConfig().deployment_compatibility_marks_enabled, false ) }, get runtimeLibraryModelsEnabled() { return resolveFlag( ServerFeatureFlag.RUNTIME_LIBRARY_MODELS_ENABLED, - remoteConfig.value.runtime_library_models_enabled, + remoteConfig().runtime_library_models_enabled, false ) }, @@ -276,14 +275,14 @@ export function useFeatureFlags() { get modelUploadFolders(): readonly string[] { return resolveFlag( ServerFeatureFlag.MODEL_UPLOAD_FOLDERS, - remoteConfig.value.model_upload_folders, + remoteConfig().model_upload_folders, [] ) }, get lateCustomNodesEnabled() { return resolveFlag( ServerFeatureFlag.LATE_CUSTOM_NODES_ENABLED, - remoteConfig.value.late_custom_nodes_enabled, + remoteConfig().late_custom_nodes_enabled, false ) }, @@ -303,18 +302,16 @@ export function useFeatureFlags() { if (!isCloud) return false const key = ServerFeatureFlag.UNIFIED_WEB_SESSION - // Overrides skip the server's web_session_enabled pairing; whoever overrides - // this key must also be in the web_session_enabled set. const value = getSessionOverride(key) ?? getDevOverride(key) ?? - remoteConfig.value.unified_web_session + remoteConfig().unified_web_session return value === true }, get webSessionLapseRecoveryEnabled() { return resolveFlag( ServerFeatureFlag.WEB_SESSION_LAPSE_RECOVERY_ENABLED, - remoteConfig.value.web_session_lapse_recovery_enabled, + remoteConfig().web_session_lapse_recovery_enabled, false ) }, @@ -323,7 +320,7 @@ export function useFeatureFlags() { return resolveStrictBooleanFlag( ServerFeatureFlag.SSO_ENABLED, - remoteConfig.value.sso_enabled + remoteConfig().sso_enabled ) }, /** Browser sign-in for a local ComfyUI that Desktop does not host. */ @@ -332,20 +329,21 @@ export function useFeatureFlags() { return resolveStrictBooleanFlag( ServerFeatureFlag.LOCAL_WEB_SSO, - remoteConfig.value.local_web_sso + remoteConfig().local_web_sso ) }, get billingControlEnabled() { return resolveAuthGatedFlag( + remoteConfigStore(), ServerFeatureFlag.BILLING_CONTROL_ENABLED, - remoteConfig.value.billing_control_enabled, - useRemoteConfigCache().cachedBillingControlEnabled + remoteConfig().billing_control_enabled, + remoteConfigStore().cachedBillingControlEnabled ) }, get memberCreditLimitsEnabled() { return resolveStrictBooleanFlag( ServerFeatureFlag.MEMBER_CREDIT_LIMITS_ENABLED, - remoteConfig.value.member_credit_limits_enabled + remoteConfig().member_credit_limits_enabled ) }, get billingNewUxEnabled() { @@ -353,13 +351,13 @@ export function useFeatureFlags() { ServerFeatureFlag.BILLING_NEW_UX_ENABLED, showsCloudBillingNewUxOnLocal() ? true - : remoteConfig.value.billing_new_ux_enabled + : remoteConfig().billing_new_ux_enabled ) }, get billingAutoTopUpAtCheckoutEnabled() { return resolveStrictBooleanFlag( ServerFeatureFlag.BILLING_AUTO_TOP_UP_AT_CHECKOUT_ENABLED, - remoteConfig.value.billing_auto_top_up_at_checkout_enabled + remoteConfig().billing_auto_top_up_at_checkout_enabled ) }, /** Top-up, subscription and billing reads run on the billing SDK on Cloud. */ @@ -370,40 +368,41 @@ export function useFeatureFlags() { if (!isCloud) return opensLocalBillingHandoff() return resolveStrictBooleanFlag( ServerFeatureFlag.UNIFIED_BILLING_SETTINGS, - remoteConfig.value.unified_billing_settings + remoteConfig().unified_billing_settings ) }, get pricingTableFallback() { return resolveStrictBooleanFlag( ServerFeatureFlag.PRICING_TABLE_FALLBACK, - remoteConfig.value.pricing_table_fallback + remoteConfig().pricing_table_fallback ) }, get oauthConsentSwitchAccountEnabled() { return resolveFlag( ServerFeatureFlag.OAUTH_CONSENT_SWITCH_ACCOUNT_ENABLED, - remoteConfig.value.oauth_consent_switch_account_enabled, + remoteConfig().oauth_consent_switch_account_enabled, false ) }, get v1PaymentRecovery() { return resolveAuthGatedFlag( + remoteConfigStore(), ServerFeatureFlag.V1_PAYMENT_RECOVERY, - remoteConfig.value.v1_payment_recovery, - useRemoteConfigCache().cachedV1PaymentRecovery + remoteConfig().v1_payment_recovery, + remoteConfigStore().cachedV1PaymentRecovery ) }, get signupTurnstileMode() { return resolveFlag( ServerFeatureFlag.SIGNUP_TURNSTILE, - remoteConfig.value.signup_turnstile, + remoteConfig().signup_turnstile, 'off' ) }, get supportsModelTypeTags() { return resolveFlag( ServerFeatureFlag.SUPPORTS_MODEL_TYPE_TAGS, - remoteConfig.value.supports_model_type_tags, + remoteConfig().supports_model_type_tags, false ) }, @@ -412,10 +411,9 @@ export function useFeatureFlags() { }, get agentInAppExperienceEnabled() { return resolveWhitelistFlag( + remoteConfigStore(), ServerFeatureFlag.AGENT_IN_APP_EXPERIENCE, - remoteConfig.value['agent-in-app-experience'], - sessionAgentGrant, - sessionAgentGrantValidUntil + remoteConfig()['agent-in-app-experience'] ) } }) diff --git a/src/config/comfyApi.test.ts b/src/config/comfyApi.test.ts index 19e6c182ab5..86ff63d3d3f 100644 --- a/src/config/comfyApi.test.ts +++ b/src/config/comfyApi.test.ts @@ -1,7 +1,7 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { getComfyApiBaseUrl, @@ -23,7 +23,7 @@ const baseUrlCases: BaseUrlCase[] = [ label: 'API', getBaseUrl: getComfyApiBaseUrl, setOverride: (value) => { - remoteConfig.value = { comfy_api_base_url: value } + useRemoteConfigStore().acceptConfig({ comfy_api_base_url: value }, false) }, defaultUrl: 'https://stagingapi.comfy.org' }, @@ -31,7 +31,10 @@ const baseUrlCases: BaseUrlCase[] = [ label: 'Cloud', getBaseUrl: getComfyCloudBaseUrl, setOverride: (value) => { - remoteConfig.value = { comfy_cloud_base_url: value } + useRemoteConfigStore().acceptConfig( + { comfy_cloud_base_url: value }, + false + ) }, defaultUrl: 'https://testcloud.comfy.org' }, @@ -39,7 +42,10 @@ const baseUrlCases: BaseUrlCase[] = [ label: 'Platform', getBaseUrl: getComfyPlatformBaseUrl, setOverride: (value) => { - remoteConfig.value = { comfy_platform_base_url: value } + useRemoteConfigStore().acceptConfig( + { comfy_platform_base_url: value }, + false + ) }, defaultUrl: 'https://stagingplatform.comfy.org' } @@ -48,14 +54,8 @@ const baseUrlCases: BaseUrlCase[] = [ describe.for(baseUrlCases)( '$label base URL', ({ getBaseUrl, setOverride, defaultUrl }) => { - const originalConfig = remoteConfig.value - beforeEach(() => { - remoteConfig.value = {} - }) - - afterEach(() => { - remoteConfig.value = originalConfig + useRemoteConfigStore().acceptConfig({}, false) }) it('honors a server-provided HTTPS override', () => { @@ -79,14 +79,8 @@ describe.for(baseUrlCases)( ) describe('compatibility with comfyui servers that predate the override keys', () => { - const originalConfig = remoteConfig.value - beforeEach(() => { - remoteConfig.value = {} - }) - - afterEach(() => { - remoteConfig.value = originalConfig + useRemoteConfigStore().acceptConfig({}, false) }) it('falls back to build-time defaults when /features omits the URL keys', async () => { diff --git a/src/config/comfyApi.ts b/src/config/comfyApi.ts index 4daeca75cac..e9111edd160 100644 --- a/src/config/comfyApi.ts +++ b/src/config/comfyApi.ts @@ -1,7 +1,7 @@ import { configValueOrDefault, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' + useRemoteConfigStore +} from '@/platform/remoteConfig/remoteConfigStore' const PROD_API_BASE_URL = 'https://api.comfy.org' const STAGING_API_BASE_URL = 'https://stagingapi.comfy.org' @@ -32,7 +32,11 @@ function resolveBaseUrl( | 'comfy_platform_base_url', defaultValue: string ): string { - const value = configValueOrDefault(remoteConfig.value, key, defaultValue) + const value = configValueOrDefault( + useRemoteConfigStore().config, + key, + defaultValue + ) try { const url = new URL(value) diff --git a/src/config/firebase.test.ts b/src/config/firebase.test.ts index 1249cad6a2a..165af7c7205 100644 --- a/src/config/firebase.test.ts +++ b/src/config/firebase.test.ts @@ -3,9 +3,10 @@ import { describe, expect, it, vi } from 'vitest' async function loadFirebase(useProdConfig: boolean) { vi.resetModules() vi.stubGlobal('__USE_PROD_CONFIG__', useProdConfig) - const { remoteConfig } = await import('@/platform/remoteConfig/remoteConfig') + const { useRemoteConfigStore } = + await import('@/platform/remoteConfig/remoteConfigStore') const { getFirebaseConfig } = await import('./firebase') - return { getFirebaseConfig, remoteConfig } + return { getFirebaseConfig, useRemoteConfigStore } } describe('getFirebaseConfig', () => { @@ -18,24 +19,24 @@ describe('getFirebaseConfig', () => { messagingSenderId: '1', appId: '1:1:web:abc' } - const { getFirebaseConfig, remoteConfig } = await loadFirebase(true) - remoteConfig.value = { firebase_config: cloud } + const { getFirebaseConfig, useRemoteConfigStore } = await loadFirebase(true) + useRemoteConfigStore().acceptConfig({ firebase_config: cloud }, false) expect(getFirebaseConfig()).toEqual(cloud) }) it('uses the dev project when the server reports firebase_env "dev", even if the build-time fallback is prod', async () => { - const { getFirebaseConfig, remoteConfig } = await loadFirebase(true) - remoteConfig.value = { firebase_env: 'dev' } + const { getFirebaseConfig, useRemoteConfigStore } = await loadFirebase(true) + useRemoteConfigStore().acceptConfig({ firebase_env: 'dev' }, false) expect(getFirebaseConfig().projectId).toBe('dreamboothy-dev') }) it('falls back to the build-time config when the server reports no firebase_env', async () => { const prod = await loadFirebase(true) - prod.remoteConfig.value = {} + prod.useRemoteConfigStore().acceptConfig({}, false) expect(prod.getFirebaseConfig().projectId).toBe('dreamboothy') const dev = await loadFirebase(false) - dev.remoteConfig.value = {} + dev.useRemoteConfigStore().acceptConfig({}, false) expect(dev.getFirebaseConfig().projectId).toBe('dreamboothy-dev') }) }) diff --git a/src/config/firebase.ts b/src/config/firebase.ts index 37f91bc5909..0a43d53ff4e 100644 --- a/src/config/firebase.ts +++ b/src/config/firebase.ts @@ -1,6 +1,6 @@ import type { FirebaseOptions } from 'firebase/app' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' const DEV_CONFIG: FirebaseOptions = { apiKey: 'AIzaSyDa_YMeyzV0SkVe92vBZ1tVikWBmOU5KVE', @@ -31,16 +31,15 @@ const BUILD_TIME_CONFIG = __USE_PROD_CONFIG__ ? PROD_CONFIG : DEV_CONFIG * else the bundled DEV_CONFIG when the server reports a dev-tier backend, else the build-time default. */ export function getFirebaseConfig(): FirebaseOptions { - const runtimeConfig = remoteConfig.value.firebase_config + const { config } = useRemoteConfigStore() + const runtimeConfig = config.firebase_config if (runtimeConfig) return runtimeConfig - if (remoteConfig.value.firebase_env === 'dev') return DEV_CONFIG + if (config.firebase_env === 'dev') return DEV_CONFIG return BUILD_TIME_CONFIG } /** Whether {@link getFirebaseConfig} names the project from the server rather than the build. */ export function hasServerFirebaseConfig(): boolean { - return ( - Boolean(remoteConfig.value.firebase_config) || - remoteConfig.value.firebase_env === 'dev' - ) + const { config } = useRemoteConfigStore() + return Boolean(config.firebase_config) || config.firebase_env === 'dev' } diff --git a/src/config/turnstile.test.ts b/src/config/turnstile.test.ts index 50c9c64819e..52b67cca66b 100644 --- a/src/config/turnstile.test.ts +++ b/src/config/turnstile.test.ts @@ -1,18 +1,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { getTurnstileSiteKey } from '@/config/turnstile' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' const TURNSTILE_TEST_SITE_KEY = '1x00000000000000000000AA' // __USE_PROD_CONFIG__ is false under vitest (see vitest.setup.ts), so the // build-time fallback resolves to the staging sitekey. const STAGING_TURNSTILE_SITE_KEY = '0x4AAAAAADnYY4_Q0qxHZ5a7' -vi.mock(import('@/platform/remoteConfig/remoteConfig')) - describe('getTurnstileSiteKey', () => { beforeEach(() => { - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, false) vi.stubGlobal('__DISTRIBUTION__', 'localhost') }) @@ -31,7 +29,10 @@ describe('getTurnstileSiteKey', () => { it('ignores remote config (the widget is cloud-only)', () => { vi.stubEnv('DEV', false) - remoteConfig.value = { turnstile_sitekey: '0xshould-not-be-used' } + useRemoteConfigStore().acceptConfig( + { turnstile_sitekey: '0xshould-not-be-used' }, + false + ) expect(getTurnstileSiteKey()).toBe('') }) @@ -43,7 +44,10 @@ describe('getTurnstileSiteKey', () => { }) it('returns the sitekey delivered via remote config', () => { - remoteConfig.value = { turnstile_sitekey: '0x4AAAAAreal' } + useRemoteConfigStore().acceptConfig( + { turnstile_sitekey: '0x4AAAAAreal' }, + false + ) expect(getTurnstileSiteKey()).toBe('0x4AAAAAreal') }) diff --git a/src/config/turnstile.ts b/src/config/turnstile.ts index 937bbed3ece..c3232ed05c3 100644 --- a/src/config/turnstile.ts +++ b/src/config/turnstile.ts @@ -1,7 +1,7 @@ import { configValueOrDefault, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' + useRemoteConfigStore +} from '@/platform/remoteConfig/remoteConfigStore' /** * Cloudflare Turnstile always-pass test sitekey, used only in local dev so the @@ -32,7 +32,7 @@ export function getTurnstileSiteKey(): string { } return configValueOrDefault( - remoteConfig.value, + useRemoteConfigStore().config, 'turnstile_sitekey', __USE_PROD_CONFIG__ ? PROD_TURNSTILE_SITE_KEY : STAGING_TURNSTILE_SITE_KEY ) diff --git a/src/core/graph/widgets/dynamicGroupDiagnostics.test.ts b/src/core/graph/widgets/dynamicGroupDiagnostics.test.ts index d987da7a9b0..7c510fe4c90 100644 --- a/src/core/graph/widgets/dynamicGroupDiagnostics.test.ts +++ b/src/core/graph/widgets/dynamicGroupDiagnostics.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import * as Y from 'yjs' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { reportError } from '@comfyorg/telemetry/reportError' import { useLitegraphService } from '@/services/litegraphService' import { useLinkStore } from '@/stores/linkStore' @@ -54,12 +54,11 @@ function refuseInputChanges() { } beforeEach(() => { - remoteConfig.value = { enable_telemetry: true } + useRemoteConfigStore().acceptConfig({ enable_telemetry: true }, false) }) afterEach(() => { distribution.isCloud = false - remoteConfig.value = {} }) describe('DynamicGroup row refusal reports', () => { @@ -155,7 +154,10 @@ describe('DynamicGroup row refusal reports', () => { 'sends with cloud=$isCloud and host telemetry=$enableTelemetry: $reported', ({ isCloud, enableTelemetry, reported }) => { distribution.isCloud = isCloud - remoteConfig.value = { enable_telemetry: enableTelemetry } + useRemoteConfigStore().acceptConfig( + { enable_telemetry: enableTelemetry }, + false + ) const { widget } = group(`Gated ${isCloud} ${enableTelemetry}`) refuseInputChanges() @@ -388,7 +390,7 @@ describe('remote DynamicGroup row count reports', () => { }) it('counts but does not send a mismatch without telemetry consent', () => { - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, false) const { setRows } = remoteGroup('ConsentDynamicGroup') refuseInputChanges() diff --git a/src/core/graph/widgets/dynamicGroupEnforcementBoundary.test.ts b/src/core/graph/widgets/dynamicGroupEnforcementBoundary.test.ts index 9878ad5f072..9fa377038b5 100644 --- a/src/core/graph/widgets/dynamicGroupEnforcementBoundary.test.ts +++ b/src/core/graph/widgets/dynamicGroupEnforcementBoundary.test.ts @@ -4,7 +4,7 @@ import * as Y from 'yjs' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' import type { IBaseWidget } from '@comfyorg/graph-model/widgets' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useLitegraphService } from '@/services/litegraphService' import { toNodeId } from '@comfyorg/graph-model/nodeId' import { followedDoc } from '@/workbench/extensions/agent/crdt/__fixtures__/followedDoc' @@ -117,7 +117,7 @@ function floatFields( } beforeEach(() => { - remoteConfig.value = { enable_telemetry: true } + useRemoteConfigStore().acceptConfig({ enable_telemetry: true }, false) for (const type of [ 'BoundaryAddNodeAboveMax', 'BoundaryAddNodeUnbounded', diff --git a/src/extensions/core/cloudBadges.ts b/src/extensions/core/cloudBadges.ts index 174df1db6e1..fc756cae903 100644 --- a/src/extensions/core/cloudBadges.ts +++ b/src/extensions/core/cloudBadges.ts @@ -1,15 +1,14 @@ -import { computed, effectScope, watch } from 'vue' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { effectScope, watch } from 'vue' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useBootDeploymentFullLabel } from '@/platform/workspace/composables/useDeploymentLabels' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { toTitleCase } from '@/utils/textCaseUtil' import type { ComfyExtension, TopbarBadge } from '@/types/comfy' -const badges = computed(() => { +function serverHealthBadges(): TopbarBadge[] { const result: TopbarBadge[] = [] - // Add server health alert first (if present) - const alert = remoteConfig.value.server_health_alert + const alert = useRemoteConfigStore().config.server_health_alert if (alert) { const message = toTitleCase(alert.message) result.push({ @@ -20,7 +19,7 @@ const badges = computed(() => { }) } return result -}) +} const canvasInfoTextScope = effectScope(true) @@ -39,7 +38,7 @@ function syncCanvasInfoText() { export const cloudBadgesExtension: ComfyExtension = { name: 'Comfy.Cloud.Badges', get topbarBadges() { - return badges.value + return serverHealthBadges() }, init() { canvasInfoTextScope.run(syncCanvasInfoText) diff --git a/src/main.ts b/src/main.ts index debd1fef4eb..35ed893aef8 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,5 @@ import { captureMessage } from '@sentry/vue' -import { createPinia } from 'pinia' +import { createPinia, setActivePinia } from 'pinia' import type { Pinia } from 'pinia' import 'primeicons/primeicons.css' import { createApp } from 'vue' @@ -13,8 +13,8 @@ import { installCloudApiAuth } from '@/platform/auth/cloudApiAuthProvider' import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import { configValueOrDefault, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' + useRemoteConfigStore +} from '@/platform/remoteConfig/remoteConfigStore' import { reportAssertFailure } from '@/platform/telemetry/assertFailureReporter' import { initSentry } from '@/platform/telemetry/initSentry' import { @@ -125,7 +125,11 @@ function initFirebaseIdentity(): void { function resolveRuntimeSentryDsn(): string { return isCloud - ? configValueOrDefault(remoteConfig.value, 'sentry_dsn', __SENTRY_DSN__) + ? configValueOrDefault( + useRemoteConfigStore().config, + 'sentry_dsn', + __SENTRY_DSN__ + ) : __SENTRY_DSN__ } @@ -164,7 +168,7 @@ function installSubgraphGraphHooks(): void { autoExposeKnownPreviewNodes(hostNode) } -async function bootstrap(): Promise { +async function bootstrap(pinia: Pinia): Promise { bootstrapTracer.recordSinceTimeOrigin('startup/entry-modules') api.captureLaunchContext() captureSafeExtensionBoot() @@ -185,7 +189,6 @@ async function bootstrap(): Promise { const localSignInFailed = await startLocalAuthSession() initFirebaseIdentity() - const pinia = createPinia() const router = await bootstrapTracer.settle('startup/router', createAppRouter) const app = createApp(App) @@ -213,4 +216,6 @@ async function bootstrap(): Promise { bootstrapTracer.milestone('app-mounted') } -if (!(await handleDesktopWorkflowHandoff())) await bootstrap() +const pinia = createPinia() +setActivePinia(pinia) +if (!(await handleDesktopWorkflowHandoff())) await bootstrap(pinia) diff --git a/src/platform/account/auth/WorkspaceAuthGate.test.ts b/src/platform/account/auth/WorkspaceAuthGate.test.ts index 2a4ea3fe10a..213d07c0a33 100644 --- a/src/platform/account/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/account/auth/WorkspaceAuthGate.test.ts @@ -23,10 +23,7 @@ import { useAuthActions } from '@/composables/auth/useAuthActions' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities' import enMessages from '@/locales/en/main.json' with { type: 'json' } -import { - remoteConfigErrorStatus, - remoteConfigState -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { stubAccountIdentityPort, @@ -91,8 +88,8 @@ describe('WorkspaceAuthGate', () => { Object.assign(useAuthStore(), { isInitialized: false }) Object.assign(useAuthStore(), { currentUser: null }) Object.assign(useApiKeyAuthStore(), { isAuthenticated: false }) - remoteConfigState.value = 'authenticated' - remoteConfigErrorStatus.value = null + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig(remoteConfigStore.config, true) Object.assign(useTeamWorkspaceStore(), { initState: 'uninitialized' }) Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-123' @@ -599,7 +596,7 @@ describe('WorkspaceAuthGate', () => { }) it('shows a recoverable error when authenticated config is unavailable', async () => { - remoteConfigState.value = 'error' + useRemoteConfigStore().failLoad(true) mountComponent() await flushPromises() @@ -612,8 +609,7 @@ describe('WorkspaceAuthGate', () => { it('requires sign out when authenticated config rejects the credential', async () => { const user = userEvent.setup() - remoteConfigState.value = 'error' - remoteConfigErrorStatus.value = 401 + useRemoteConfigStore().failLoad(true, 401) mountComponent() await flushPromises() diff --git a/src/platform/account/auth/WorkspaceAuthGate.vue b/src/platform/account/auth/WorkspaceAuthGate.vue index b0e7d7ce155..0632b176413 100644 --- a/src/platform/account/auth/WorkspaceAuthGate.vue +++ b/src/platform/account/auth/WorkspaceAuthGate.vue @@ -99,10 +99,7 @@ import { useFeatureFlags } from '@/composables/useFeatureFlags' import { SessionRevokedError } from '@/platform/auth/session/sessionRevokedError' import { signedInOnWebSession } from '@comfyorg/api-client/webSessionFetch' import { isCloud } from '@/platform/distribution/types' -import { - remoteConfigErrorStatus, - remoteConfigState -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' import { reportError } from '@comfyorg/telemetry/reportError' import type { ReportErrorOptions } from '@comfyorg/telemetry/reportError' @@ -123,6 +120,7 @@ const initializationState = ref< const initializationRetryable = ref(true) const errorPanel = useTemplateRef('errorPanel') const billingCapabilities = useBillingCapabilities() +const remoteConfigStore = useRemoteConfigStore() syncWorkspaceTelemetryContext() let initializationGeneration = 0 let initializationController: AbortController | null = null @@ -190,7 +188,7 @@ async function initialize(): Promise { }) ]).finally(() => clearTimeout(timeoutId)) if (generation !== initializationGeneration) return - if (remoteConfigState.value !== 'authenticated') { + if (remoteConfigStore.loadState !== 'authenticated') { throw new Error('Failed to load authenticated remote config') } @@ -249,8 +247,8 @@ function initializationFailureReport( function isRetryableInitializationError(error: unknown): boolean { if ( - remoteConfigErrorStatus.value === 401 || - remoteConfigErrorStatus.value === 403 + remoteConfigStore.errorStatus === 401 || + remoteConfigStore.errorStatus === 403 ) { return false } diff --git a/src/platform/account/components/dialogs/settings/BillingTab.test.ts b/src/platform/account/components/dialogs/settings/BillingTab.test.ts index ddc36c58cc0..bae43580e33 100644 --- a/src/platform/account/components/dialogs/settings/BillingTab.test.ts +++ b/src/platform/account/components/dialogs/settings/BillingTab.test.ts @@ -33,7 +33,6 @@ import { } from '@/platform/billing/composables/__mocks__/servedBillingNotices' import { receiveServerFact } from '@/platform/serverFacts/serverFact' import type { BillingTopUpDenial, Plan } from '@comfyorg/billing-core' -import { useFreeTierQuota } from '@/platform/billing/subscription/composables/useFreeTierQuota' import { useTelemetry } from '@comfyorg/telemetry' import { reportError } from '@comfyorg/telemetry/reportError' import { billingApi } from '@/platform/billing/api/billingApi' @@ -65,7 +64,6 @@ vi.mock(import('@/platform/billing/composables/useSubscriptionPaywall')) vi.mock(import('@/composables/useFeatureFlags')) vi.mock(import('@/platform/billing/composables/useBillingCapabilities')) vi.mock(import('@/platform/billing/composables/useBillingUI')) -vi.mock(import('@/platform/billing/subscription/composables/useFreeTierQuota')) vi.mock(import('@/platform/billing/api/billingApi')) vi.mock(import('@comfyorg/telemetry')) vi.mock(import('@/platform/billing/localBillingHandoff')) @@ -277,13 +275,6 @@ function arrange(scenario: Scenario = {}) { refresh }) ) - vi.mocked(useFreeTierQuota).mockReturnValue( - fromPartial({ - quotaEnabled: computed(() => false), - available: ref(0), - maxAvailable: ref(0) - }) - ) render(BillingTab, { global: { diff --git a/src/platform/account/components/dialogs/settings/BillingTabLegacy.test.ts b/src/platform/account/components/dialogs/settings/BillingTabLegacy.test.ts index cf9dfd1f3ed..e3684c40bcc 100644 --- a/src/platform/account/components/dialogs/settings/BillingTabLegacy.test.ts +++ b/src/platform/account/components/dialogs/settings/BillingTabLegacy.test.ts @@ -23,7 +23,6 @@ import type { import { useFeatureFlags } from '@/composables/useFeatureFlags' import { receiveServerFact } from '@/platform/serverFacts/serverFact' import type { BillingTopUpDenial, Plan } from '@comfyorg/billing-core' -import { useFreeTierQuota } from '@/platform/billing/subscription/composables/useFreeTierQuota' import { useTelemetry } from '@comfyorg/telemetry' import { reportError } from '@comfyorg/telemetry/reportError' import { billingApi } from '@/platform/billing/api/billingApi' @@ -55,7 +54,6 @@ vi.mock(import('@/platform/billing/composables/useSubscriptionPaywall')) vi.mock(import('@/composables/useFeatureFlags')) vi.mock(import('@/platform/billing/composables/useBillingCapabilities')) vi.mock(import('@/platform/billing/composables/useBillingUI')) -vi.mock(import('@/platform/billing/subscription/composables/useFreeTierQuota')) vi.mock(import('@/platform/billing/api/billingApi')) vi.mock(import('@comfyorg/telemetry')) vi.mock(import('@/platform/billing/localBillingHandoff'), { spy: true }) @@ -240,13 +238,6 @@ function arrange(scenario: Scenario = {}) { refresh }) ) - vi.mocked(useFreeTierQuota).mockReturnValue( - fromPartial({ - quotaEnabled: computed(() => false), - available: ref(0), - maxAvailable: ref(0) - }) - ) render(BillingTab, { global: { diff --git a/src/platform/auth/firebaseIdentity.test.ts b/src/platform/auth/firebaseIdentity.test.ts index 59b49e86647..c0e48f50099 100644 --- a/src/platform/auth/firebaseIdentity.test.ts +++ b/src/platform/auth/firebaseIdentity.test.ts @@ -15,18 +15,13 @@ const RUNTIME_CONFIG = { appId: '999' } -/** - * Each case needs an identity that has not resolved yet, so it imports a - * fresh module graph along with the SDK and remote-config instances that - * graph binds to. - */ async function loadFresh() { vi.resetModules() const [identity, firebaseApp, firebaseAuth, remote] = await Promise.all([ import('./firebaseIdentity'), import('firebase/app'), import('firebase/auth'), - import('@/platform/remoteConfig/remoteConfig') + import('@/platform/remoteConfig/remoteConfigStore') ]) return { ...identity, ...firebaseApp, ...firebaseAuth, ...remote } } @@ -75,11 +70,11 @@ describe('firebaseIdentity', () => { vi.mocked(initializeAuth).mockReturnValue( fromPartial({ currentUser: signedIn }) ) - sdk.remoteConfigState.value = 'anonymous' - sdk.remoteConfig.value = { - ...sdk.remoteConfig.value, - firebase_config: RUNTIME_CONFIG - } + const remoteConfigStore = sdk.useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { ...remoteConfigStore.config, firebase_config: RUNTIME_CONFIG }, + false + ) firebaseIdentity.initialize() @@ -92,9 +87,9 @@ describe('firebaseIdentity', () => { 'refuses to resolve while remote config is still unloaded instead of booting on build-time config (DEV: $dev)', async ({ dev }) => { vi.stubEnv('DEV', dev) - const { firebaseIdentity, initializeApp, remoteConfigState } = + const { firebaseIdentity, initializeApp, useRemoteConfigStore } = await loadFresh() - remoteConfigState.value = 'unloaded' + useRemoteConfigStore().invalidate() expect(() => firebaseIdentity.initialize()).toThrow(/remote config/) expect(initializeApp).not.toHaveBeenCalled() @@ -106,13 +101,13 @@ describe('firebaseIdentity', () => { firebaseIdentity, initializeApp, initializeAuth, - remoteConfig, - remoteConfigState + useRemoteConfigStore } = await loadFresh() vi.mocked(initializeApp).mockReturnValue(defaultApp) vi.mocked(initializeAuth).mockReturnValue(fromPartial({})) - remoteConfigState.value = 'error' - remoteConfig.value = {} + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig({}, false) + remoteConfigStore.failLoad(false) firebaseIdentity.initialize() @@ -132,11 +127,11 @@ describe('firebaseIdentity', () => { initializeApp, initializeAuth } = sdk - sdk.remoteConfigState.value = 'anonymous' - sdk.remoteConfig.value = { - ...sdk.remoteConfig.value, - firebase_config: RUNTIME_CONFIG - } + const remoteConfigStore = sdk.useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { ...remoteConfigStore.config, firebase_config: RUNTIME_CONFIG }, + false + ) vi.mocked(getApps).mockReturnValue([defaultApp]) vi.mocked(initializeAuth).mockReturnValue( fromPartial({ currentUser: signedIn }) diff --git a/src/platform/auth/firebaseIdentity.ts b/src/platform/auth/firebaseIdentity.ts index 28aa6699c2f..e04294039ac 100644 --- a/src/platform/auth/firebaseIdentity.ts +++ b/src/platform/auth/firebaseIdentity.ts @@ -7,7 +7,7 @@ import { import { createFirebaseIdentity } from '@comfyorg/account-core/firebase' import { getFirebaseConfig } from '@/config/firebase' -import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' class FirebaseBeforeRemoteConfigError extends Error { constructor() { @@ -19,7 +19,7 @@ class FirebaseBeforeRemoteConfigError extends Error { } function loadedFirebaseConfig() { - if (remoteConfigState.value === 'unloaded') { + if (useRemoteConfigStore().loadState === 'unloaded') { throw new FirebaseBeforeRemoteConfigError() } return getFirebaseConfig() diff --git a/src/platform/auth/nonWebClientsStayOnTokens.test.ts b/src/platform/auth/nonWebClientsStayOnTokens.test.ts index 3f6dd926f2e..8c663f783ba 100644 --- a/src/platform/auth/nonWebClientsStayOnTokens.test.ts +++ b/src/platform/auth/nonWebClientsStayOnTokens.test.ts @@ -19,7 +19,6 @@ import { installDesktopLoginRedemption } from '@/platform/cloud/onboarding/deskt import * as distributionTypes from '@/platform/distribution/types' import { capturePreservedQuery } from '@/platform/navigation/preservedQueryManager' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' import { api } from '@/scripts/api' import type { ComfyApp } from '@/scripts/app' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' @@ -259,7 +258,7 @@ const apiCalls = (auth: Record): RecordedRequest[] => [ } ] -const API_KEY_GOLDEN: RecordedRequest[] = [ +const apiKeyGolden = (): RecordedRequest[] => [ FEATURES_BOOTSTRAP, { method: 'POST', @@ -316,7 +315,6 @@ describe('clients the web session leaves on tokens', () => { afterEach(() => { hooks?.stop() hooks = undefined - remoteConfig.value = {} }) it.for([...FEATURE_ROWS, ...API_KEY_SESSION_ROWS])( @@ -331,7 +329,7 @@ describe('clients the web session leaves on tokens', () => { await sendApiCalls() await vi.advanceTimersByTimeAsync(0) - expect(recorder.all).toEqual(API_KEY_GOLDEN) + expect(recorder.all).toEqual(apiKeyGolden()) expectNoSessionTraffic(recorder.all) } ) diff --git a/src/platform/auth/webSessionFlagOff.test.ts b/src/platform/auth/webSessionFlagOff.test.ts index 4665ccff6a8..da8ea45f665 100644 --- a/src/platform/auth/webSessionFlagOff.test.ts +++ b/src/platform/auth/webSessionFlagOff.test.ts @@ -21,7 +21,6 @@ import { installCloudApiAuth } from '@/platform/auth/cloudApiAuthProvider' import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore' import { takeInteractiveSignIn } from '@/platform/auth/session/interactiveSignInMarker' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' import { useTelemetry } from '@comfyorg/telemetry' import { useBillingReadRail } from '@/platform/billing/composables/useBillingReadRail' import { TOKEN_REFRESH_BUFFER_MS } from '@/platform/workspace/workspaceConstants' @@ -398,7 +397,9 @@ const SIGN_OUT: RecordedRequest[] = [ const CUSTOMER_PROVISIONING: RecordedRequest = { method: 'POST', - path: `${getComfyApiBaseUrl()}/customers`, + get path() { + return `${getComfyApiBaseUrl()}/customers` + }, headers: { authorization: 'Bearer firebase-id-token', 'content-type': 'application/json' @@ -468,7 +469,6 @@ describe('cloud auth requests with unified_web_session off', () => { afterEach(() => { hooks?.stop() hooks = undefined - remoteConfig.value = {} }) it.for([ @@ -580,7 +580,6 @@ describe.for([ afterEach(() => { hooks?.stop() hooks = undefined - remoteConfig.value = {} }) it('reads on the Firebase-minted Cloud JWT and re-mints a 401 through Firebase once', async () => { @@ -686,10 +685,6 @@ describe.for([ identity.reset() }) - afterEach(() => { - remoteConfig.value = {} - }) - it.for([ { name: 'a Firebase login', user: FIREBASE_USER, expected: 'signed_in' }, { name: 'no login', user: null, expected: 'signed_out' } @@ -714,10 +709,6 @@ describe('an interactive sign-in with unified_web_session off', () => { sessionStorage.clear() }) - afterEach(() => { - remoteConfig.value = {} - }) - it('never consumes the marker and sends no session request or session event', async () => { const recorder = installFetchRecorder({}) await refreshRemoteConfig({ useAuth: false }) @@ -738,10 +729,6 @@ describe('Firebase-only account actions with unified_web_session off', () => { identity.reset() }) - afterEach(() => { - remoteConfig.value = {} - }) - const EMAIL_USER = fromPartial({ uid: 'user-a', providerData: [{ providerId: 'password' }] diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index 96931d011e2..d11890f7e6e 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -65,7 +65,6 @@ import { installCloudApiAuth } from '@/platform/auth/cloudApiAuthProvider' import { useTelemetry } from '@comfyorg/telemetry' import { reportError } from '@comfyorg/telemetry/reportError' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' import { useToast } from '@/components/ui/toast/toastStore' import { billingApi } from '@/platform/billing/api/billingApi' import { installWorkspaceApiAuth } from '@/platform/workspace/api/workspaceApiAuth' @@ -434,7 +433,6 @@ describe('cloud app on the shared web session (unified_web_session on)', () => { afterEach(() => { hooks?.stop() hooks = undefined - remoteConfig.value = {} }) it('creates the session once per interactive sign-in, never on refresh, and deletes it on sign-out', async () => { @@ -944,7 +942,6 @@ describe('cloud API requests on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -1172,7 +1169,6 @@ describe('workspace API and global settings on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -1339,7 +1335,6 @@ describe('live updates and media on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -1734,7 +1729,6 @@ describe('comfy-api calls on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2044,7 +2038,6 @@ describe('billing SDK rails on a tab that arrived by session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2162,7 +2155,6 @@ describe('the Run token on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2468,7 +2460,6 @@ describe('a sibling tab on the unified Cloud JWT', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2574,7 +2565,6 @@ describe('billing on a tab that arrived by session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2692,10 +2682,6 @@ describe('a tab that arrived on the session with no Firebase login', () => { vi.spyOn(api, 'resetSocket').mockResolvedValue() }) - afterEach(() => { - remoteConfig.value = {} - }) - it('takes its identity from the session', async () => { const { authStore } = await bootSessionOnly() const user = useCurrentUser() @@ -2774,10 +2760,6 @@ describe('booting the cloud identity from the session', () => { vi.spyOn(api, 'resetSocket').mockResolvedValue() }) - afterEach(() => { - remoteConfig.value = {} - }) - it('signs in on the session alone', async () => { const { server, authStore } = await install({ userId: 'user-a' }) identity.resolve(null) @@ -3029,6 +3011,7 @@ describe('booting the cloud identity from the session', () => { markInteractiveSignIn('user-a') const reloaded = createDisposablePinia() setActivePinia(reloaded.pinia) + await refreshRemoteConfig({ useAuth: false }) useAuthStore() identity.resolve(USER_A) @@ -3208,6 +3191,7 @@ describe('signing in again after a sign-out', () => { const page = createDisposablePinia() pages.push(page) setActivePinia(page.pinia) + await refreshRemoteConfig({ useAuth: false }) useAuthStore() identity.resolve(user) const webSession = useCloudWebSessionStore() @@ -3239,7 +3223,6 @@ describe('signing in again after a sign-out', () => { afterEach(() => { pages.splice(0).forEach((page) => page[Symbol.dispose]()) - remoteConfig.value = {} }) it('creates the session once on the reload after an interactive sign-in, then signs in', async () => { @@ -3300,10 +3283,10 @@ describe('signing in again after a sign-out', () => { it('keeps the marker when a pending sign-in fails to create the session, so the next load retries', async () => { const server = installServer('revoked') - await refreshRemoteConfig({ useAuth: false }) const page = createDisposablePinia() pages.push(page) setActivePinia(page.pinia) + await refreshRemoteConfig({ useAuth: false }) useAuthStore() server.dropPosts = true await useAuthStore().login('user-a@example.com', 'password') @@ -3324,10 +3307,10 @@ describe('signing in again after a sign-out', () => { unified_web_session: false } const server = installServer('revoked', features) - await refreshRemoteConfig({ useAuth: false }) const loginPage = createDisposablePinia() pages.push(loginPage) setActivePinia(loginPage.pinia) + await refreshRemoteConfig({ useAuth: false }) await useAuthStore().login('user-a@example.com', 'password') features.unified_web_session = true await refreshRemoteConfig({ useAuth: false }) @@ -3373,7 +3356,6 @@ describe('a lapsed SSO session signs in again through SSO (sso_enabled)', () => afterEach(() => { pages.splice(0).forEach((page) => page[Symbol.dispose]()) - remoteConfig.value = {} }) const loadPage = async ( @@ -3728,10 +3710,6 @@ describe('an SSO account with no Firebase login (sso_enabled)', () => { vi.spyOn(api, 'resetSocket').mockResolvedValue() }) - afterEach(() => { - remoteConfig.value = {} - }) - it.for<{ name: string sso: boolean @@ -3891,7 +3869,6 @@ describe('an SSO session with no Firebase login reaching Firebase-only paths', ( }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.DESKTOP_LOGIN) }) diff --git a/src/platform/billing/billingWeb.test.ts b/src/platform/billing/billingWeb.test.ts index 8ea48ae5532..bcc6d4b4900 100644 --- a/src/platform/billing/billingWeb.test.ts +++ b/src/platform/billing/billingWeb.test.ts @@ -1,4 +1,4 @@ -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { getBillingWebUrl, @@ -26,10 +26,6 @@ describe('normalizeHostedBillingDestination', () => { }) describe('getBillingWebUrl', () => { - beforeEach(() => { - remoteConfig.value = {} - }) - it('accepts an HTTPS deployment URL from the env fallback', () => { vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org/app') @@ -53,21 +49,27 @@ describe('getBillingWebUrl', () => { }) it('prefers the server value over the env fallback', () => { - remoteConfig.value = { billing_web_url: 'https://stagingbilling.comfy.org' } + useRemoteConfigStore().acceptConfig( + { billing_web_url: 'https://stagingbilling.comfy.org' }, + false + ) vi.stubEnv('VITE_BILLING_WEB_URL', 'http://localhost:5174') expect(getBillingWebUrl()?.href).toBe('https://stagingbilling.comfy.org/') }) it('falls through to the env fallback when the server sends nothing', () => { - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, false) vi.stubEnv('VITE_BILLING_WEB_URL', 'http://localhost:5174') expect(getBillingWebUrl()?.href).toBe('http://localhost:5174/') }) it('fails closed to null when the server value is invalid, ignoring the env fallback', () => { - remoteConfig.value = { billing_web_url: 'http://billing.example.com' } + useRemoteConfigStore().acceptConfig( + { billing_web_url: 'http://billing.example.com' }, + false + ) vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') expect(getBillingWebUrl()).toBeNull() diff --git a/src/platform/billing/billingWeb.ts b/src/platform/billing/billingWeb.ts index 43c5bcecf03..1d279a7036a 100644 --- a/src/platform/billing/billingWeb.ts +++ b/src/platform/billing/billingWeb.ts @@ -1,6 +1,6 @@ import type { HostedBillingDestination } from '@comfyorg/account-core/billing' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']) @@ -55,7 +55,7 @@ function validateBillingWebUrl(value: string): URL | null { * hosted-billing rollout already takes for an unresolved destination. */ export function getBillingWebUrl(): URL | null { - const fromServer = remoteConfig.value.billing_web_url + const fromServer = useRemoteConfigStore().config.billing_web_url if (typeof fromServer === 'string' && fromServer !== '') { return validateBillingWebUrl(fromServer) } diff --git a/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.test.ts index 91fbff8c4a9..5ff8381a1dc 100644 --- a/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -31,7 +31,7 @@ import { useTelemetry } from '@comfyorg/telemetry' import { TelemetryRegistry } from '@comfyorg/telemetry/TelemetryRegistry' import { DatadogRumTelemetryProvider } from '@/platform/telemetry/providers/cloud/DatadogRumTelemetryProvider' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -628,12 +628,10 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('says Subscribe keeps runs going while the served free runs remain', () => { - remoteConfig.value = { - free_tier_balance: { allowance: 5, remaining: 3, used: 2 } - } - onTestFinished(() => { - remoteConfig.value = {} - }) + useRemoteConfigStore().acceptConfig( + { free_tier_balance: { allowance: 5, remaining: 3, used: 2 } }, + false + ) const billing = mockBillingContext() billing.isInitialized.value = true billing.subscriptionState = computed(() => 'never_subscribed') @@ -1034,7 +1032,10 @@ describe('TopUpCreditsDialogContentWorkspace', () => { .spyOn(billingApi, 'createTopupCheckout') .mockResolvedValue({ checkout_url: checkoutUrl }) window.__comfyDesktop2 = {} - remoteConfig.value = { billing_web_url: 'https://testbilling.comfy.org' } + useRemoteConfigStore().acceptConfig( + { billing_web_url: 'https://testbilling.comfy.org' }, + false + ) const open = vi.spyOn(window, 'open').mockReturnValue(null) const appUrl = window.location.href @@ -1056,7 +1057,6 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(window.location.href).toBe(appUrl) } finally { delete window.__comfyDesktop2 - remoteConfig.value = {} } }) diff --git a/src/platform/billing/composables/useBillingCapabilities.test.ts b/src/platform/billing/composables/useBillingCapabilities.test.ts index 29fcad7aa0e..3316dfbb4b9 100644 --- a/src/platform/billing/composables/useBillingCapabilities.test.ts +++ b/src/platform/billing/composables/useBillingCapabilities.test.ts @@ -20,7 +20,7 @@ import { billingApi } from '@/platform/billing/api/billingApi' import { refreshBillingAccount } from '@/platform/billing/billingAccountRefresh' import { setLocalBillingWebEnabled } from '@/platform/billing/localBillingWebEnabled' import { WorkspaceApiError } from '@/platform/remote/ingest/ingestApiError' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useBillingCapabilities } from './useBillingCapabilities' import { describeServerFactGate } from '@/utils/__tests__/serverFactGate' @@ -1205,7 +1205,6 @@ describe('useBillingCapabilities', () => { afterEach(() => { localStorage.removeItem(LAPSE_RECOVERY_FLAG) - remoteConfig.value = {} }) it('stays denied after the session is restored with the flag off', async () => { @@ -1228,10 +1227,14 @@ describe('useBillingCapabilities', () => { await denyThenRestoreSession() expect(billingApi.getBillingCapabilities).toHaveBeenCalledOnce() - remoteConfig.value = { - ...remoteConfig.value, - web_session_lapse_recovery_enabled: true - } + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { + ...remoteConfigStore.config, + web_session_lapse_recovery_enabled: true + }, + false + ) await vi.advanceTimersByTimeAsync(0) expect(billingApi.getBillingCapabilities).toHaveBeenCalledTimes(2) @@ -1280,10 +1283,14 @@ describe('useBillingCapabilities', () => { }) ) const initialized = billingCapabilities.initialize() - remoteConfig.value = { - ...remoteConfig.value, - web_session_lapse_recovery_enabled: true - } + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { + ...remoteConfigStore.config, + web_session_lapse_recovery_enabled: true + }, + false + ) await vi.advanceTimersByTimeAsync(0) scope.stop() @@ -1309,10 +1316,14 @@ describe('useBillingCapabilities', () => { .mockResolvedValueOnce(capabilitiesResponse(true)) const initialized = billingCapabilities.initialize() - remoteConfig.value = { - ...remoteConfig.value, - web_session_lapse_recovery_enabled: true - } + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { + ...remoteConfigStore.config, + web_session_lapse_recovery_enabled: true + }, + false + ) await vi.advanceTimersByTimeAsync(0) rejectRead(new WorkspaceApiError('authentication required', 401)) await initialized diff --git a/src/platform/billing/composables/useBillingContext.test.ts b/src/platform/billing/composables/useBillingContext.test.ts index 60154a8e7dc..955a78bfd95 100644 --- a/src/platform/billing/composables/useBillingContext.test.ts +++ b/src/platform/billing/composables/useBillingContext.test.ts @@ -12,11 +12,7 @@ import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspace import { billingApi } from '@/platform/billing/api/billingApi' import type { BillingStatusResponse, Plan } from '@comfyorg/billing-core' -import { - authenticatedRemoteConfigState, - remoteConfig, - remoteConfigState -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { readCheckoutOperation, @@ -49,16 +45,10 @@ const DEFAULT_BILLING_STATUS: BillingStatusResponse = { subscription_duration: 'MONTHLY' } -const { - mockPlans, - mockFetchPlans, - mockIsCloud, - mockFreeTierExecutionPermitted -} = vi.hoisted(() => ({ +const { mockPlans, mockFetchPlans, mockIsCloud } = vi.hoisted(() => ({ mockPlans: { value: [] as Plan[] }, mockFetchPlans: vi.fn(async () => undefined), - mockIsCloud: { value: true }, - mockFreeTierExecutionPermitted: { value: true } + mockIsCloud: { value: true } })) const mockBillingStatus: { value: Partial } = { @@ -77,18 +67,6 @@ vi.mock(import('@/platform/distribution/types'), () => { vi.mock(import('@/platform/billing/subscription/composables/useSubscription')) -vi.mock( - import('@/platform/billing/subscription/composables/useFreeTierQuota'), - () => ({ - useFreeTierQuota: () => ({ - quotaEnabled: { value: false }, - get freeTierExecutionPermitted() { - return mockFreeTierExecutionPermitted - } - }) - }) -) - vi.mock(import('@/composables/auth/useAuthActions')) vi.mock( @@ -120,7 +98,6 @@ describe('useBillingContext', () => { currency: 'usd' }) mockIsCloud.value = true - mockFreeTierExecutionPermitted.value = true const workspaceStore = useTeamWorkspaceStore() const refs = storeToRefs(workspaceStore) @@ -139,9 +116,6 @@ describe('useBillingContext', () => { vi.mocked(useWorkspaceBillingStateStore().updateSummary).mockImplementation( () => {} ) - remoteConfig.value = {} - remoteConfigState.value = 'unloaded' - authenticatedRemoteConfigState.value = 'unloaded' mockIsPersonal.value = true mockPlans.value = [] const subscription = useSubscription() @@ -179,19 +153,22 @@ describe('useBillingContext', () => { describe('canRunWorkflows', () => { it('is true when not on free tier', async () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { free_tier_balance: { allowance: 5, used: 5, remaining: 0 } }, + true + ) useSubscription().subscriptionTier = computed(() => 'PRO') mockIsCloud.value = true - mockFreeTierExecutionPermitted.value = false const context = useBillingContext() await context.initialize() expect(context.canRunWorkflows.value).toBe(true) }) it('is true when on free tier and freeTierExecutionPermitted is true', async () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { free_tier_balance: { allowance: 5, used: 0, remaining: 5 } }, + true + ) useSubscription().subscriptionTier = computed(() => 'FREE') mockBillingStatus.value.subscription_tier = 'FREE' useSubscription().subscriptionStatus.value = { @@ -199,15 +176,16 @@ describe('useBillingContext', () => { subscription_tier: 'FREE' } mockIsCloud.value = true - mockFreeTierExecutionPermitted.value = true const context = useBillingContext() await context.initialize() expect(context.canRunWorkflows.value).toBe(true) }) it('is false when on free tier on cloud and freeTierExecutionPermitted is false', async () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { free_tier_balance: { allowance: 5, used: 5, remaining: 0 } }, + true + ) useSubscription().subscriptionTier = computed(() => 'FREE') mockBillingStatus.value.subscription_tier = 'FREE' useSubscription().subscriptionStatus.value = { @@ -215,15 +193,16 @@ describe('useBillingContext', () => { subscription_tier: 'FREE' } mockIsCloud.value = true - mockFreeTierExecutionPermitted.value = false const context = useBillingContext() await context.initialize() expect(context.canRunWorkflows.value).toBe(false) }) it('is true when on free tier off cloud even if freeTierExecutionPermitted is false', async () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { free_tier_balance: { allowance: 5, used: 5, remaining: 0 } }, + true + ) useSubscription().subscriptionTier = computed(() => 'FREE') mockBillingStatus.value.subscription_tier = 'FREE' useSubscription().subscriptionStatus.value = { @@ -231,15 +210,13 @@ describe('useBillingContext', () => { subscription_tier: 'FREE' } mockIsCloud.value = false - mockFreeTierExecutionPermitted.value = false const context = useBillingContext() await context.initialize() expect(context.canRunWorkflows.value).toBe(true) }) it('is true when config is not loaded, even if freeTierExecutionPermitted is false', async () => { - remoteConfigState.value = 'unloaded' - authenticatedRemoteConfigState.value = 'unloaded' + useRemoteConfigStore().invalidate() useSubscription().subscriptionTier = computed(() => 'FREE') mockBillingStatus.value.subscription_tier = 'FREE' useSubscription().subscriptionStatus.value = { @@ -247,7 +224,6 @@ describe('useBillingContext', () => { subscription_tier: 'FREE' } mockIsCloud.value = true - mockFreeTierExecutionPermitted.value = false const context = useBillingContext() await context.initialize() expect(context.canRunWorkflows.value).toBe(true) @@ -318,8 +294,7 @@ describe('useBillingContext', () => { }) it('routes migrated Stripe topups through workspace billing', async () => { - remoteConfigState.value = 'authenticated' - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig({}, true) const context = useBillingContext() await nextTick() diff --git a/src/platform/billing/composables/useBillingContext.ts b/src/platform/billing/composables/useBillingContext.ts index 75416dad703..2b39e3f0f06 100644 --- a/src/platform/billing/composables/useBillingContext.ts +++ b/src/platform/billing/composables/useBillingContext.ts @@ -3,7 +3,7 @@ import { reportError } from '@comfyorg/telemetry/reportError' import { useWorkspaceBillingStateStore } from '@/platform/billing/stores/workspaceBillingStateStore' import { useErrorHandling } from '@/composables/useErrorHandling' import { t } from '@/i18n' -import { isAuthenticatedConfigLoaded } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { computed, onScopeDispose, ref, shallowRef, toValue, watch } from 'vue' import { createSharedComposable, until } from '@vueuse/core' @@ -156,13 +156,14 @@ function useBillingContextInternal(): BillingContext { const isFreeTier = computed(() => subscription.value?.tier === 'FREE') const freeTierQuota = useFreeTierQuota() + const remoteConfigStore = useRemoteConfigStore() const canRunWorkflows = computed( () => canAccessSubscriptionFeatures.value && (!isFreeTier.value || !isCloud || - !isAuthenticatedConfigLoaded.value || + !remoteConfigStore.isAuthenticatedConfigLoaded || freeTierQuota.freeTierExecutionPermitted.value) ) diff --git a/src/platform/billing/composables/useBillingDialogs.subscriptionRequired.test.ts b/src/platform/billing/composables/useBillingDialogs.subscriptionRequired.test.ts index 8c2d3e51fb3..032098a1626 100644 --- a/src/platform/billing/composables/useBillingDialogs.subscriptionRequired.test.ts +++ b/src/platform/billing/composables/useBillingDialogs.subscriptionRequired.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useSubscriptionDialog } from '@/platform/billing/subscription/composables/useSubscriptionDialog' -import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' const mockIsCloud = vi.hoisted(() => ({ value: true })) vi.mock(import('@/platform/distribution/types'), () => ({ @@ -10,8 +10,6 @@ vi.mock(import('@/platform/distribution/types'), () => ({ } })) -vi.mock(import('@/platform/remoteConfig/remoteConfig')) - const refreshRemoteConfig = vi.hoisted(() => vi.fn()) vi.mock(import('@/platform/remoteConfig/refreshRemoteConfig'), () => ({ refreshRemoteConfig @@ -33,7 +31,7 @@ describe('showSubscriptionRequiredDialog', () => { beforeEach(() => { mockIsCloud.value = true - remoteConfigState.value = 'unloaded' + useRemoteConfigStore().invalidate() window.__CONFIG__ = {} }) @@ -53,8 +51,7 @@ describe('showSubscriptionRequiredDialog', () => { }) it('opens the pricing table immediately when config is already loaded', async () => { - remoteConfigState.value = 'authenticated' - window.__CONFIG__ = { subscription_required: true } + useRemoteConfigStore().acceptConfig({ subscription_required: true }, true) const opened = await useBillingDialogs().showSubscriptionRequiredDialog({ reason: 'subscribe_now_button' @@ -68,7 +65,7 @@ describe('showSubscriptionRequiredDialog', () => { }) it('retries the /features fetch instead of trusting an unloaded config snapshot', async () => { - remoteConfigState.value = 'unloaded' + useRemoteConfigStore().invalidate() window.__CONFIG__ = {} refreshRemoteConfig.mockImplementation(() => { window.__CONFIG__ = { subscription_required: true } @@ -84,7 +81,7 @@ describe('showSubscriptionRequiredDialog', () => { }) it('resolves false instead of rejecting when the config refresh fails', async () => { - remoteConfigState.value = 'unloaded' + useRemoteConfigStore().invalidate() window.__CONFIG__ = {} refreshRemoteConfig.mockRejectedValueOnce(new Error('offline')) @@ -102,8 +99,7 @@ describe('showSubscriptionRequiredDialog', () => { }) it('reports a closed gate instead of returning silently', async () => { - remoteConfigState.value = 'authenticated' - window.__CONFIG__ = { subscription_required: false } + useRemoteConfigStore().acceptConfig({ subscription_required: false }, true) const opened = await useBillingDialogs().showSubscriptionRequiredDialog() diff --git a/src/platform/billing/composables/useBillingDialogs.ts b/src/platform/billing/composables/useBillingDialogs.ts index a4057f1c135..4ebae892746 100644 --- a/src/platform/billing/composables/useBillingDialogs.ts +++ b/src/platform/billing/composables/useBillingDialogs.ts @@ -116,9 +116,9 @@ export function useBillingDialogs() { try { if (!window.__CONFIG__?.subscription_required) { - const { remoteConfigState } = - await import('@/platform/remoteConfig/remoteConfig') - if (remoteConfigState.value === 'unloaded') { + const { useRemoteConfigStore } = + await import('@/platform/remoteConfig/remoteConfigStore') + if (useRemoteConfigStore().loadState === 'unloaded') { const { refreshRemoteConfig } = await import('@/platform/remoteConfig/refreshRemoteConfig') await refreshRemoteConfig() diff --git a/src/platform/billing/hostedBillingRoutes.test.ts b/src/platform/billing/hostedBillingRoutes.test.ts index 76e8b76d891..517b72b89bd 100644 --- a/src/platform/billing/hostedBillingRoutes.test.ts +++ b/src/platform/billing/hostedBillingRoutes.test.ts @@ -3,7 +3,7 @@ import type { BillingIntent } from '@comfyorg/billing-contract' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { hostedBillingRoute } from './hostedBillingRoutes' @@ -29,7 +29,6 @@ function entryUrl( describe('hostedBillingRoute', () => { beforeEach(() => { cloudBaseUrl.value = 'https://testcloud.comfy.org' - remoteConfig.value = {} }) it.for([ @@ -158,7 +157,10 @@ describe('hostedBillingRoute', () => { }) it('mints an entry against a server-provided billing-web origin', () => { - remoteConfig.value = { billing_web_url: 'https://stagingbilling.comfy.org' } + useRemoteConfigStore().acceptConfig( + { billing_web_url: 'https://stagingbilling.comfy.org' }, + false + ) expect(hostedBillingRoute('billing_web', 'pricing')).toEqual({ kind: 'billing_web', diff --git a/src/platform/billing/openHostedBillingTab.handoff.test.ts b/src/platform/billing/openHostedBillingTab.handoff.test.ts index 6f446d3a675..15c6442afa9 100644 --- a/src/platform/billing/openHostedBillingTab.handoff.test.ts +++ b/src/platform/billing/openHostedBillingTab.handoff.test.ts @@ -1,7 +1,7 @@ import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import { useTelemetry } from '@comfyorg/telemetry' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { clearCheckoutJourney, @@ -36,16 +36,17 @@ function linkParams(tab: FakeTab): Record { describe('the billing-web handoff', () => { beforeEach(() => { - const previousConfig = remoteConfig.value - remoteConfig.value = { - hosted_billing_destination: 'billing_web', - billing_web_url: 'https://billing.comfy.org', - comfy_cloud_base_url: 'https://cloud.comfy.org' - } + useRemoteConfigStore().acceptConfig( + { + hosted_billing_destination: 'billing_web', + billing_web_url: 'https://billing.comfy.org', + comfy_cloud_base_url: 'https://cloud.comfy.org' + }, + false + ) Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-1' }) return () => { disarmHostedBillingReturnRefresh() - remoteConfig.value = previousConfig clearCheckoutJourney() } }) @@ -202,10 +203,11 @@ describe('the billing-web handoff', () => { ) it('reports no handoff while the server keeps billing on the provider', () => { - remoteConfig.value = { - ...remoteConfig.value, - hosted_billing_destination: 'stripe' - } + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { ...remoteConfigStore.config, hosted_billing_destination: 'stripe' }, + false + ) const open = vi.fn() vi.stubGlobal('open', open) const handoff = { diff --git a/src/platform/billing/stores/localBillingWebFlagStore.test.ts b/src/platform/billing/stores/localBillingWebFlagStore.test.ts index d2a08f5566c..c35760c77e1 100644 --- a/src/platform/billing/stores/localBillingWebFlagStore.test.ts +++ b/src/platform/billing/stores/localBillingWebFlagStore.test.ts @@ -21,7 +21,7 @@ import { } from '@/platform/auth/desktopHost/desktopHostSession' import { showsCloudBillingNewUxOnLocal } from '@/platform/billing/localBillingWebEnabled' import { useLocalBillingWebFlagStore as defineFlagStore } from '@/platform/billing/stores/localBillingWebFlagStore' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useAuthStore } from '@/stores/authStore' @@ -141,7 +141,7 @@ describe('useLocalBillingWebFlagStore', () => { ) it('exposes only its two flags from a Cloud document with other keys', async () => { - const localConfig = { ...remoteConfig.value } + const localConfig = { ...useRemoteConfigStore().config } serveFlags({ local_billing_web: true, unified_billing_settings: true, @@ -152,7 +152,7 @@ describe('useLocalBillingWebFlagStore', () => { const { store } = await signInAndRead() expect(store.enabled).toBe(true) - expect(remoteConfig.value).toEqual(localConfig) + expect(useRemoteConfigStore().config).toEqual(localConfig) }) it('reads the new billing UX from the same request as the handoff flag', async () => { diff --git a/src/platform/billing/subscription/components/FreeTierQuota.test.ts b/src/platform/billing/subscription/components/FreeTierQuota.test.ts index 55e7406b1f5..24fcd681760 100644 --- a/src/platform/billing/subscription/components/FreeTierQuota.test.ts +++ b/src/platform/billing/subscription/components/FreeTierQuota.test.ts @@ -1,4 +1,5 @@ import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { render, screen } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { computed, nextTick, ref } from 'vue' @@ -7,22 +8,22 @@ import { createI18n } from 'vue-i18n' import FreeTierQuota from './FreeTierQuota.vue' const mockIsFreeTier = ref(true) -const mockAvailable = ref(3) +vi.mock(import('@/platform/distribution/types'), () => ({ + DISTRIBUTION: 'cloud' as const, + isCloud: true, + isDesktop: false, + isNightly: false +})) vi.mock(import('@/platform/billing/composables/useBillingContext')) vi.mock(import('@/platform/billing/composables/useSubscriptionPaywall')) -vi.mock( - import('@/platform/billing/subscription/composables/useFreeTierQuota'), - () => ({ - useFreeTierQuota: () => ({ - available: computed(() => mockAvailable.value), - hasInvalidNodes: computed(() => false), - maxAvailable: computed(() => 5), - quotaEnabled: computed(() => true) - }) - }) -) +function serveFreeTierBalance(remaining: number) { + useRemoteConfigStore().acceptConfig( + { free_tier_balance: { allowance: 5, remaining, used: 5 - remaining } }, + false + ) +} const i18n = createI18n({ legacy: false, @@ -43,7 +44,7 @@ describe('FreeTierQuota', () => { vi.mocked(useBillingContext).mockReturnValue(billing) mockIsFreeTier.value = true - mockAvailable.value = 3 + serveFreeTierBalance(3) }) it('hides the displayed quota when the user leaves the free tier', async () => { @@ -58,7 +59,7 @@ describe('FreeTierQuota', () => { }) it('shows an explicit zero count when the quota is exhausted', async () => { - mockAvailable.value = 0 + serveFreeTierBalance(0) render(FreeTierQuota, { global: { plugins: [i18n] } }) expect(await screen.findByText('0 / 5 runs left')).toBeInTheDocument() diff --git a/src/platform/billing/subscription/composables/useFreeTierQuota.test.ts b/src/platform/billing/subscription/composables/useFreeTierQuota.test.ts index 959e06feee8..8735473d11d 100644 --- a/src/platform/billing/subscription/composables/useFreeTierQuota.test.ts +++ b/src/platform/billing/subscription/composables/useFreeTierQuota.test.ts @@ -2,14 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope, nextTick } from 'vue' import type { EffectScope } from 'vue' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useFreeTierQuota } from './useFreeTierQuota' -vi.mock(import('@vueuse/core'), () => ({ - createSharedComposable: unknown>(fn: T) => - fn -})) - const mockIsCloud = vi.hoisted(() => ({ value: true })) vi.mock(import('@/platform/distribution/types'), () => ({ get isCloud() { @@ -23,8 +18,6 @@ vi.mock(import('@/systems/badgeSystem'), () => ({ graphCreditsBadges: () => mockCreditBadges.value })) -vi.mock(import('@/platform/remoteConfig/remoteConfig')) - describe('useFreeTierQuota', () => { let scope: EffectScope @@ -38,9 +31,10 @@ describe('useFreeTierQuota', () => { scope = effectScope() mockIsCloud.value = true mockCreditBadges.value = [] - remoteConfig.value = { - free_tier_balance: { allowance: 5, used: 0, remaining: 5 } - } + useRemoteConfigStore().acceptConfig( + { free_tier_balance: { allowance: 5, used: 0, remaining: 5 } }, + false + ) }) afterEach(() => { @@ -73,7 +67,7 @@ describe('useFreeTierQuota', () => { }) it('keeps the quota disabled when the backend sends no free-tier balance', () => { - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, false) const quota = createQuota() @@ -84,9 +78,10 @@ describe('useFreeTierQuota', () => { it('updates the quota when remote config changes', async () => { const quota = createQuota() - remoteConfig.value = { - free_tier_balance: { allowance: 10, used: 7, remaining: 3 } - } + useRemoteConfigStore().acceptConfig( + { free_tier_balance: { allowance: 10, used: 7, remaining: 3 } }, + false + ) await nextTick() expect(quota.available.value).toBe(3) diff --git a/src/platform/billing/subscription/composables/useFreeTierQuota.ts b/src/platform/billing/subscription/composables/useFreeTierQuota.ts index 4df5987312e..8d7e3ecedf9 100644 --- a/src/platform/billing/subscription/composables/useFreeTierQuota.ts +++ b/src/platform/billing/subscription/composables/useFreeTierQuota.ts @@ -1,21 +1,22 @@ -import { createSharedComposable } from '@vueuse/core' +import { defineStore, storeToRefs } from 'pinia' import { computed, ref, watch } from 'vue' import { isCloud } from '@/platform/distribution/types' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useApp } from '@/scripts/appInstance' import { graphCreditsBadges } from '@/systems/badgeSystem' -export const useFreeTierQuota = createSharedComposable(function () { +const useFreeTierQuotaStore = defineStore('freeTierQuota', () => { + const remoteConfigStore = useRemoteConfigStore() const available = ref(0) const maxAvailable = ref(0) watch( - () => remoteConfig.value.free_tier_balance?.remaining, + () => remoteConfigStore.config.free_tier_balance?.remaining, (val) => (available.value = val ?? 0), { immediate: true } ) watch( - () => remoteConfig.value.free_tier_balance?.allowance, + () => remoteConfigStore.config.free_tier_balance?.allowance, (val) => (maxAvailable.value = val ?? 0), { immediate: true } ) @@ -42,3 +43,23 @@ export const useFreeTierQuota = createSharedComposable(function () { trackRun } }) + +/** Free Cloud runs left this session, seeded from remote config and decremented per run. */ +export function useFreeTierQuota() { + const store = useFreeTierQuotaStore() + const { + available, + freeTierExecutionPermitted, + hasInvalidNodes, + maxAvailable, + quotaEnabled + } = storeToRefs(store) + return { + available, + freeTierExecutionPermitted, + hasInvalidNodes, + maxAvailable, + quotaEnabled, + trackRun: store.trackRun + } +} diff --git a/src/platform/billing/subscription/composables/useSubscriptionDialog.test.ts b/src/platform/billing/subscription/composables/useSubscriptionDialog.test.ts index a2b6c73ec96..e45b8a9978f 100644 --- a/src/platform/billing/subscription/composables/useSubscriptionDialog.test.ts +++ b/src/platform/billing/subscription/composables/useSubscriptionDialog.test.ts @@ -35,7 +35,7 @@ import { registerRefreshOnReturn } from '@/platform/billing/refreshOnReturn' import { onBillingRefresh } from '@/platform/billing/billingRefresh' import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useFreeTierQuota } from './useFreeTierQuota' import { useSubscriptionDialog } from './useSubscriptionDialog' @@ -346,13 +346,16 @@ describe('useSubscriptionDialog', () => { 'explains a refused run for a served $state plan with $remaining of $allowance free runs left', async ({ state, remaining, allowance, body }) => { mockSubscriptionState.value = state - remoteConfig.value = { - free_tier_balance: { - allowance, - used: allowance - remaining, - remaining - } - } + useRemoteConfigStore().acceptConfig( + { + free_tier_balance: { + allowance, + used: allowance - remaining, + remaining + } + }, + false + ) useFreeTierQuota() await nextTick() const { showPricingTable } = useSubscriptionDialog() diff --git a/src/platform/billing/subscription/constants/tierPricing.ts b/src/platform/billing/subscription/constants/tierPricing.ts index e820e4edc77..e954f37cc8d 100644 --- a/src/platform/billing/subscription/constants/tierPricing.ts +++ b/src/platform/billing/subscription/constants/tierPricing.ts @@ -2,7 +2,7 @@ import type { BillingTierKey } from '@comfyorg/account-core/billing' import { TIER_CATALOG } from '@comfyorg/account-ui/billing/catalog' import type { SubscriptionTier as IngestSubscriptionTier } from '@comfyorg/ingest-types' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import type { components } from '@/types/comfyRegistryTypes' export type { IngestSubscriptionTier } @@ -163,7 +163,8 @@ export function getTierPrice(tierKey: TierKey, isYearly = false): number { } export function getTierCredits(tierKey: TierKey): number | null { - if (tierKey === 'free') return remoteConfig.value.free_tier_credits ?? null + if (tierKey === 'free') + return useRemoteConfigStore().config.free_tier_credits ?? null if (tierKey === 'founder') return FOUNDER_MONTHLY_CREDITS return TIER_PRICING[tierKey]?.credits } diff --git a/src/platform/billing/subscription/launchCancellationFlow.test.ts b/src/platform/billing/subscription/launchCancellationFlow.test.ts index c1f57aa1dde..0a8698743bf 100644 --- a/src/platform/billing/subscription/launchCancellationFlow.test.ts +++ b/src/platform/billing/subscription/launchCancellationFlow.test.ts @@ -1,10 +1,10 @@ import type { RetentionFlowResponse } from '@comfyorg/ingest-types' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { computed } from 'vue' import type { BillingType } from '@/platform/billing/composables/types' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { reportError } from '@comfyorg/telemetry/reportError' import { useToast } from '@/components/ui/toast/toastStore' import { billingApi } from '@/platform/billing/api/billingApi' @@ -70,7 +70,10 @@ beforeEach(() => { mocks.billingType.value = 'workspace' mocks.activeWorkspaceId = 'workspace-1' mocks.isPersonal = true - remoteConfig.value = { cancellation_survey_id: 'survey-1' } + useRemoteConfigStore().acceptConfig( + { cancellation_survey_id: 'survey-1' }, + false + ) vi.spyOn( useTeamWorkspaceStore(), @@ -84,10 +87,6 @@ beforeEach(() => { ).mockImplementation(() => mocks.isPersonal) }) -afterEach(() => { - remoteConfig.value = {} -}) - describe('launchCancellationFlow', () => { it.for([ { @@ -169,7 +168,7 @@ describe('launchCancellationFlow', () => { { name: 'is not configured', config: {} }, { name: 'is blank', config: { cancellation_survey_id: '' } } ])('skips the survey when its ID $name', async ({ config }) => { - remoteConfig.value = config + useRemoteConfigStore().acceptConfig(config, false) const { shown, showFlow } = captureFlow() await launchCancellationFlow({ showFlow }) diff --git a/src/platform/billing/subscription/launchCancellationFlow.ts b/src/platform/billing/subscription/launchCancellationFlow.ts index 1e3732c6bba..682be58686f 100644 --- a/src/platform/billing/subscription/launchCancellationFlow.ts +++ b/src/platform/billing/subscription/launchCancellationFlow.ts @@ -6,7 +6,7 @@ import type { import { useBillingContext } from '@/platform/billing/composables/useBillingContext' import { useToast } from '@/components/ui/toast/toastStore' import { t } from '@/i18n' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { reportError } from '@comfyorg/telemetry/reportError' import { billingApi } from '@/platform/billing/api/billingApi' import { WorkspaceApiError } from '@/platform/remote/ingest/ingestApiError' @@ -137,7 +137,8 @@ async function showCancellationFlow( try { await showFlow({ cancelAt, - surveyId: remoteConfig.value.cancellation_survey_id || undefined, + surveyId: + useRemoteConfigStore().config.cancellation_survey_id || undefined, flow, workspaceId: launchWorkspaceId, isScopeCurrent diff --git a/src/platform/billing/subscription/utils/tierBenefits.test.ts b/src/platform/billing/subscription/utils/tierBenefits.test.ts index edabfed7c6b..111601c3036 100644 --- a/src/platform/billing/subscription/utils/tierBenefits.test.ts +++ b/src/platform/billing/subscription/utils/tierBenefits.test.ts @@ -1,16 +1,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { getCommonTierBenefits } from '@/platform/billing/subscription/utils/tierBenefits' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' - -vi.mock(import('@/platform/remoteConfig/remoteConfig')) +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' const translate = (key: string) => `t:${key}` const formatNumber = (value: number) => `n:${value}` describe('getCommonTierBenefits', () => { beforeEach(() => { - remoteConfig.value = { free_tier_credits: 120 } + useRemoteConfigStore().acceptConfig({ free_tier_credits: 120 }, false) }) it('includes monthlyCredits only for the free tier when credits are configured', () => { @@ -33,7 +31,7 @@ describe('getCommonTierBenefits', () => { }) it('omits monthlyCredits for free tier when remoteConfig has no credits', () => { - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, false) const benefits = getCommonTierBenefits('free', translate, formatNumber) diff --git a/src/platform/cloud/onboarding/CloudLoginView.test.ts b/src/platform/cloud/onboarding/CloudLoginView.test.ts index 6296a731a12..24ab6fa6af0 100644 --- a/src/platform/cloud/onboarding/CloudLoginView.test.ts +++ b/src/platform/cloud/onboarding/CloudLoginView.test.ts @@ -17,7 +17,7 @@ import enMessages from '@/locales/en/main.json' with { type: 'json' } import { captureOAuthRequestId } from '@/platform/cloud/oauth/oauthState' import type { RemoteConfig } from '@/platform/remoteConfig/types' import CloudLoginView from '@/platform/cloud/onboarding/CloudLoginView.vue' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import type { useSessionCookie } from '@/platform/auth/session/useSessionCookie' import { presentSsoRequired } from '@/platform/auth/sso/ssoRequired' import { SSO_REQUIRED_DIALOG_KEY } from '@/platform/auth/sso/ssoRequiredDialogKey' @@ -121,7 +121,6 @@ async function renderLoginView( afterEach(() => { isEmbeddedWebView.value = false - remoteConfig.value = {} sessionStorage.clear() }) @@ -155,7 +154,7 @@ describe('CloudLoginView', () => { expected: 'with Google to get 5 free runs.' } ])('$name', async ({ offer, expected }) => { - remoteConfig.value = { free_tier_offer: offer } + useRemoteConfigStore().acceptConfig({ free_tier_offer: offer }, false) await renderLoginView('/cloud/login', FREE_RUN_MESSAGES) expect(screen.getByText(expected)).toBeInTheDocument() diff --git a/src/platform/cloud/onboarding/CloudLoginView.vue b/src/platform/cloud/onboarding/CloudLoginView.vue index 232416dddcc..5ffb7094ecf 100644 --- a/src/platform/cloud/onboarding/CloudLoginView.vue +++ b/src/platform/cloud/onboarding/CloudLoginView.vue @@ -112,7 +112,7 @@ import { useCloudAuthPage } from '@/platform/cloud/onboarding/composables/useClo import { useSsoSignIn } from '@/platform/cloud/onboarding/composables/useSsoSignIn' import { CLOUD_AUTH_LINK_BUTTON_CLASS } from '@/platform/cloud/onboarding/constants/authClasses' import { SSO_ERROR_MESSAGE_KEY } from '@/platform/cloud/onboarding/sso/ssoErrorMessages' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import type { SignInData } from '@/schemas/signInSchema' const { t } = useI18n() @@ -122,8 +122,9 @@ const authActions = useAuthActions() const { flags } = useFeatureFlags() const { state: ssoState, busy: ssoBusy, trySso } = useSsoSignIn('cloud_login') +const remoteConfigStore = useRemoteConfigStore() const freeRunsSuffix = computed(() => { - const offer = remoteConfig.value.free_tier_offer + const offer = remoteConfigStore.config.free_tier_offer if (!offer) return null const key = offer.requires_google_sign_in ? 'auth.login.freeRunsSuffixGoogle' diff --git a/src/platform/cloud/onboarding/CloudSurveyView.vue b/src/platform/cloud/onboarding/CloudSurveyView.vue index ca39dd89ec0..53353f90345 100644 --- a/src/platform/cloud/onboarding/CloudSurveyView.vue +++ b/src/platform/cloud/onboarding/CloudSurveyView.vue @@ -29,7 +29,7 @@ import { isSurveyReplayRequested, restoreSurveyReplayRequest } from '@/platform/onboarding/onboardingReplay' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useTelemetry } from '@comfyorg/telemetry' import { reportError } from '@comfyorg/telemetry/reportError' import { useAuthStore } from '@/stores/authStore' @@ -42,8 +42,9 @@ const { t } = useI18n() const { flags } = useFeatureFlags() const onboardingSurveyEnabled = computed(() => flags.onboardingSurveyEnabled) +const remoteConfigStore = useRemoteConfigStore() const activeSurvey = computed( - () => remoteConfig.value.onboarding_survey ?? defaultOnboardingSurvey + () => remoteConfigStore.config.onboarding_survey ?? defaultOnboardingSurvey ) const isSubmitting = ref(false) diff --git a/src/platform/cloud/onboarding/composables/useFreeTierOnboarding.test.ts b/src/platform/cloud/onboarding/composables/useFreeTierOnboarding.test.ts index 99ba35b9cdc..d572c7b6c79 100644 --- a/src/platform/cloud/onboarding/composables/useFreeTierOnboarding.test.ts +++ b/src/platform/cloud/onboarding/composables/useFreeTierOnboarding.test.ts @@ -1,12 +1,10 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it } from 'vitest' import { useFreeTierOnboarding } from '@/platform/cloud/onboarding/composables/useFreeTierOnboarding' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' - -vi.mock(import('@/platform/remoteConfig/remoteConfig')) +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' beforeEach(() => { - remoteConfig.value = { free_tier_credits: 50 } + useRemoteConfigStore().acceptConfig({ free_tier_credits: 50 }, false) }) describe('useFreeTierOnboarding', () => { @@ -40,25 +38,25 @@ describe('useFreeTierOnboarding', () => { describe('isFreeTierEnabled', () => { it('returns true when remote config says enabled', () => { - remoteConfig.value = { - free_tier_credits: 50, - new_free_tier_subscriptions: true - } + useRemoteConfigStore().acceptConfig( + { free_tier_credits: 50, new_free_tier_subscriptions: true }, + false + ) const { isFreeTierEnabled } = useFreeTierOnboarding() expect(isFreeTierEnabled.value).toBe(true) }) it('returns false when remote config says disabled', () => { - remoteConfig.value = { - free_tier_credits: 50, - new_free_tier_subscriptions: false - } + useRemoteConfigStore().acceptConfig( + { free_tier_credits: 50, new_free_tier_subscriptions: false }, + false + ) const { isFreeTierEnabled } = useFreeTierOnboarding() expect(isFreeTierEnabled.value).toBe(false) }) it('defaults to false when not set in remote config', () => { - remoteConfig.value = { free_tier_credits: 50 } + useRemoteConfigStore().acceptConfig({ free_tier_credits: 50 }, false) const { isFreeTierEnabled } = useFreeTierOnboarding() expect(isFreeTierEnabled.value).toBe(false) }) diff --git a/src/platform/cloud/onboarding/composables/useFreeTierOnboarding.ts b/src/platform/cloud/onboarding/composables/useFreeTierOnboarding.ts index 94fd3402774..e15c1d42d44 100644 --- a/src/platform/cloud/onboarding/composables/useFreeTierOnboarding.ts +++ b/src/platform/cloud/onboarding/composables/useFreeTierOnboarding.ts @@ -1,13 +1,14 @@ import { computed, ref } from 'vue' import { getTierCredits } from '@/platform/billing/subscription/constants/tierPricing' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' export function useFreeTierOnboarding() { + const remoteConfigStore = useRemoteConfigStore() const showEmailForm = ref(false) const freeTierCredits = computed(() => getTierCredits('free')) const isFreeTierEnabled = computed( - () => remoteConfig.value.new_free_tier_subscriptions ?? false + () => remoteConfigStore.config.new_free_tier_subscriptions ?? false ) function switchToEmailForm() { diff --git a/src/platform/customNodes/manager/components/survey/ManagerSurveyDialog.test.ts b/src/platform/customNodes/manager/components/survey/ManagerSurveyDialog.test.ts index eb2aaaf2817..0804d2a3082 100644 --- a/src/platform/customNodes/manager/components/survey/ManagerSurveyDialog.test.ts +++ b/src/platform/customNodes/manager/components/survey/ManagerSurveyDialog.test.ts @@ -1,14 +1,12 @@ import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { computed, nextTick } from 'vue' import { createI18n } from 'vue-i18n' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import en from '@/locales/en/main.json' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' - -vi.mock(import('@/platform/remoteConfig/remoteConfig')) +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' vi.mock(import('@/composables/auth/useCurrentUser')) @@ -26,12 +24,11 @@ function renderDialog(onClose = vi.fn()) { } describe('ManagerSurveyDialog', () => { - beforeEach(() => { - remoteConfig.value = {} - }) - it('embeds the configured survey URL with the logged-in user', () => { - remoteConfig.value = { manager_survey_url: SURVEY_URL } + useRemoteConfigStore().acceptConfig( + { manager_survey_url: SURVEY_URL }, + false + ) useCurrentUser().resolvedUserInfo = computed(() => ({ id: 'user-123' })) renderDialog() @@ -45,7 +42,10 @@ describe('ManagerSurveyDialog', () => { }) it('omits distinct_id when there is no logged-in user', () => { - remoteConfig.value = { manager_survey_url: SURVEY_URL } + useRemoteConfigStore().acceptConfig( + { manager_survey_url: SURVEY_URL }, + false + ) renderDialog() @@ -63,7 +63,10 @@ describe('ManagerSurveyDialog', () => { }) it('shows the error state when the configured survey url is malformed', () => { - remoteConfig.value = { manager_survey_url: 'not a valid url' } + useRemoteConfigStore().acceptConfig( + { manager_survey_url: 'not a valid url' }, + false + ) renderDialog() @@ -75,7 +78,10 @@ describe('ManagerSurveyDialog', () => { renderDialog() expect(screen.getByTestId('manager-survey-error')).toBeTruthy() - remoteConfig.value = { manager_survey_url: SURVEY_URL } + useRemoteConfigStore().acceptConfig( + { manager_survey_url: SURVEY_URL }, + false + ) await nextTick() expect(screen.queryByTestId('manager-survey-error')).toBeNull() @@ -83,7 +89,10 @@ describe('ManagerSurveyDialog', () => { }) it('clears the loading state once the iframe loads', async () => { - remoteConfig.value = { manager_survey_url: SURVEY_URL } + useRemoteConfigStore().acceptConfig( + { manager_survey_url: SURVEY_URL }, + false + ) renderDialog() expect(screen.getByTestId('manager-survey-loading')).toBeTruthy() @@ -96,9 +105,13 @@ describe('ManagerSurveyDialog', () => { }) it('applies survey height messages even when the url has a trailing slash', async () => { - remoteConfig.value = { - manager_survey_url: 'https://us.posthog.com/external_surveys/survey-123/' - } + useRemoteConfigStore().acceptConfig( + { + manager_survey_url: + 'https://us.posthog.com/external_surveys/survey-123/' + }, + false + ) renderDialog() const iframe = screen.getByTestId('manager-survey-iframe') @@ -119,7 +132,10 @@ describe('ManagerSurveyDialog', () => { }) it('removes the iframe and shows the error state when loading times out', async () => { - remoteConfig.value = { manager_survey_url: SURVEY_URL } + useRemoteConfigStore().acceptConfig( + { manager_survey_url: SURVEY_URL }, + false + ) renderDialog() expect(screen.getByTestId('manager-survey-iframe')).toBeTruthy() @@ -133,7 +149,10 @@ describe('ManagerSurveyDialog', () => { it('closes the dialog when the close button is clicked', async () => { const onClose = vi.fn() - remoteConfig.value = { manager_survey_url: SURVEY_URL } + useRemoteConfigStore().acceptConfig( + { manager_survey_url: SURVEY_URL }, + false + ) renderDialog(onClose) await userEvent.click(screen.getByRole('button', { name: 'Close' })) diff --git a/src/platform/customNodes/manager/components/survey/ManagerSurveyDialog.vue b/src/platform/customNodes/manager/components/survey/ManagerSurveyDialog.vue index 1e597d2125d..5e784ac57a4 100644 --- a/src/platform/customNodes/manager/components/survey/ManagerSurveyDialog.vue +++ b/src/platform/customNodes/manager/components/survey/ManagerSurveyDialog.vue @@ -53,7 +53,7 @@ import { computed, ref, watch } from 'vue' import AppDialogPanel from '@/components/dialog/AppDialogPanel.vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' const DEFAULT_IFRAME_HEIGHT = 460 const MAX_IFRAME_HEIGHT = 10000 @@ -65,9 +65,9 @@ defineProps<{ const { resolvedUserInfo } = useCurrentUser() -// The hosted (external) survey URL is provided per environment by cloud config. +const remoteConfigStore = useRemoteConfigStore() const surveyUrl = computed(() => { - const base = remoteConfig.value.manager_survey_url + const base = remoteConfigStore.config.manager_survey_url if (!base) return undefined try { const url = new URL(base) diff --git a/src/platform/openOnCloud/desktopWorkflowRelay.test.ts b/src/platform/openOnCloud/desktopWorkflowRelay.test.ts index 8be0d8af522..56c485e570a 100644 --- a/src/platform/openOnCloud/desktopWorkflowRelay.test.ts +++ b/src/platform/openOnCloud/desktopWorkflowRelay.test.ts @@ -15,7 +15,7 @@ import { handleDesktopWorkflowHandoff, stageDesktopWorkflowHandoff } from '@/platform/openOnCloud/desktopWorkflowRelay' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { api } from '@/scripts/api' import { defaultGraph } from '@/scripts/defaultGraph' @@ -65,14 +65,7 @@ describe(handleDesktopWorkflowHandoff, () => { vi.mocked(fetch).mockImplementation(async () => Response.json({ open_on_cloud_enabled: true }) ) - const previousConfig = remoteConfig.value - const previousWindowConfig = window.__CONFIG__ - remoteConfig.value = {} - window.__CONFIG__ = {} - onTestFinished(() => { - remoteConfig.value = previousConfig - window.__CONFIG__ = previousWindowConfig - }) + useRemoteConfigStore().acceptConfig({}, false) }) it('lets the editor boot when the URL carries no relay', async () => { @@ -154,12 +147,12 @@ describe(handleDesktopWorkflowHandoff, () => { comfy_cloud_base_url: 'https://custom-cloud.example.com', open_on_cloud_enabled: true } - remoteConfig.value = features + useRemoteConfigStore().acceptConfig(features, false) const { relay, record } = await stagedRelay() expect(new URL(record.destination).origin).toBe( features.comfy_cloud_base_url ) - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, false) openAt(relay) vi.mocked(fetch).mockResolvedValue(Response.json(features)) const replace = relayed() diff --git a/src/platform/openOnCloud/localHandoffProtocol.test.ts b/src/platform/openOnCloud/localHandoffProtocol.test.ts index fc5185b247a..97a72fdd967 100644 --- a/src/platform/openOnCloud/localHandoffProtocol.test.ts +++ b/src/platform/openOnCloud/localHandoffProtocol.test.ts @@ -1,21 +1,20 @@ -import { afterEach, describe, expect, it } from 'vitest' +import { describe, expect, it } from 'vitest' import { cloudEditorUrl, isLocalOrigin } from '@/platform/openOnCloud/localHandoffProtocol' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' describe(cloudEditorUrl, () => { - afterEach(() => { - remoteConfig.value = {} - }) - it('retains the configured employee rollout override in a new Cloud tab', () => { - remoteConfig.value = { - comfy_cloud_base_url: - 'https://fe-pr-22949.testenvs.comfy.org/?ff=open_on_cloud_enabled:true' - } + useRemoteConfigStore().acceptConfig( + { + comfy_cloud_base_url: + 'https://fe-pr-22949.testenvs.comfy.org/?ff=open_on_cloud_enabled:true' + }, + false + ) expect(cloudEditorUrl('workflow-transfer')).toBe( 'https://fe-pr-22949.testenvs.comfy.org/?ff=open_on_cloud_enabled%3Atrue&from_local=workflow-transfer' diff --git a/src/platform/openOnCloud/openWorkflowOnCloud.test.ts b/src/platform/openOnCloud/openWorkflowOnCloud.test.ts index 4d0876cf106..c5352d5efdc 100644 --- a/src/platform/openOnCloud/openWorkflowOnCloud.test.ts +++ b/src/platform/openOnCloud/openWorkflowOnCloud.test.ts @@ -30,7 +30,7 @@ vi.mock(import('@/platform/openOnCloud/serializeRootGraph'), () => ({ serializeRootGraph: vi.fn(() => structuredClone(defaultGraph)) })) -const cloudOrigin = new URL(getComfyCloudBaseUrl()).origin +const cloudOrigin = () => new URL(getComfyCloudBaseUrl()).origin const PREPARE_FAILED_TOAST = expect.objectContaining({ kind: 'error', title: "Couldn't prepare this workflow for Comfy Cloud" @@ -56,7 +56,7 @@ function openedNonce(tabs: ReturnType['tabs']): string { function sendFromTab( data: unknown, - { origin = cloudOrigin, fromTab = true } = {} + { origin = cloudOrigin(), fromTab = true } = {} ) { window.dispatchEvent( new MessageEvent('message', { @@ -74,7 +74,7 @@ describe('openWorkflowOnCloud in a browser', () => { await openWorkflowOnCloud(tabs) const url = new URL(tabs.open.mock.calls[0][0]) - expect(url.origin).toBe(cloudOrigin) + expect(url.origin).toBe(cloudOrigin()) expect(url.searchParams.get('from_local')).toMatch(/^[\w-]{24}$/) expect(tabs.openDisowned).not.toHaveBeenCalled() expect(useToast().toasts).not.toContainEqual(PREPARE_FAILED_TOAST) @@ -99,7 +99,7 @@ describe('openWorkflowOnCloud in a browser', () => { ]) }) }, - cloudOrigin + cloudOrigin() ) }) @@ -120,7 +120,7 @@ describe('openWorkflowOnCloud in a browser', () => { it.for([ { name: 'another origin', origin: 'https://evil.example', fromTab: true }, - { name: 'another window', origin: cloudOrigin, fromTab: false } + { name: 'another window', origin: undefined, fromTab: false } ])('ignores a ready message from $name', async ({ origin, fromTab }) => { const { tab, tabs } = fakeTabs() await openWorkflowOnCloud(tabs) diff --git a/src/platform/remoteConfig/__mocks__/remoteConfig.ts b/src/platform/remoteConfig/__mocks__/remoteConfig.ts deleted file mode 100644 index c819400e891..00000000000 --- a/src/platform/remoteConfig/__mocks__/remoteConfig.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { onTestFinished } from 'vitest' -import { computed, customRef } from 'vue' - -import type * as realRemoteConfig from '@/platform/remoteConfig/remoteConfig' - -function testScopedRef(defaultValue: T) { - let value = defaultValue - - return customRef((track, trigger) => ({ - get() { - track() - return value - }, - set(nextValue) { - value = nextValue - trigger() - - onTestFinished(() => { - value = defaultValue - trigger() - }) - } - })) -} - -function testScopedRemovableRef(defaultValue: T) { - const scopedRef = testScopedRef(defaultValue) - return Object.assign(scopedRef, { - remove() { - scopedRef.value = defaultValue - } - }) -} - -const remoteConfigStateRef = - testScopedRef('unloaded') -const authenticatedRemoteConfigStateRef = - testScopedRef( - 'unloaded' - ) - -const remoteConfigCache: ReturnType< - typeof realRemoteConfig.useRemoteConfigCache -> = { - cachedBillingControlEnabled: testScopedRemovableRef(undefined), - cachedV1PaymentRecovery: testScopedRemovableRef(undefined) -} - -const remoteConfigModule: typeof realRemoteConfig = { - remoteConfig: testScopedRef({}), - remoteConfigState: remoteConfigStateRef, - authenticatedRemoteConfigState: authenticatedRemoteConfigStateRef, - remoteConfigRevision: testScopedRef(0), - remoteConfigErrorStatus: testScopedRef(null), - isAuthenticatedConfigLoaded: computed( - () => - authenticatedRemoteConfigStateRef.value === 'authenticated' || - remoteConfigStateRef.value === 'authenticated' - ), - configValueOrDefault(remoteConfig, key, defaultValue) { - return remoteConfig[key] || defaultValue - }, - useRemoteConfigCache: () => remoteConfigCache, - sessionAgentGrant: testScopedRef(undefined), - sessionAgentGrantValidUntil: testScopedRef(undefined) -} - -export const { - remoteConfigState, - authenticatedRemoteConfigState, - remoteConfigRevision, - remoteConfigErrorStatus, - isAuthenticatedConfigLoaded, - remoteConfig, - configValueOrDefault, - sessionAgentGrant, - sessionAgentGrantValidUntil, - useRemoteConfigCache -} = remoteConfigModule diff --git a/src/platform/remoteConfig/refreshRemoteConfig.test.ts b/src/platform/remoteConfig/refreshRemoteConfig.test.ts index 93adf878669..e7952f0aed5 100644 --- a/src/platform/remoteConfig/refreshRemoteConfig.test.ts +++ b/src/platform/remoteConfig/refreshRemoteConfig.test.ts @@ -1,6 +1,9 @@ +import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick } from 'vue' +import { resolveUnifiedWebSession } from '@comfyorg/account-core/webSessionFlag' + import { api } from '@/scripts/api' import { @@ -8,21 +11,36 @@ import { loadRemoteConfigUntilReady, refreshRemoteConfig } from './refreshRemoteConfig' -import { - authenticatedRemoteConfigState, - remoteConfig, - remoteConfigErrorStatus, - remoteConfigRevision, - remoteConfigState, - sessionAgentGrant, - sessionAgentGrantValidUntil, - useRemoteConfigCache -} from './remoteConfig' +import { useRemoteConfigStore } from './remoteConfigStore' vi.mock(import('@/scripts/api')) +vi.mock(import('@comfyorg/account-core/webSessionFlag')) + +const distribution = vi.hoisted(() => ({ isCloud: false })) +vi.mock(import('@/platform/distribution/types'), () => ({ + DISTRIBUTION: 'localhost' as const, + get isCloud() { + return distribution.isCloud + }, + isDesktop: false, + isNightly: false +})) + +function deferred() { + let resolve: (value: T) => void = () => {} + const promise = new Promise((settle) => { + resolve = settle + }) + return { promise, resolve } +} -const { cachedBillingControlEnabled, cachedV1PaymentRecovery } = - useRemoteConfigCache() +function rejectOnAbort(signal: AbortSignal | null | undefined) { + return new Promise((_, reject) => { + signal?.addEventListener('abort', () => { + reject(new DOMException('Aborted', 'AbortError')) + }) + }) +} describe('refreshRemoteConfig', () => { const mockConfig = { feature1: true, feature2: 'value' } @@ -56,44 +74,41 @@ describe('refreshRemoteConfig', () => { } beforeEach(() => { + distribution.isCloud = false vi.mocked(api.apiURL).mockImplementation( (route: string) => `/ComfyUI/api${route}` ) - remoteConfig.value = {} - remoteConfigErrorStatus.value = null - remoteConfigState.value = 'unloaded' - authenticatedRemoteConfigState.value = 'unloaded' - remoteConfigRevision.value = 0 - cachedBillingControlEnabled.value = undefined - cachedV1PaymentRecovery.value = undefined - sessionAgentGrant.value = undefined - sessionAgentGrantValidUntil.value = undefined - window.__CONFIG__ = {} + const store = useRemoteConfigStore() + store.acceptConfig({}, false) + store.invalidate() }) it('retains base URLs while invalidating identity-specific config', () => { - remoteConfig.value = { - subscription_required: true, - comfy_api_base_url: 'https://api.example.com', - comfy_cloud_base_url: 'https://cloud.example.com', - comfy_platform_base_url: 'https://platform.example.com' - } - window.__CONFIG__ = remoteConfig.value - sessionAgentGrant.value = true - sessionAgentGrantValidUntil.value = Date.now() + 60_000 + const store = useRemoteConfigStore() + store.acceptConfig( + { + subscription_required: true, + 'agent-in-app-experience': true, + comfy_api_base_url: 'https://api.example.com', + comfy_cloud_base_url: 'https://cloud.example.com', + comfy_platform_base_url: 'https://platform.example.com' + }, + true + ) + expect(store.agentGrant).toBe(true) invalidateRemoteConfig() - expect(remoteConfig.value).toEqual({ + expect(store.config).toEqual({ comfy_api_base_url: 'https://api.example.com', comfy_cloud_base_url: 'https://cloud.example.com', comfy_platform_base_url: 'https://platform.example.com' }) - expect(window.__CONFIG__).toEqual(remoteConfig.value) - expect(remoteConfigState.value).toBe('unloaded') - expect(sessionAgentGrant.value).toBeUndefined() - expect(authenticatedRemoteConfigState.value).toBe('unloaded') - expect(sessionAgentGrantValidUntil.value).toBeUndefined() + expect(window.__CONFIG__).toEqual(store.config) + expect(store.loadState).toBe('unloaded') + expect(store.agentGrant).toBeUndefined() + expect(store.authenticatedLoadState).toBe('unloaded') + expect(store.agentGrantValidUntil).toBeUndefined() }) it('persists the authenticated server flags to localStorage', async () => { @@ -122,7 +137,7 @@ describe('refreshRemoteConfig', () => { expect.objectContaining({ cache: 'no-store' }) ) expect(global.fetch).not.toHaveBeenCalled() - expect(remoteConfig.value).toEqual(mockConfig) + expect(useRemoteConfigStore().config).toEqual(mockConfig) expect(window.__CONFIG__).toEqual(mockConfig) }) @@ -136,8 +151,8 @@ describe('refreshRemoteConfig', () => { }) it('rejects a successful response when no auth header was attached', async () => { - remoteConfig.value = { subscription_required: true } - window.__CONFIG__ = remoteConfig.value + const store = useRemoteConfigStore() + store.acceptConfig({ subscription_required: true }, false) vi.mocked(api.fetchApi).mockImplementation(async (_route, options) => { options?.onAuthHeader?.(false) return mockSuccessResponse({ 'agent-in-app-experience': true }) @@ -145,14 +160,14 @@ describe('refreshRemoteConfig', () => { await refreshRemoteConfig() - expect(remoteConfig.value).toEqual({ subscription_required: true }) - expect(authenticatedRemoteConfigState.value).toBe('error') - expect(remoteConfigState.value).toBe('error') - expect(remoteConfigRevision.value).toBe(1) + expect(store.config).toEqual({ subscription_required: true }) + expect(store.authenticatedLoadState).toBe('error') + expect(store.loadState).toBe('error') }) it('restores the prior state when the caller cancels the refresh', async () => { - authenticatedRemoteConfigState.value = 'error' + const store = useRemoteConfigStore() + store.failLoad(true) vi.mocked(api.fetchApi).mockImplementation( (_route, options) => new Promise((_, reject) => { @@ -164,12 +179,12 @@ describe('refreshRemoteConfig', () => { const controller = new AbortController() const refresh = refreshRemoteConfig({ signal: controller.signal }) - expect(authenticatedRemoteConfigState.value).toBe('loading') + expect(store.authenticatedLoadState).toBe('loading') await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledOnce()) controller.abort() await refresh - expect(authenticatedRemoteConfigState.value).toBe('error') + expect(store.authenticatedLoadState).toBe('error') }) it('passes an AbortSignal on the authenticated branch', async () => { @@ -203,11 +218,12 @@ describe('refreshRemoteConfig', () => { return mockSuccessResponse(latestConfig) }) + const store = useRemoteConfigStore() const firstRefresh = refreshRemoteConfig({ useAuth: true }) await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledTimes(1)) await refreshRemoteConfig({ useAuth: true }) - expect(cachedBillingControlEnabled.value).toBe(false) - expect(cachedV1PaymentRecovery.value).toBe(false) + expect(store.cachedBillingControlEnabled).toBe(false) + expect(store.cachedV1PaymentRecovery).toBe(false) resolveFirst?.( new Response( JSON.stringify({ @@ -219,20 +235,18 @@ describe('refreshRemoteConfig', () => { ) await firstRefresh - expect(remoteConfig.value).toEqual(latestConfig) - expect(remoteConfigState.value).toBe('authenticated') - expect(remoteConfigErrorStatus.value).toBeNull() - expect(cachedBillingControlEnabled.value).toBe(false) - expect(cachedV1PaymentRecovery.value).toBe(false) + expect(store.config).toEqual(latestConfig) + expect(store.loadState).toBe('authenticated') + expect(store.errorStatus).toBeNull() + expect(store.cachedBillingControlEnabled).toBe(false) + expect(store.cachedV1PaymentRecovery).toBe(false) } ) it('preserves shared state when the caller cancels the refresh', async () => { const existingConfig = { subscription_required: true } - remoteConfig.value = existingConfig - remoteConfigState.value = 'authenticated' - remoteConfigErrorStatus.value = 500 - window.__CONFIG__ = existingConfig + const store = useRemoteConfigStore() + store.acceptConfig(existingConfig, true) vi.mocked(api.fetchApi).mockImplementation( (_route, options) => new Promise((_, reject) => { @@ -255,14 +269,15 @@ describe('refreshRemoteConfig', () => { controller.abort() await refresh - expect(remoteConfig.value).toEqual(existingConfig) - expect(remoteConfigState.value).toBe('authenticated') - expect(remoteConfigErrorStatus.value).toBe(500) + expect(store.config).toEqual(existingConfig) + expect(store.loadState).toBe('authenticated') + expect(store.authenticatedLoadState).toBe('authenticated') expect(window.__CONFIG__).toEqual(existingConfig) }) it('keeps authenticated state settled while polling', async () => { - authenticatedRemoteConfigState.value = 'authenticated' + const store = useRemoteConfigStore() + store.acceptConfig({}, true) let resolveRefresh: ((response: Response) => void) | undefined vi.mocked(api.fetchApi).mockImplementation( (_route, options) => @@ -274,7 +289,7 @@ describe('refreshRemoteConfig', () => { const refresh = refreshRemoteConfig() - expect(authenticatedRemoteConfigState.value).toBe('authenticated') + expect(store.authenticatedLoadState).toBe('authenticated') await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledOnce()) resolveRefresh?.(mockSuccessResponse()) await refresh @@ -293,25 +308,25 @@ describe('refreshRemoteConfig', () => { expect.objectContaining({ cache: 'no-store' }) ) expect(api.fetchApi).not.toHaveBeenCalled() - expect(remoteConfig.value).toEqual(mockConfig) + expect(useRemoteConfigStore().config).toEqual(mockConfig) expect(window.__CONFIG__).toEqual(mockConfig) }) it('clears authenticated state and its grant when anonymous config commits', async () => { - authenticatedRemoteConfigState.value = 'authenticated' - sessionAgentGrant.value = true - sessionAgentGrantValidUntil.value = Date.now() + 60_000 + const store = useRemoteConfigStore() + store.acceptConfig({ 'agent-in-app-experience': true }, true) vi.mocked(global.fetch).mockResolvedValue(mockSuccessResponse()) await refreshRemoteConfig({ useAuth: false }) - expect(authenticatedRemoteConfigState.value).toBe('unloaded') - expect(sessionAgentGrant.value).toBeUndefined() - expect(sessionAgentGrantValidUntil.value).toBeUndefined() + expect(store.authenticatedLoadState).toBe('unloaded') + expect(store.agentGrant).toBeUndefined() + expect(store.agentGrantValidUntil).toBeUndefined() }) it('keeps anonymous state after an older authenticated refresh settles', async () => { - authenticatedRemoteConfigState.value = 'error' + const store = useRemoteConfigStore() + store.failLoad(true) let resolveAuthenticated: ((response: Response) => void) | undefined vi.mocked(api.fetchApi).mockImplementation( (_route, options) => @@ -328,31 +343,53 @@ describe('refreshRemoteConfig', () => { resolveAuthenticated?.(mockSuccessResponse()) await authenticatedRefresh - expect(authenticatedRemoteConfigState.value).toBe('unloaded') - expect(remoteConfigState.value).toBe('anonymous') + expect(store.authenticatedLoadState).toBe('unloaded') + expect(store.loadState).toBe('anonymous') }) + it.for([ + { invalidated: false, expected: true }, + { invalidated: true, expected: undefined } + ])( + 'applies the credentialed web-session answer unless invalidated first ($invalidated)', + async ({ invalidated, expected }) => { + distribution.isCloud = true + const answer = deferred() + vi.mocked(resolveUnifiedWebSession).mockReturnValue(answer.promise) + vi.mocked(global.fetch).mockResolvedValue( + mockSuccessResponse({ web_session_probe: true }) + ) + + const refresh = refreshRemoteConfig({ useAuth: false }) + await vi.waitFor(() => + expect(resolveUnifiedWebSession).toHaveBeenCalledOnce() + ) + if (invalidated) invalidateRemoteConfig() + answer.resolve(true) + await refresh + + expect(useRemoteConfigStore().config.unified_web_session).toBe(expected) + } + ) + 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 + const store = useRemoteConfigStore() + store.acceptConfig(existingConfig, true) vi.mocked(global.fetch).mockResolvedValue( mockErrorResponse(401, 'Unauthorized') ) await refreshRemoteConfig({ useAuth: false }) - expect(remoteConfig.value).toEqual(existingConfig) + expect(store.config).toEqual(existingConfig) expect(window.__CONFIG__).toEqual(existingConfig) - expect(sessionAgentGrant.value).toBe(true) - expect(authenticatedRemoteConfigState.value).toBe('authenticated') - expect(remoteConfigErrorStatus.value).toBeNull() + expect(store.agentGrant).toBe(true) + expect(store.authenticatedLoadState).toBe('authenticated') + expect(store.errorStatus).toBeNull() }) }) @@ -366,6 +403,27 @@ describe('refreshRemoteConfig', () => { expect(init?.signal).toBeInstanceOf(AbortSignal) }) + it('abandons a /features read that is still unanswered after five seconds', async () => { + vi.useFakeTimers() + const existingConfig = { subscription_required: true } + const store = useRemoteConfigStore() + store.acceptConfig(existingConfig, false) + vi.mocked(global.fetch).mockImplementation((_input, init) => + rejectOnAbort(init?.signal) + ) + + const refresh = refreshRemoteConfig({ useAuth: false }) + await vi.advanceTimersByTimeAsync(4_999) + const signal = vi.mocked(global.fetch).mock.calls[0][1]?.signal + expect(signal?.aborted).toBe(false) + await vi.advanceTimersByTimeAsync(1) + await refresh + + expect(signal?.aborted).toBe(true) + expect(store.loadState).toBe('error') + expect(store.config).toEqual(existingConfig) + }) + it('falls back to empty config when the request aborts', async () => { vi.mocked(global.fetch).mockRejectedValue( new DOMException('Aborted', 'AbortError') @@ -373,28 +431,112 @@ describe('refreshRemoteConfig', () => { await refreshRemoteConfig({ useAuth: false }) - expect(remoteConfig.value).toEqual({}) + expect(useRemoteConfigStore().config).toEqual({}) expect(window.__CONFIG__).toEqual({}) }) }) + describe('cancellation', () => { + it('cancels the request when the caller signal is already aborted', async () => { + vi.mocked(global.fetch).mockImplementation(async (_input, init) => + init?.signal?.aborted + ? Promise.reject(new DOMException('Aborted', 'AbortError')) + : mockSuccessResponse() + ) + const controller = new AbortController() + controller.abort() + + await refreshRemoteConfig({ useAuth: false, signal: controller.signal }) + + expect(vi.mocked(global.fetch).mock.calls[0][1]?.signal?.aborted).toBe( + true + ) + expect(useRemoteConfigStore().loadState).toBe('unloaded') + }) + + it.for(['the request is in flight', 'the response body is read'])( + 'keeps the current config when the caller cancels while %s', + async (stage) => { + const existingConfig = { subscription_required: true } + const store = useRemoteConfigStore() + store.acceptConfig(existingConfig, false) + const response = deferred() + const body = deferred>() + vi.mocked(global.fetch).mockReturnValue(response.promise) + const controller = new AbortController() + + const refresh = refreshRemoteConfig({ + useAuth: false, + signal: controller.signal + }) + await vi.waitFor(() => expect(global.fetch).toHaveBeenCalledOnce()) + if (stage === 'the request is in flight') { + controller.abort() + response.resolve(mockErrorResponse(503, 'Service Unavailable')) + } else { + const json = vi.fn(() => body.promise) + response.resolve(fromPartial({ ok: true, json })) + await vi.waitFor(() => expect(json).toHaveBeenCalledOnce()) + controller.abort() + body.resolve({ stale: true }) + } + await refresh + + expect(store.config).toEqual(existingConfig) + expect(store.loadState).toBe('anonymous') + } + ) + + it('cancels an in-flight read on invalidation without reporting a failure', async () => { + vi.mocked(global.fetch).mockImplementation((_input, init) => + rejectOnAbort(init?.signal) + ) + + const refresh = refreshRemoteConfig({ useAuth: false }) + await vi.waitFor(() => expect(global.fetch).toHaveBeenCalledOnce()) + invalidateRemoteConfig() + + expect(vi.mocked(global.fetch).mock.calls[0][1]?.signal?.aborted).toBe( + true + ) + await refresh + const store = useRemoteConfigStore() + expect(store.loadState).toBe('unloaded') + expect(store.errorStatus).toBeNull() + }) + + it('drops a body that finishes reading after invalidation', async () => { + const body = deferred>() + const json = vi.fn(() => body.promise) + vi.mocked(global.fetch).mockResolvedValue( + fromPartial({ ok: true, json }) + ) + + const refresh = refreshRemoteConfig({ useAuth: false }) + await vi.waitFor(() => expect(json).toHaveBeenCalledOnce()) + invalidateRemoteConfig() + body.resolve({ subscription_required: true }) + await refresh + + const store = useRemoteConfigStore() + expect(store.config).not.toHaveProperty('subscription_required') + expect(store.loadState).toBe('unloaded') + }) + }) + describe('error handling', () => { it('clears config on 401 response', async () => { mockAuthenticatedFetch(mockErrorResponse(401, 'Unauthorized')) await refreshRemoteConfig() - expect(remoteConfig.value).toEqual({}) + expect(useRemoteConfigStore().config).toEqual({}) expect(window.__CONFIG__).toEqual({}) }) it("records this session's grant without persisting it anywhere", async () => { - // Prime the two feature values that are intentionally backed by storage, - // so any storage delta below can only come from the session grant. localStorage.setItem('billing_control_enabled', 'false') localStorage.setItem('v1_payment_recovery', 'false') - cachedBillingControlEnabled.value = false - cachedV1PaymentRecovery.value = false const localStorageBefore = storageEntries(localStorage) const sessionStorageBefore = storageEntries(sessionStorage) mockAuthenticatedFetch( @@ -403,8 +545,9 @@ describe('refreshRemoteConfig', () => { await refreshRemoteConfig() - expect(sessionAgentGrant.value).toBe(true) - expect(sessionAgentGrantValidUntil.value).toBeGreaterThan(Date.now()) + const store = useRemoteConfigStore() + expect(store.agentGrant).toBe(true) + expect(store.agentGrantValidUntil).toBeGreaterThan(Date.now()) expect(storageEntries(localStorage)).toEqual(localStorageBefore) expect(storageEntries(sessionStorage)).toEqual(sessionStorageBefore) }) @@ -418,26 +561,29 @@ describe('refreshRemoteConfig', () => { await refreshRemoteConfig() await vi.advanceTimersByTimeAsync(15 * 60_000) - expect(sessionAgentGrant.value).toBeUndefined() - expect(sessionAgentGrantValidUntil.value).toBeUndefined() + const store = useRemoteConfigStore() + expect(store.agentGrant).toBeUndefined() + expect(store.agentGrantValidUntil).toBeUndefined() }) it('keeps this session granted when the poll fails transiently', async () => { - sessionAgentGrant.value = true + const store = useRemoteConfigStore() + store.acceptConfig({ 'agent-in-app-experience': true }, true) mockAuthenticatedFetch(mockErrorResponse(503, 'Service Unavailable')) await refreshRemoteConfig() - expect(sessionAgentGrant.value).toBe(true) + expect(store.agentGrant).toBe(true) }) it('drops the grant when auth itself is rejected', async () => { - sessionAgentGrant.value = true + const store = useRemoteConfigStore() + store.acceptConfig({ 'agent-in-app-experience': true }, true) mockAuthenticatedFetch(mockErrorResponse(401, 'Unauthorized')) await refreshRemoteConfig() - expect(sessionAgentGrant.value).toBeUndefined() + expect(store.agentGrant).toBeUndefined() }) it('clears config on 403 response', async () => { @@ -445,7 +591,7 @@ describe('refreshRemoteConfig', () => { await refreshRemoteConfig() - expect(remoteConfig.value).toEqual({}) + expect(useRemoteConfigStore().config).toEqual({}) expect(window.__CONFIG__).toEqual({}) }) @@ -454,29 +600,29 @@ describe('refreshRemoteConfig', () => { subscription_required: true, comfy_cloud_base_url: 'https://cloud.example.com' } - remoteConfig.value = existingConfig - window.__CONFIG__ = existingConfig + const store = useRemoteConfigStore() + store.acceptConfig(existingConfig, false) vi.mocked(api.fetchApi).mockRejectedValue(new Error('Network error')) await refreshRemoteConfig() - expect(remoteConfig.value).toEqual(existingConfig) + expect(store.config).toEqual(existingConfig) expect(window.__CONFIG__).toEqual(existingConfig) }) it('preserves config on 500 response', async () => { const existingConfig = { subscription_required: true } - remoteConfig.value = existingConfig - window.__CONFIG__ = existingConfig + const store = useRemoteConfigStore() + store.acceptConfig(existingConfig, false) mockAuthenticatedFetch(mockErrorResponse(500, 'Internal Server Error')) await refreshRemoteConfig() - expect(remoteConfig.value).toEqual(existingConfig) + expect(store.config).toEqual(existingConfig) expect(window.__CONFIG__).toEqual(existingConfig) - expect(remoteConfigState.value).toBe('error') - expect(remoteConfigErrorStatus.value).toBeNull() + expect(store.loadState).toBe('error') + expect(store.errorStatus).toBeNull() }) }) @@ -496,8 +642,8 @@ describe('refreshRemoteConfig', () => { await loading expect(global.fetch).toHaveBeenCalledTimes(3) - expect(remoteConfigState.value).toBe('anonymous') - expect(remoteConfig.value).toEqual(serverConfig) + expect(useRemoteConfigStore().loadState).toBe('anonymous') + expect(useRemoteConfigStore().config).toEqual(serverConfig) vi.useRealTimers() }) @@ -515,7 +661,7 @@ describe('refreshRemoteConfig', () => { await loading expect(global.fetch).toHaveBeenCalledTimes(2) - expect(remoteConfig.value).toEqual(serverConfig) + expect(useRemoteConfigStore().config).toEqual(serverConfig) vi.useRealTimers() }) @@ -571,7 +717,7 @@ describe('refreshRemoteConfig', () => { await loading expect(global.fetch).toHaveBeenCalledTimes(1) - expect(remoteConfig.value).toEqual(serverConfig) + expect(useRemoteConfigStore().config).toEqual(serverConfig) vi.useRealTimers() }) }) diff --git a/src/platform/remoteConfig/refreshRemoteConfig.ts b/src/platform/remoteConfig/refreshRemoteConfig.ts index 0df042e396f..656c41d7237 100644 --- a/src/platform/remoteConfig/refreshRemoteConfig.ts +++ b/src/platform/remoteConfig/refreshRemoteConfig.ts @@ -7,22 +7,12 @@ import { isCloud } from '@/platform/distribution/types' import { reportError } from '@comfyorg/telemetry/reportError' import { isLoopbackHost } from '@/utils/hostWhitelist' -import { - authenticatedRemoteConfigState, - remoteConfig, - remoteConfigErrorStatus, - remoteConfigRevision, - remoteConfigState, - sessionAgentGrant, - sessionAgentGrantValidUntil, - useRemoteConfigCache -} from './remoteConfig' +import { useRemoteConfigStore } from './remoteConfigStore' // 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 { /** @@ -35,45 +25,14 @@ 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 } = - remoteConfig.value - const retainedConfig = { - ...(comfy_api_base_url && { comfy_api_base_url }), - ...(comfy_cloud_base_url && { comfy_cloud_base_url }), - ...(comfy_platform_base_url && { comfy_platform_base_url }) - } - window.__CONFIG__ = retainedConfig - remoteConfig.value = retainedConfig - remoteConfigErrorStatus.value = null - remoteConfigState.value = 'unloaded' - authenticatedRemoteConfigState.value = 'unloaded' - clearSessionAgentGrant() + useRemoteConfigStore().invalidate() } async function fetchRemoteConfig( @@ -101,31 +60,6 @@ async function fetchRemoteConfig( 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 - const cache = useRemoteConfigCache() - cache.cachedBillingControlEnabled.value = Boolean( - config.billing_control_enabled - ) - cache.cachedV1PaymentRecovery.value = Boolean(config.v1_payment_recovery) - cacheSessionAgentGrant(config['agent-in-app-experience'] === true) - } else { - authenticatedRemoteConfigState.value = 'unloaded' - authenticatedLoadingGeneration = undefined - clearSessionAgentGrant() - } - remoteConfigRevision.value++ -} - /** * The anonymous document answers `unified_web_session` false for a cookie-only * caller; only a credentialed read that names its client is authoritative. @@ -141,65 +75,19 @@ async function readCredentialedWebSessionFlag( probe: async () => true }) if (generation !== refreshGeneration) return - const merged: Record = { - ...config, - unified_web_session: enabled - } - window.__CONFIG__ = merged - remoteConfig.value = merged - 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) { - 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) { - authenticatedRemoteConfigState.value = 'error' - authenticatedLoadingGeneration = undefined - } - remoteConfigState.value = 'error' - remoteConfigRevision.value++ + useRemoteConfigStore().acceptUnifiedWebSession(enabled) } -/** - * Loads remote configuration from the backend /features endpoint - * and updates the reactive remoteConfig ref. - * - * Sets remoteConfigState to: - * - 'anonymous' when loaded without auth - * - 'authenticated' when loaded with auth - * - 'error' when load fails - */ +/** Loads `/features` into the remote config store, anonymously or with auth. */ export async function refreshRemoteConfig( options: RefreshRemoteConfigOptions = {} ): Promise { const { useAuth = true, signal } = options const generation = ++refreshGeneration - const previousAuthenticatedState = authenticatedRemoteConfigState.value + const store = useRemoteConfigStore() + const previousAuthenticatedState = store.authenticatedLoadState if (useAuth && previousAuthenticatedState !== 'authenticated') { - authenticatedRemoteConfigState.value = 'loading' + store.beginAuthenticatedLoad() authenticatedLoadingGeneration = generation } const controller = new AbortController() @@ -226,28 +114,30 @@ export async function refreshRemoteConfig( if (generation !== refreshGeneration) return if (signal?.aborted) return if (useAuth && !authenticated) { - authenticatedRemoteConfigState.value = 'error' - authenticatedLoadingGeneration = undefined - remoteConfigErrorStatus.value = null - remoteConfigState.value = 'error' console.warn( 'Rejected authenticated remote config response without credentials' ) - remoteConfigRevision.value++ + authenticatedLoadingGeneration = undefined + store.failLoad(true) return } - commitRemoteConfigSuccess(config, useAuth) + authenticatedLoadingGeneration = undefined + store.acceptConfig(config, useAuth) if (!useAuth) await readCredentialedWebSessionFlag(config, generation) return } - commitRemoteConfigFailure(response, useAuth) + console.warn('Failed to load remote config:', response.statusText) + if (useAuth) authenticatedLoadingGeneration = undefined + store.failLoad(useAuth, response.status) } catch (error) { if (generation !== refreshGeneration) return if (signal?.aborted) return - commitRemoteConfigException(error, useAuth) + console.error('Failed to fetch remote config:', error) + if (useAuth) authenticatedLoadingGeneration = undefined + store.failLoad(useAuth) } finally { if (authenticatedLoadingGeneration === generation) { - authenticatedRemoteConfigState.value = previousAuthenticatedState + store.abandonAuthenticatedLoad(previousAuthenticatedState) authenticatedLoadingGeneration = undefined } clearTimeout(timeoutId) @@ -272,7 +162,7 @@ export async function loadRemoteConfigUntilReady(): Promise { let unnamedProjectReads = 0 for (let attempt = 0; ; attempt++) { await refreshRemoteConfig({ useAuth: false }) - if (remoteConfigState.value !== 'error') { + if (useRemoteConfigStore().loadState !== 'error') { if (hasServerFirebaseConfig()) return unnamedProjectReads++ if (unnamedProjectReads === 1) { diff --git a/src/platform/remoteConfig/remoteConfig.test.ts b/src/platform/remoteConfig/remoteConfig.test.ts deleted file mode 100644 index ba71e1751e8..00000000000 --- a/src/platform/remoteConfig/remoteConfig.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it, onTestFinished } from 'vitest' - -import { useRemoteConfigCache } from './remoteConfig' - -describe('useRemoteConfigCache', () => { - it('reads persisted flags on first use, not at import, and shares one cache', () => { - localStorage.setItem('billing_control_enabled', 'true') - localStorage.setItem('v1_payment_recovery', 'false') - onTestFinished(() => { - localStorage.removeItem('billing_control_enabled') - localStorage.removeItem('v1_payment_recovery') - }) - - const cache = useRemoteConfigCache() - - expect(cache.cachedBillingControlEnabled.value).toBe(true) - expect(cache.cachedV1PaymentRecovery.value).toBe(false) - expect(useRemoteConfigCache()).toBe(cache) - }) -}) diff --git a/src/platform/remoteConfig/remoteConfig.ts b/src/platform/remoteConfig/remoteConfig.ts deleted file mode 100644 index 254eed2e1d0..00000000000 --- a/src/platform/remoteConfig/remoteConfig.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { StorageSerializers, createGlobalState, useStorage } from '@vueuse/core' - -import type { ServerFeatureFlag } from '@/platform/remoteConfig/serverFeatureFlag' - -/** - * Remote configuration service - * - * Fetches configuration from the server at runtime, enabling: - * - Feature flags without rebuilding - * - Server-side feature discovery - * - Version compatibility management - * - Avoiding vendor lock-in for native apps - * - * This module is tree-shaken in OSS builds. - */ - -import { computed, ref } from 'vue' - -import type { RemoteConfig } from './types' - -/** - * Load state for remote configuration. - * - 'unloaded': No config loaded yet - * - 'anonymous': Config loaded without auth (bootstrap) - * - 'authenticated': Config loaded with auth (user-specific flags available) - * - '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( - () => authenticatedRemoteConfigState.value === 'authenticated' -) - -/** - * Reactive remote configuration - * Updated whenever config is loaded from the server - */ -export const remoteConfig = ref({}) - -export function configValueOrDefault( - remoteConfig: RemoteConfig, - key: K, - defaultValue: NonNullable -): NonNullable { - const configValue = remoteConfig[key] - return configValue || defaultValue -} - -/** Last authenticated agent-allowlist answer, kept in memory for this session and never persisted. */ -export const sessionAgentGrant = ref() -export const sessionAgentGrantValidUntil = ref() - -function createRemoteConfigCache() { - return { - cachedBillingControlEnabled: useStorage( - 'billing_control_enabled' satisfies `${ServerFeatureFlag.BILLING_CONTROL_ENABLED}`, - undefined, - undefined, - { serializer: StorageSerializers.boolean } - ), - cachedV1PaymentRecovery: useStorage( - 'v1_payment_recovery' satisfies `${ServerFeatureFlag.V1_PAYMENT_RECOVERY}`, - undefined, - undefined, - { serializer: StorageSerializers.boolean } - ) - } -} - -/** Persisted server-flag cache, created on first use and shared by every caller. */ -export const useRemoteConfigCache = createGlobalState(createRemoteConfigCache) diff --git a/src/platform/remoteConfig/remoteConfigStore.test.ts b/src/platform/remoteConfig/remoteConfigStore.test.ts new file mode 100644 index 00000000000..4bd3ed509ca --- /dev/null +++ b/src/platform/remoteConfig/remoteConfigStore.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' + +import { useRemoteConfigStore } from './remoteConfigStore' + +type RemoteConfigStore = ReturnType + +describe('useRemoteConfigStore', () => { + it.for([ + { + name: 'unloaded', + act: (store: RemoteConfigStore) => store.invalidate(), + loaded: false + }, + { + name: 'anonymous', + act: (store: RemoteConfigStore) => store.acceptConfig({}, false), + loaded: false + }, + { + name: 'authenticated', + act: (store: RemoteConfigStore) => store.acceptConfig({}, true), + loaded: true + }, + { + name: 'authenticated then reloading', + act: (store: RemoteConfigStore) => { + store.acceptConfig({}, true) + store.beginAuthenticatedLoad() + }, + loaded: false + }, + { + name: 'authenticated then an anonymous read failed', + act: (store: RemoteConfigStore) => { + store.acceptConfig({}, true) + store.failLoad(false) + }, + loaded: true + }, + { + name: 'authenticated then an authenticated read failed', + act: (store: RemoteConfigStore) => { + store.acceptConfig({}, true) + store.failLoad(true) + }, + loaded: false + } + ])('isAuthenticatedConfigLoaded is $loaded when $name', ({ act, loaded }) => { + const store = useRemoteConfigStore() + + act(store) + + expect(store.isAuthenticatedConfigLoaded).toBe(loaded) + }) +}) diff --git a/src/platform/remoteConfig/remoteConfigStore.ts b/src/platform/remoteConfig/remoteConfigStore.ts new file mode 100644 index 00000000000..4a25d7b1c4d --- /dev/null +++ b/src/platform/remoteConfig/remoteConfigStore.ts @@ -0,0 +1,156 @@ +import { StorageSerializers, useStorage } from '@vueuse/core' +import { defineStore } from 'pinia' +import { computed, ref, shallowRef } from 'vue' + +import type { ServerFeatureFlag } from '@/platform/remoteConfig/serverFeatureFlag' + +import type { RemoteConfig } from './types' + +type RemoteConfigLoadState = + | 'unloaded' + | 'anonymous' + | 'authenticated' + | 'error' +type AuthenticatedRemoteConfigLoadState = + | 'unloaded' + | 'loading' + | 'authenticated' + | 'error' + +const AGENT_GRANT_FALLBACK_MS = 15 * 60_000 + +export function configValueOrDefault( + remoteConfig: RemoteConfig, + key: K, + defaultValue: NonNullable +): NonNullable { + const configValue = remoteConfig[key] + return configValue || defaultValue +} + +/** Runtime configuration served by `/features`, changed only through its actions. */ +export const useRemoteConfigStore = defineStore('remoteConfig', () => { + const config = shallowRef({}) + const loadState = ref('unloaded') + const authenticatedLoadState = + ref('unloaded') + const errorStatus = ref(null) + const agentGrant = ref() + const agentGrantValidUntil = ref() + let agentGrantExpiryTimer: ReturnType | undefined + + const cachedBillingControlEnabled = useStorage( + 'billing_control_enabled' satisfies `${ServerFeatureFlag.BILLING_CONTROL_ENABLED}`, + undefined, + undefined, + { serializer: StorageSerializers.boolean } + ) + const cachedV1PaymentRecovery = useStorage( + 'v1_payment_recovery' satisfies `${ServerFeatureFlag.V1_PAYMENT_RECOVERY}`, + undefined, + undefined, + { serializer: StorageSerializers.boolean } + ) + + function publishConfig(next: RemoteConfig): void { + window.__CONFIG__ = next + config.value = next + } + + function clearAgentGrant(): void { + clearTimeout(agentGrantExpiryTimer) + agentGrantExpiryTimer = undefined + agentGrant.value = undefined + agentGrantValidUntil.value = undefined + } + + function grantAgentForSession(granted: boolean): void { + clearTimeout(agentGrantExpiryTimer) + agentGrant.value = granted + const validUntil = Date.now() + AGENT_GRANT_FALLBACK_MS + agentGrantValidUntil.value = validUntil + agentGrantExpiryTimer = setTimeout(() => { + if (agentGrantValidUntil.value !== validUntil) return + clearAgentGrant() + }, AGENT_GRANT_FALLBACK_MS) + } + + function beginAuthenticatedLoad(): void { + authenticatedLoadState.value = 'loading' + } + + function abandonAuthenticatedLoad( + previous: AuthenticatedRemoteConfigLoadState + ): void { + authenticatedLoadState.value = previous + } + + function acceptConfig(next: RemoteConfig, authenticated: boolean): void { + publishConfig(next) + errorStatus.value = null + loadState.value = authenticated ? 'authenticated' : 'anonymous' + if (!authenticated) { + authenticatedLoadState.value = 'unloaded' + clearAgentGrant() + return + } + authenticatedLoadState.value = 'authenticated' + cachedBillingControlEnabled.value = Boolean(next.billing_control_enabled) + cachedV1PaymentRecovery.value = Boolean(next.v1_payment_recovery) + grantAgentForSession(next['agent-in-app-experience'] === true) + } + + function acceptUnifiedWebSession(enabled: boolean): void { + publishConfig({ ...config.value, unified_web_session: enabled }) + } + + function failLoad(authenticated: boolean, status?: number): void { + const identityRejected = authenticated && (status === 401 || status === 403) + errorStatus.value = identityRejected ? status : null + if (identityRejected) { + publishConfig({}) + clearAgentGrant() + } + if (authenticated) authenticatedLoadState.value = 'error' + loadState.value = 'error' + } + + function invalidate(): void { + const { + comfy_api_base_url, + comfy_cloud_base_url, + comfy_platform_base_url + } = config.value + publishConfig({ + ...(comfy_api_base_url && { comfy_api_base_url }), + ...(comfy_cloud_base_url && { comfy_cloud_base_url }), + ...(comfy_platform_base_url && { comfy_platform_base_url }) + }) + errorStatus.value = null + loadState.value = 'unloaded' + authenticatedLoadState.value = 'unloaded' + clearAgentGrant() + } + + return { + config: computed(() => config.value), + loadState: computed(() => loadState.value), + authenticatedLoadState: computed(() => authenticatedLoadState.value), + isAuthenticatedConfigLoaded: computed( + () => authenticatedLoadState.value === 'authenticated' + ), + errorStatus: computed(() => errorStatus.value), + agentGrant: computed(() => agentGrant.value), + agentGrantValidUntil: computed(() => agentGrantValidUntil.value), + cachedBillingControlEnabled: computed( + () => cachedBillingControlEnabled.value + ), + cachedV1PaymentRecovery: computed(() => cachedV1PaymentRecovery.value), + beginAuthenticatedLoad, + abandonAuthenticatedLoad, + acceptConfig, + acceptUnifiedWebSession, + failLoad, + invalidate + } +}) diff --git a/src/platform/telemetry/hostTelemetryEnabled.ts b/src/platform/telemetry/hostTelemetryEnabled.ts index 9b97babfb3b..b4a80a80dbc 100644 --- a/src/platform/telemetry/hostTelemetryEnabled.ts +++ b/src/platform/telemetry/hostTelemetryEnabled.ts @@ -1,4 +1,4 @@ -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { getDevOverride } from '@/utils/devFeatureFlagOverride' const ENABLE_TELEMETRY_FEATURE = 'enable_telemetry' @@ -7,5 +7,5 @@ export function isHostTelemetryEnabled(): boolean { const override = getDevOverride(ENABLE_TELEMETRY_FEATURE) if (override !== undefined) return override - return remoteConfig.value.enable_telemetry === true + return useRemoteConfigStore().config.enable_telemetry === true } diff --git a/src/platform/telemetry/initHostTelemetry.test.ts b/src/platform/telemetry/initHostTelemetry.test.ts index 7352b8821a1..8d7d1e130db 100644 --- a/src/platform/telemetry/initHostTelemetry.test.ts +++ b/src/platform/telemetry/initHostTelemetry.test.ts @@ -1,19 +1,18 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { setTelemetryRegistry, useTelemetry } from '@comfyorg/telemetry' import { initHostTelemetry } from '@/platform/telemetry/initHostTelemetry' import { TelemetryEvents } from '@comfyorg/telemetry/types' describe('initHostTelemetry', () => { afterEach(() => { - remoteConfig.value = {} setTelemetryRegistry(null) delete window.__comfyDesktop2 }) it('leaves the registry untouched when enable_telemetry is on but the host Telemetry bridge is absent', () => { - remoteConfig.value = { enable_telemetry: true } + useRemoteConfigStore().acceptConfig({ enable_telemetry: true }, false) initHostTelemetry() @@ -26,7 +25,7 @@ describe('initHostTelemetry', () => { isRemote: () => false, Telemetry: { capture: vi.fn() } } - remoteConfig.value = { enable_telemetry: false } + useRemoteConfigStore().acceptConfig({ enable_telemetry: false }, false) initHostTelemetry() @@ -36,7 +35,7 @@ describe('initHostTelemetry', () => { it('registers the host telemetry sink when enable_telemetry and the bridge are present', () => { const capture = vi.fn() window.__comfyDesktop2 = { isRemote: () => false, Telemetry: { capture } } - remoteConfig.value = { enable_telemetry: true } + useRemoteConfigStore().acceptConfig({ enable_telemetry: true }, false) initHostTelemetry() useTelemetry()?.trackSignupOpened() @@ -50,7 +49,7 @@ describe('initHostTelemetry', () => { it('dispatches canonical billing events through the host registry', () => { const capture = vi.fn() window.__comfyDesktop2 = { isRemote: () => false, Telemetry: { capture } } - remoteConfig.value = { enable_telemetry: true } + useRemoteConfigStore().acceptConfig({ enable_telemetry: true }, false) initHostTelemetry() useTelemetry()?.trackBillingEvent({ diff --git a/src/platform/telemetry/providers/cloud/MixpanelTelemetryProvider.test.ts b/src/platform/telemetry/providers/cloud/MixpanelTelemetryProvider.test.ts index 838591ca5ba..0a0ae64f73b 100644 --- a/src/platform/telemetry/providers/cloud/MixpanelTelemetryProvider.test.ts +++ b/src/platform/telemetry/providers/cloud/MixpanelTelemetryProvider.test.ts @@ -21,10 +21,6 @@ vi.mock(import('@/platform/telemetry/utils/surveyNormalization'), () => ({ normalizeSurveyResponses: mockNormalizeSurveyResponses })) -vi.mock(import('@/platform/remoteConfig/remoteConfig'), () => ({ - remoteConfig: { value: null } -})) - import { MixpanelTelemetryProvider } from '@/platform/telemetry/providers/cloud/MixpanelTelemetryProvider' import type { AuthMetadata, diff --git a/src/platform/telemetry/providers/cloud/MixpanelTelemetryProvider.ts b/src/platform/telemetry/providers/cloud/MixpanelTelemetryProvider.ts index 635c68c86c8..5e6c7e44656 100644 --- a/src/platform/telemetry/providers/cloud/MixpanelTelemetryProvider.ts +++ b/src/platform/telemetry/providers/cloud/MixpanelTelemetryProvider.ts @@ -42,7 +42,7 @@ import type { WorkflowSavedMetadata, WorkspaceInviteMetadata } from '@comfyorg/telemetry/types' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import type { RemoteConfig } from '@/platform/remoteConfig/types' import { OnboardingTourEvents, @@ -92,8 +92,9 @@ export class MixpanelTelemetryProvider implements TelemetryProvider { private disabledEvents = new Set(DEFAULT_DISABLED_EVENTS) constructor() { + const remoteConfigStore = useRemoteConfigStore() watch( - remoteConfig, + () => remoteConfigStore.config, (config) => { this.configureDisabledEvents(config) }, diff --git a/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.test.ts b/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.test.ts index 8a7f91c6162..9027189650a 100644 --- a/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.test.ts +++ b/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.test.ts @@ -11,8 +11,7 @@ import { computed, nextTick, ref } from 'vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import type { SubscriptionInfo } from '@/platform/billing/composables/types' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' -import type { RemoteConfig } from '@/platform/remoteConfig/types' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import type { BootstrapCompleteMetadata, @@ -47,8 +46,7 @@ const hoisted = vi.hoisted(() => { toolkit_node_names: ['LoadImage'] } const refs = { - tier: null as unknown as Ref, - remoteConfig: null as unknown as Ref + tier: null as unknown as Ref } return { @@ -81,8 +79,6 @@ const hoisted = vi.hoisted(() => { vi.mock(import('@/composables/auth/useCurrentUser')) -vi.mock(import('@/platform/remoteConfig/remoteConfig')) - vi.mock(import('posthog-js'), () => hoisted.mockPosthog) vi.mock(import('@/platform/telemetry/utils/getExecutionContext'), () => ({ @@ -166,10 +162,6 @@ function trackSurveys(provider: PostHogTelemetryProvider, ids: string[]): void { describe('PostHogTelemetryProvider', () => { beforeEach(() => { - hoisted.refs.remoteConfig = remoteConfig - hoisted.refs.remoteConfig.value = {} - // Fresh tier ref per test: each provider registers an undisposed tier - // watch, so a shared ref would leak watchers across tests. hoisted.refs.tier = ref(null) const billing = useBillingContext() billing.tier = computed(() => hoisted.refs.tier.value) @@ -235,12 +227,16 @@ describe('PostHogTelemetryProvider', () => { }) it('applies posthog_config overrides from remote config', async () => { - hoisted.refs.remoteConfig.value = { - posthog_config: { - debug: true, - api_host: 'https://custom.host.com' - } - } + useRemoteConfigStore().acceptConfig( + { + posthog_project_token: 'phc_test_token', + posthog_config: { + debug: true, + api_host: 'https://custom.host.com' + } + }, + false + ) createProvider() await vi.dynamicImportSettled() @@ -254,9 +250,13 @@ describe('PostHogTelemetryProvider', () => { }) it("lets the server's person_profiles win over the client default", async () => { - hoisted.refs.remoteConfig.value = { - posthog_config: { person_profiles: 'always' } - } + useRemoteConfigStore().acceptConfig( + { + posthog_project_token: 'phc_test_token', + posthog_config: { person_profiles: 'always' } + }, + false + ) createProvider() await vi.dynamicImportSettled() @@ -2200,11 +2200,15 @@ describe('PostHogTelemetryProvider', () => { it('remoteConfig.posthog_config cannot override before_send (PII stripping)', async () => { const remoteBefore_send = vi.fn() - hoisted.refs.remoteConfig.value = { - posthog_config: { - before_send: remoteBefore_send - } - } + useRemoteConfigStore().acceptConfig( + { + posthog_project_token: 'phc_test_token', + posthog_config: { + before_send: remoteBefore_send + } + }, + false + ) createProvider() await vi.dynamicImportSettled() diff --git a/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.ts b/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.ts index 54f1f69f6aa..1cf89c25b33 100644 --- a/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.ts +++ b/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.ts @@ -25,7 +25,7 @@ import { import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { whenStoresReady } from '@/platform/telemetry/storeReadiness' import type { RemoteConfig } from '@/platform/remoteConfig/types' import { getAgentPanelOpen } from '@/platform/telemetry/utils/getAgentPanelOpen' @@ -224,8 +224,9 @@ export class PostHogTelemetryProvider implements TelemetryProvider { constructor() { const windowConfig = window.__CONFIG__ + const remoteConfigStore = useRemoteConfigStore() watch( - remoteConfig, + () => remoteConfigStore.config, (config) => { this.configureDisabledEvents(config) }, @@ -240,7 +241,7 @@ export class PostHogTelemetryProvider implements TelemetryProvider { void import('posthog-js') .then(async (posthogModule) => { this.posthog = posthogModule.default - const serverConfig = remoteConfig.value.posthog_config ?? {} + const serverConfig = remoteConfigStore.config.posthog_config ?? {} this.posthog.init(apiKey, { api_host: windowConfig?.posthog_api_host || DEFAULT_POSTHOG_API_HOST, diff --git a/src/platform/telemetry/providers/cloud/SyftTelemetryProvider.test.ts b/src/platform/telemetry/providers/cloud/SyftTelemetryProvider.test.ts index e06b9b8cdf6..6d6ccf13853 100644 --- a/src/platform/telemetry/providers/cloud/SyftTelemetryProvider.test.ts +++ b/src/platform/telemetry/providers/cloud/SyftTelemetryProvider.test.ts @@ -1,20 +1,18 @@ import { computed } from 'vue' import { beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock(import('@/composables/auth/useCurrentUser')) +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' -vi.mock(import('@/platform/remoteConfig/remoteConfig')) +vi.mock(import('@/composables/auth/useCurrentUser')) const SYFT_SRC = 'https://cdn.sy-d.io/syftnext/syft.umd.js' async function importProvider() { - const [{ SyftTelemetryProvider }, { useCurrentUser }, { remoteConfig }] = - await Promise.all([ - import('@/platform/telemetry/providers/cloud/SyftTelemetryProvider'), - import('@/composables/auth/useCurrentUser'), - import('@/platform/remoteConfig/remoteConfig') - ]) - return { SyftTelemetryProvider, useCurrentUser, remoteConfig } + const [{ SyftTelemetryProvider }, { useCurrentUser }] = await Promise.all([ + import('@/platform/telemetry/providers/cloud/SyftTelemetryProvider'), + import('@/composables/auth/useCurrentUser') + ]) + return { SyftTelemetryProvider, useCurrentUser } } function installSyftSpy(): SyftDataClient { @@ -64,8 +62,11 @@ describe('SyftTelemetryProvider', () => { }) it('loads the Syft SDK once when a source id is configured', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) const appendChild = mockScriptAppend() new SyftTelemetryProvider() @@ -81,8 +82,11 @@ describe('SyftTelemetryProvider', () => { }) it('clears the stub after SDK load failure so later calls can retry', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) const appendChild = mockScriptAppend() const provider = new SyftTelemetryProvider() @@ -106,8 +110,11 @@ describe('SyftTelemetryProvider', () => { }) it('replays a pending identify with its original traits after SDK load failure', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) const appendChild = mockScriptAppend() new SyftTelemetryProvider().trackAuth({ @@ -128,9 +135,11 @@ describe('SyftTelemetryProvider', () => { }) it('replays at most once but still allows a later manual retry', async () => { - const { SyftTelemetryProvider, remoteConfig, useCurrentUser } = - await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider, useCurrentUser } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) const appendChild = mockScriptAppend() useCurrentUser().userEmail = computed(() => 'restored@example.com') const provider = new SyftTelemetryProvider() @@ -156,8 +165,11 @@ describe('SyftTelemetryProvider', () => { }) it('leaves an externally installed client untouched on script error', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) const appendChild = mockScriptAppend() new SyftTelemetryProvider().trackAuth({ @@ -176,8 +188,11 @@ describe('SyftTelemetryProvider', () => { }) it('rejects pending fetchID promises when the SDK fails to load', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) const appendChild = mockScriptAppend() new SyftTelemetryProvider() @@ -189,14 +204,17 @@ describe('SyftTelemetryProvider', () => { }) it('bootstraps on the first call after the source id arrives', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() + const { SyftTelemetryProvider } = await importProvider() const appendChild = mockScriptAppend() const provider = new SyftTelemetryProvider() expect(appendChild).not.toHaveBeenCalled() expect(window.syftc).toBeUndefined() - remoteConfig.value = { syftdata_source_id: 'src-123' } + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) provider.trackAuth({ email: 'late@example.com', is_new_user: false, @@ -213,8 +231,11 @@ describe('SyftTelemetryProvider', () => { }) it('preserves an existing opt-out flag when writing the source id', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) window.syftc = { enabled: false } mockScriptAppend() @@ -224,8 +245,11 @@ describe('SyftTelemetryProvider', () => { }) it('skips identify when Syft installed its disabled-mode client', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) const appendChild = mockScriptAppend() const disabledClient = { enable: vi.fn() } window.syft = disabledClient @@ -243,9 +267,11 @@ describe('SyftTelemetryProvider', () => { }) it('does not touch the current user store during construction', async () => { - const { SyftTelemetryProvider, remoteConfig, useCurrentUser } = - await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider, useCurrentUser } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) mockScriptAppend() new SyftTelemetryProvider() @@ -254,8 +280,11 @@ describe('SyftTelemetryProvider', () => { }) it('preserves an existing GTM-loaded Syft client and script', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) const syft = installSyftSpy() const appendChild = mockScriptAppend() @@ -266,8 +295,11 @@ describe('SyftTelemetryProvider', () => { }) it('identifies new auth users with signup source and normalized email', async () => { - const { SyftTelemetryProvider, remoteConfig } = await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) mockScriptAppend() new SyftTelemetryProvider().trackAuth({ @@ -329,9 +361,11 @@ describe('SyftTelemetryProvider', () => { }) it('identifies restored sessions from the current user store', async () => { - const { SyftTelemetryProvider, remoteConfig, useCurrentUser } = - await importProvider() - remoteConfig.value = { syftdata_source_id: 'src-123' } + const { SyftTelemetryProvider, useCurrentUser } = await importProvider() + useRemoteConfigStore().acceptConfig( + { syftdata_source_id: 'src-123' }, + false + ) mockScriptAppend() useCurrentUser().userEmail = computed(() => 'Restored@Example.com') vi.mocked(useCurrentUser).mockClear() diff --git a/src/platform/telemetry/providers/cloud/SyftTelemetryProvider.ts b/src/platform/telemetry/providers/cloud/SyftTelemetryProvider.ts index c71292a138c..0480fdad154 100644 --- a/src/platform/telemetry/providers/cloud/SyftTelemetryProvider.ts +++ b/src/platform/telemetry/providers/cloud/SyftTelemetryProvider.ts @@ -1,7 +1,7 @@ import { createScriptLoader } from '@comfyorg/shared-frontend-utils/loadExternalScript' import { useCurrentUser } from '@/composables/auth/useCurrentUser' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { normalizeEmail } from '@/platform/telemetry/utils/normalizeEmail' import type { @@ -57,7 +57,7 @@ function createSyftStub(): SyftDataClient { } function ensureSyftClient(): SyftDataClient | SyftDisabledClient | null { - const sourceId = remoteConfig.value.syftdata_source_id + const sourceId = useRemoteConfigStore().config.syftdata_source_id if (!sourceId) return window.syft ?? null window.syftc = { ...window.syftc, sourceId } diff --git a/src/platform/telemetry/providers/cloud/storeReadinessGate.test.ts b/src/platform/telemetry/providers/cloud/storeReadinessGate.test.ts index 1d1e0d1a070..d70f71e4caf 100644 --- a/src/platform/telemetry/providers/cloud/storeReadinessGate.test.ts +++ b/src/platform/telemetry/providers/cloud/storeReadinessGate.test.ts @@ -1,10 +1,9 @@ -import { setActivePinia } from 'pinia' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { computed } from 'vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' const hoisted = vi.hoisted(() => { const customerIoTrack = vi.fn( @@ -76,8 +75,6 @@ vi.mock(import('@customerio/cdp-analytics-browser'), () => ({ InAppPlugin: vi.fn(() => ({ name: 'Customer.io In-App Plugin' })) })) -vi.mock(import('@/platform/remoteConfig/remoteConfig')) - vi.mock(import('@/platform/billing/composables/useBillingContext')) import { @@ -113,8 +110,7 @@ describe('telemetry providers wait for Pinia before touching stores', () => { const billing = useBillingContext() billing.tier = computed(() => null) vi.mocked(useBillingContext).mockReturnValue(billing) - remoteConfig.value = {} - setActivePinia(undefined) + useRemoteConfigStore().acceptConfig({}, false) markStoresPending() }) diff --git a/src/platform/telemetry/storeReadiness.test.ts b/src/platform/telemetry/storeReadiness.test.ts index 0877859a666..dec152eb030 100644 --- a/src/platform/telemetry/storeReadiness.test.ts +++ b/src/platform/telemetry/storeReadiness.test.ts @@ -1,6 +1,4 @@ -import type { Pinia } from 'pinia' -import { getActivePinia, setActivePinia } from 'pinia' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { markStoresPending, @@ -8,23 +6,8 @@ import { whenStoresReady } from './storeReadiness' -/** - * The gate exists for the window before `main.ts` installs Pinia, so these - * tests must opt out of the testing Pinia the global setup installs — and put - * it back afterwards so the global teardown still disposes it. - */ -let globalPinia!: Pinia - -beforeEach(() => { - const pinia = getActivePinia() - if (!pinia) throw new Error('vitest.setup.ts should install a testing Pinia') - globalPinia = pinia - setActivePinia(undefined) -}) - afterEach(() => { markStoresReady() - setActivePinia(globalPinia) }) describe('whenStoresReady', () => { @@ -44,11 +27,4 @@ describe('whenStoresReady', () => { await whenStoresReady() expect(resolved).toHaveBeenCalledOnce() }) - - it('resolves during a pending window once a Pinia instance is active', async () => { - markStoresPending() - setActivePinia(globalPinia) - - await expect(whenStoresReady()).resolves.toBeUndefined() - }) }) diff --git a/src/platform/telemetry/storeReadiness.ts b/src/platform/telemetry/storeReadiness.ts index c618e98bd20..f56e76963b1 100644 --- a/src/platform/telemetry/storeReadiness.ts +++ b/src/platform/telemetry/storeReadiness.ts @@ -1,10 +1,7 @@ -import { getActivePinia } from 'pinia' - -/** Gates store-backed telemetry setup until `main.ts` installs Pinia. */ let storesReady: Promise = Promise.resolve() let resolveStoresReady: (() => void) | undefined -/** Opens the window during which no Pinia instance is installed yet. */ +/** Opens the window during which Pinia is not installed into the app yet. */ export function markStoresPending(): void { if (resolveStoresReady) return storesReady = new Promise((resolve) => { @@ -21,5 +18,5 @@ export function markStoresReady(): void { /** Resolves once store-backed composables are safe to call. */ export function whenStoresReady(): Promise { - return getActivePinia() ? Promise.resolve() : storesReady + return storesReady } diff --git a/src/platform/updates/common/releaseService.test.ts b/src/platform/updates/common/releaseService.test.ts index 8695de4365c..093ee76078e 100644 --- a/src/platform/updates/common/releaseService.test.ts +++ b/src/platform/updates/common/releaseService.test.ts @@ -1,7 +1,7 @@ import axios from 'axios' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useReleaseService } from '@/platform/updates/common/releaseService' // Hoist the mock to avoid hoisting issues @@ -31,13 +31,12 @@ describe('useReleaseService', () => { ] beforeEach(() => { - remoteConfig.value = { comfy_api_base_url: 'https://api.example.com' } + useRemoteConfigStore().acceptConfig( + { comfy_api_base_url: 'https://api.example.com' }, + false + ) vi.mocked(axios.isAxiosError).mockReturnValue(true) service = useReleaseService() - - return () => { - remoteConfig.value = {} - } }) it('should initialize with default state', () => { @@ -93,7 +92,10 @@ describe('useReleaseService', () => { }) it('sends the request to the base URL configured after service creation', async () => { - remoteConfig.value = { comfy_api_base_url: 'https://changed.example.com' } + useRemoteConfigStore().acceptConfig( + { comfy_api_base_url: 'https://changed.example.com' }, + false + ) mockAxiosInstance.get.mockResolvedValue({ data: mockReleases }) await service.getReleases({ project: 'comfyui' }) diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts index 820ecff62bd..60b24b72677 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts @@ -1,6 +1,6 @@ import { fromPartial } from '@total-typescript/shoehorn' import type { User } from 'firebase/auth' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import type { FirebaseIdentity } from '@comfyorg/account-core/firebase' import { COMFY_CLIENT } from '@comfyorg/account-core/requestAuth' @@ -8,7 +8,6 @@ import { COMFY_CLIENT } from '@comfyorg/account-core/requestAuth' import type { IWidget } from '@/lib/litegraph/src/litegraph' import { useSessionCookie } from '@/platform/auth/session/useSessionCookie' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { useRemoteWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget' import { api } from '@/scripts/api' @@ -143,10 +142,6 @@ describe('remote widgets on the shared web session', () => { vi.spyOn(api, 'resetSocket').mockResolvedValue() }) - afterEach(() => { - remoteConfig.value = {} - }) - it.for([ { workspace: 'ws-team', other: 'ws-personal' }, { workspace: 'ws-personal', other: 'ws-team' } diff --git a/src/router.signedOutReroute.test.ts b/src/router.signedOutReroute.test.ts index 4872300fa86..1a26be8bb24 100644 --- a/src/router.signedOutReroute.test.ts +++ b/src/router.signedOutReroute.test.ts @@ -8,10 +8,7 @@ import type { WebSession } from '@comfyorg/account-core/webSession' import { cloudSignIn } from '@/platform/auth/session/cloudIdentityBoot' import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore' import { invalidateRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' -import { - remoteConfig, - remoteConfigState -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { createAppRouter } from '@/router' import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useAuthStore } from '@/stores/authStore' @@ -60,8 +57,6 @@ describe('a requiresAuth route whose account leaves the tab', () => { afterEach(() => { localStorage.removeItem(REROUTE_FLAG) - remoteConfig.value = {} - remoteConfigState.value = 'unloaded' }) it('stays on the page with the reroute flag off', async () => { @@ -86,10 +81,15 @@ describe('a requiresAuth route whose account leaves the tab', () => { }) it('lands on sign-in when signing out clears the remote config that enabled the reroute', async () => { - remoteConfig.value = { signed_out_reroute_enabled: true } + const remoteConfigStore = useRemoteConfigStore() + const signedOutConfig = remoteConfigStore.config + remoteConfigStore.acceptConfig( + { ...signedOutConfig, signed_out_reroute_enabled: true }, + false + ) const router = await openSurveySignedIn() - remoteConfig.value = {} + remoteConfigStore.acceptConfig(signedOutConfig, false) useAuthStore().currentUser = null await vi.waitFor(() => @@ -123,8 +123,11 @@ describe('a requiresAuth route whose account leaves the tab', () => { ) it('lands on sign-in when Firebase signs out before the web session does', async () => { - remoteConfig.value = { signed_out_reroute_enabled: true } - remoteConfigState.value = 'authenticated' + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { ...remoteConfigStore.config, signed_out_reroute_enabled: true }, + true + ) const webSession = useCloudWebSessionStore() webSession.state = { phase: 'signed_in', session: sessionFor('user-a') } const router = await openSurveySignedIn() @@ -158,12 +161,15 @@ describe('a requiresAuth route whose account leaves the tab', () => { }) it("stays on the page when a switched-in account's flag is off and its config fails", async () => { - remoteConfig.value = { signed_out_reroute_enabled: true } - remoteConfigState.value = 'authenticated' + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { ...remoteConfigStore.config, signed_out_reroute_enabled: true }, + true + ) const router = await openSurveySignedIn() - remoteConfig.value = {} - remoteConfigState.value = 'error' + remoteConfigStore.invalidate() + remoteConfigStore.failLoad(true) useAuthStore().currentUser = fromPartial({ uid: 'user-b' }) await nextTick() useAuthStore().currentUser = null @@ -174,16 +180,19 @@ describe('a requiresAuth route whose account leaves the tab', () => { }) it('stays on the page when an account switched in after a Firebase sign-out has its flag off and its config fails', async () => { - remoteConfig.value = { signed_out_reroute_enabled: true } - remoteConfigState.value = 'authenticated' + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { ...remoteConfigStore.config, signed_out_reroute_enabled: true }, + true + ) const webSession = useCloudWebSessionStore() webSession.state = { phase: 'signed_in', session: sessionFor('user-a') } const router = await openSurveySignedIn() useAuthStore().currentUser = null await nextTick() - remoteConfig.value = {} - remoteConfigState.value = 'error' + remoteConfigStore.invalidate() + remoteConfigStore.failLoad(true) useAuthStore().currentUser = fromPartial({ uid: 'user-b' }) await nextTick() useAuthStore().currentUser = null @@ -195,12 +204,14 @@ describe('a requiresAuth route whose account leaves the tab', () => { }) it('lands on sign-in when the remote config fails to load before the account leaves', async () => { - remoteConfig.value = { signed_out_reroute_enabled: true } - remoteConfigState.value = 'authenticated' + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig( + { ...remoteConfigStore.config, signed_out_reroute_enabled: true }, + true + ) const router = await openSurveySignedIn() - remoteConfig.value = {} - remoteConfigState.value = 'error' + remoteConfigStore.failLoad(true, 401) await nextTick() useAuthStore().currentUser = null diff --git a/src/router.ts b/src/router.ts index 5c2d479361e..913b37790f6 100644 --- a/src/router.ts +++ b/src/router.ts @@ -26,7 +26,7 @@ import { readSsoHint } from '@/platform/auth/session/ssoReentryStorage' import { trackSsoRequiredShown } from '@/platform/auth/sso/ssoTelemetry' -import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { isCloud, isDesktop } from '@/platform/distribution/types' import { useTelemetry } from '@comfyorg/telemetry' import { reportError } from '@comfyorg/telemetry/reportError' @@ -144,7 +144,6 @@ const RECOVERING_SESSION_PHASES = new Set([ ]) function installCloudAuthGuards(router: Router): void { - const { flags } = useFeatureFlags() const PUBLIC_ROUTE_NAMES = new Set([ 'cloud-login', 'cloud-signup', @@ -210,6 +209,8 @@ function installCloudAuthGuards(router: Router): void { watchedAccounts.add(authStore) const apiKeyAuthStore = useApiKeyAuthStore() const webSession = useCloudWebSessionStore() + const remoteConfigStore = useRemoteConfigStore() + const { flags: accountFlags } = useFeatureFlags() const account = computed(() => { if (authStore.isAuthenticated || apiKeyAuthStore.isAuthenticated) return 'signed_in' @@ -223,8 +224,8 @@ function installCloudAuthGuards(router: Router): void { watch( [ account, - () => flags.signedOutRerouteEnabled, - remoteConfigState, + () => accountFlags.signedOutRerouteEnabled, + () => remoteConfigStore.loadState, () => authStore.currentUser?.uid ], ([state, enabled, configState, uid]) => { @@ -251,6 +252,7 @@ function installCloudAuthGuards(router: Router): void { to: RouteLocationNormalized, query: LocationQueryRaw ): NavigationGuardReturn { + const { flags } = useFeatureFlags() const ssoError = flags.ssoEnabled ? readSsoError(to.query.sso_error) : undefined @@ -354,7 +356,7 @@ function installCloudAuthGuards(router: Router): void { } if (!isDesktop && to.path === '/') { - if (!flags.onboardingSurveyEnabled) { + if (!useFeatureFlags().flags.onboardingSurveyEnabled) { return } const { getSurveyCompletedStatus } = diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index 7ddbc8e3b83..81aa6fc041a 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -21,11 +21,8 @@ import { isSurveyReplayRequested, requestOnboardingReplay } from '@/platform/onboarding/onboardingReplay' -import { - remoteConfig, - remoteConfigState -} from '@/platform/remoteConfig/remoteConfig' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useDialogService } from '@/services/dialogService' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { api } from '@/scripts/api' @@ -1369,7 +1366,7 @@ describe('useAuthStore', () => { authStateCallback(accountB) expect(accountASignal?.aborted).toBe(true) - expect(remoteConfigState.value).toBe('unloaded') + expect(useRemoteConfigStore().loadState).toBe('unloaded') await refreshRemoteConfig() resolveAccountA?.( @@ -1379,7 +1376,7 @@ describe('useAuthStore', () => { ) await accountARefresh - expect(remoteConfig.value.subscription_required).toBe(false) + expect(useRemoteConfigStore().config.subscription_required).toBe(false) }) it('does not reconnect on a same-account token refresh', () => { diff --git a/src/stores/modelStore.test.ts b/src/stores/modelStore.test.ts index 6293a3d9bb3..268255abee5 100644 --- a/src/stores/modelStore.test.ts +++ b/src/stores/modelStore.test.ts @@ -4,7 +4,7 @@ import { reactive, watch } from 'vue' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { assetService } from '@/platform/assets/services/assetService' import type * as DistributionTypes from '@/platform/distribution/types' -import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { api } from '@/scripts/api' import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' import { @@ -21,8 +21,6 @@ const mockDistribution = vi.hoisted( vi.mock(import('@/platform/distribution/types'), () => mockDistribution) -vi.mock(import('@/platform/remoteConfig/remoteConfig')) - const featureState = { serverFeatures: {} as Record } @@ -97,7 +95,6 @@ describe('useModelStore', () => { beforeEach(async () => { mockDistribution.isCloud = false featureState.serverFeatures = reactive({ assets: false }) - remoteConfig.value = {} }) it('lists and refreshes Release models without asset filtering on a picked deployment', async () => { @@ -816,7 +813,10 @@ describe('useModelStore', () => { ) featureState.serverFeatures.assets = true - remoteConfig.value = { supports_model_type_tags: true } + useRemoteConfigStore().acceptConfig( + { supports_model_type_tags: true }, + false + ) await vi.advanceTimersByTimeAsync(1000) await Promise.all(eagerLoads) @@ -839,7 +839,10 @@ describe('useModelStore', () => { expect(api.getModelFolders).toHaveBeenCalledTimes(1) expect(assetService.getAssetModels).toHaveBeenCalledTimes(1) - remoteConfig.value = { supports_model_type_tags: true } + useRemoteConfigStore().acceptConfig( + { supports_model_type_tags: true }, + false + ) await vi.waitFor(() => { expect(api.getModelFolders).toHaveBeenCalledTimes(2) @@ -851,14 +854,20 @@ describe('useModelStore', () => { it('rebuilds again when the capability rolls back', async () => { enableMocks(true) - remoteConfig.value = { supports_model_type_tags: true } + useRemoteConfigStore().acceptConfig( + { supports_model_type_tags: true }, + false + ) store = useModelStore() await store.loadModelFolders() await store.getLoadedModelFolder('checkpoints') expect(api.getModelFolders).toHaveBeenCalledTimes(1) expect(assetService.getAssetModels).toHaveBeenCalledTimes(1) - remoteConfig.value = { supports_model_type_tags: false } + useRemoteConfigStore().acceptConfig( + { supports_model_type_tags: false }, + false + ) await vi.waitFor(() => { expect(api.getModelFolders).toHaveBeenCalledTimes(2) diff --git a/src/utils/sessionFeatureFlagOverride.test.ts b/src/utils/sessionFeatureFlagOverride.test.ts index 13a5330dc82..57da4b9530b 100644 --- a/src/utils/sessionFeatureFlagOverride.test.ts +++ b/src/utils/sessionFeatureFlagOverride.test.ts @@ -191,18 +191,13 @@ describe('getSessionOverride', () => { it('withholds a stored override before Auth has resolved and does not initialize Firebase', async () => { vi.resetModules() - const [ - { getSessionOverride: readFresh }, - { getApps, initializeApp }, - { remoteConfigState } - ] = await Promise.all([ - import('@/utils/sessionFeatureFlagOverride'), - import('firebase/app'), - import('@/platform/remoteConfig/remoteConfig') - ]) + const [{ getSessionOverride: readFresh }, { getApps, initializeApp }] = + await Promise.all([ + import('@/utils/sessionFeatureFlagOverride'), + import('firebase/app') + ]) vi.mocked(initializeApp).mockClear() vi.mocked(getApps).mockReturnValue([]) - remoteConfigState.value = 'anonymous' visit('/?ff=onboarding_tour_enabled') expect(readFresh('onboarding_tour_enabled')).toBeUndefined() diff --git a/src/workbench/extensions/agent/components/agent/message/AgentMessage.test.ts b/src/workbench/extensions/agent/components/agent/message/AgentMessage.test.ts index d51ea673840..2d110656af9 100644 --- a/src/workbench/extensions/agent/components/agent/message/AgentMessage.test.ts +++ b/src/workbench/extensions/agent/components/agent/message/AgentMessage.test.ts @@ -4,10 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { ref } from 'vue' import { microUsdToCredits } from '@comfyorg/shared-frontend-utils/creditsUtil' import { i18n, loadLocale } from '@/i18n' -import { - authenticatedRemoteConfigState, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import type { TurnId } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { toTurnId } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { createAgentEventTransport } from '@/workbench/extensions/agent/services/agent/agentEventTransport' @@ -48,8 +45,10 @@ function paywallMessage(message?: string): AssistantMessage { describe('AgentMessage credit usage', () => { beforeEach(() => { - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { 'agent-credit-usage-summary': 'treatment' } + useRemoteConfigStore().acceptConfig( + { 'agent-credit-usage-summary': 'treatment' }, + true + ) }) it('shows the completed turn charge without presenting it as a session total', () => { @@ -196,7 +195,10 @@ describe('AgentMessage credit usage', () => { }) it('hides usage in the control arm', () => { - remoteConfig.value = { 'agent-credit-usage-summary': 'control' } + useRemoteConfigStore().acceptConfig( + { 'agent-credit-usage-summary': 'control' }, + true + ) render(AgentMessage, { props: { message: { diff --git a/src/workbench/extensions/agent/composables/useAgentDockMount.billingContext.test.ts b/src/workbench/extensions/agent/composables/useAgentDockMount.billingContext.test.ts index 79eaf40a7e2..bfd4cfb36a4 100644 --- a/src/workbench/extensions/agent/composables/useAgentDockMount.billingContext.test.ts +++ b/src/workbench/extensions/agent/composables/useAgentDockMount.billingContext.test.ts @@ -18,11 +18,7 @@ import { useAgentDockMount } from '@/workbench/extensions/agent/composables/useA import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' import type { BillingStatusResponse, Plan } from '@comfyorg/billing-core' -import { - authenticatedRemoteConfigState, - remoteConfig, - remoteConfigState -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useBillingContext as useSharedBillingContext } from '@/platform/billing/composables/useBillingContext' @@ -43,29 +39,23 @@ const DEFAULT_BILLING_STATUS: BillingStatusResponse = { subscription_duration: 'MONTHLY' } -const { - mockPlans, - mockFetchPlans, - mockBillingStatus, - mockIsCloud, - mockFreeTierExecutionPermitted -} = vi.hoisted(() => { - const mockBillingStatus: { value: Partial } = { - value: { - is_active: true, - has_funds: true, - subscription_tier: 'PRO', - subscription_duration: 'MONTHLY' +const { mockPlans, mockFetchPlans, mockBillingStatus, mockIsCloud } = + vi.hoisted(() => { + const mockBillingStatus: { value: Partial } = { + value: { + is_active: true, + has_funds: true, + subscription_tier: 'PRO', + subscription_duration: 'MONTHLY' + } } - } - return { - mockPlans: { value: [] as Plan[] }, - mockFetchPlans: vi.fn(async () => undefined), - mockBillingStatus, - mockIsCloud: { value: true }, - mockFreeTierExecutionPermitted: { value: true } - } -}) + return { + mockPlans: { value: [] as Plan[] }, + mockFetchPlans: vi.fn(async () => undefined), + mockBillingStatus, + mockIsCloud: { value: true } + } + }) let mockIsPersonal: Ref @@ -79,18 +69,6 @@ vi.mock(import('@/platform/distribution/types'), () => { vi.mock(import('@/platform/billing/subscription/composables/useSubscription')) -vi.mock( - import('@/platform/billing/subscription/composables/useFreeTierQuota'), - () => ({ - useFreeTierQuota: () => ({ - quotaEnabled: { value: false }, - get freeTierExecutionPermitted() { - return mockFreeTierExecutionPermitted - } - }) - }) -) - vi.mock(import('@/composables/auth/useAuthActions')) vi.mock( @@ -127,7 +105,6 @@ vi.mock(import('@/platform/billing/api/billingApi'), () => ({ describe('useAgentDockMount with the real billing context', () => { beforeEach(() => { mockIsCloud.value = true - mockFreeTierExecutionPermitted.value = true const workspaceStore = useTeamWorkspaceStore() const refs = storeToRefs(workspaceStore) @@ -142,9 +119,9 @@ describe('useAgentDockMount with the real billing context', () => { }) useAuthStore() vi.mocked(workspaceStore.updateActiveWorkspace).mockImplementation(() => {}) - remoteConfig.value = {} - remoteConfigState.value = 'unloaded' - authenticatedRemoteConfigState.value = 'unloaded' + const remoteConfigStore = useRemoteConfigStore() + remoteConfigStore.acceptConfig({}, false) + remoteConfigStore.invalidate() mockIsPersonal.value = true mockPlans.value = [] const subscription = useSubscription() diff --git a/src/workbench/extensions/agent/experiments/creditUsageSummary.test.ts b/src/workbench/extensions/agent/experiments/creditUsageSummary.test.ts index db1387bf5a7..efbc907edeb 100644 --- a/src/workbench/extensions/agent/experiments/creditUsageSummary.test.ts +++ b/src/workbench/extensions/agent/experiments/creditUsageSummary.test.ts @@ -1,9 +1,6 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' -import { - authenticatedRemoteConfigState, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useTelemetry } from '@comfyorg/telemetry' import { getDevOverride } from '@/utils/devFeatureFlagOverride' @@ -13,22 +10,18 @@ import { useCreditUsageSummary } from './creditUsageSummary' -vi.mock(import('@/platform/remoteConfig/remoteConfig')) vi.mock(import('@comfyorg/telemetry')) vi.mock(import('@/utils/devFeatureFlagOverride')) vi.mock(import('@/utils/sessionFeatureFlagOverride')) describe('useCreditUsageSummary', () => { - beforeEach(() => { - authenticatedRemoteConfigState.value = 'unloaded' - remoteConfig.value = {} - }) - it.for([['control', false] as const, ['treatment', true] as const])( 'attributes the %s arm after a charged reply renders', ([arm, shown]) => { - remoteConfig.value = { [CREDIT_USAGE_SUMMARY_FLAG]: arm } - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { [CREDIT_USAGE_SUMMARY_FLAG]: arm }, + true + ) const experiment = useCreditUsageSummary() expect(experiment.showSummary.value).toBe(shown) @@ -52,10 +45,10 @@ describe('useCreditUsageSummary', () => { experiment.expose() expect(useTelemetry()?.trackAgentCreditUsageExposure).not.toHaveBeenCalled() - authenticatedRemoteConfigState.value = 'authenticated' - ;(remoteConfig.value as Record)[ - CREDIT_USAGE_SUMMARY_FLAG - ] = 'unexpected' + const malformedConfig: Record = { + [CREDIT_USAGE_SUMMARY_FLAG]: 'unexpected' + } + useRemoteConfigStore().acceptConfig(malformedConfig, true) experiment.expose() expect(useTelemetry()?.trackAgentCreditUsageExposure).not.toHaveBeenCalled() @@ -67,8 +60,10 @@ describe('useCreditUsageSummary', () => { }) it('permits one new exposure after the panel reopens', () => { - remoteConfig.value = { [CREDIT_USAGE_SUMMARY_FLAG]: 'treatment' } - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { [CREDIT_USAGE_SUMMARY_FLAG]: 'treatment' }, + true + ) const panelStore = useAgentPanelStore() const experiment = useCreditUsageSummary() experiment.expose() diff --git a/src/workbench/extensions/agent/experiments/creditUsageSummary.ts b/src/workbench/extensions/agent/experiments/creditUsageSummary.ts index b3ed7a8d849..b2202d2408e 100644 --- a/src/workbench/extensions/agent/experiments/creditUsageSummary.ts +++ b/src/workbench/extensions/agent/experiments/creditUsageSummary.ts @@ -2,10 +2,7 @@ import { computed } from 'vue' import { zGetFeaturesResponse } from '@comfyorg/ingest-types/zod' -import { - isAuthenticatedConfigLoaded, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useTelemetry } from '@comfyorg/telemetry' import type { AgentCreditUsageVariant } from '@comfyorg/telemetry/types' import { getDevOverride } from '@/utils/devFeatureFlagOverride' @@ -29,7 +26,7 @@ function resolveAssignment(): { const candidate = override !== undefined ? override - : remoteConfig.value[CREDIT_USAGE_SUMMARY_FLAG] + : useRemoteConfigStore().config[CREDIT_USAGE_SUMMARY_FLAG] return { assignment: assignmentSchema.parse(candidate), hasQaOverride: override !== undefined, @@ -39,16 +36,18 @@ function resolveAssignment(): { export function useCreditUsageSummary() { const panelStore = useAgentPanelStore() + const remoteConfigStore = useRemoteConfigStore() const assignment = computed(() => { const resolved = resolveAssignment() - return isAuthenticatedConfigLoaded.value || resolved.hasQaOverride + return remoteConfigStore.isAuthenticatedConfigLoaded || + resolved.hasQaOverride ? resolved.assignment : 'control' }) const attributeExperiment = computed(() => { const resolved = resolveAssignment() return ( - isAuthenticatedConfigLoaded.value && + remoteConfigStore.isAuthenticatedConfigLoaded && !resolved.hasQaOverride && resolved.hasServedAssignment ) diff --git a/src/workbench/extensions/agent/experiments/freeUsePlacement.test.ts b/src/workbench/extensions/agent/experiments/freeUsePlacement.test.ts index b45ae04932a..ef031e1176a 100644 --- a/src/workbench/extensions/agent/experiments/freeUsePlacement.test.ts +++ b/src/workbench/extensions/agent/experiments/freeUsePlacement.test.ts @@ -2,10 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope, nextTick } from 'vue' import type { EffectScope } from 'vue' -import { - authenticatedRemoteConfigState, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useTelemetry } from '@comfyorg/telemetry' import { getDevOverride } from '@/utils/devFeatureFlagOverride' import { getSessionOverride } from '@/utils/sessionFeatureFlagOverride' @@ -19,7 +16,6 @@ import { const distribution = { isCloud: true } -vi.mock(import('@/platform/remoteConfig/remoteConfig')) vi.mock(import('@comfyorg/telemetry')) vi.mock(import('@/utils/devFeatureFlagOverride')) vi.mock(import('@/utils/sessionFeatureFlagOverride')) @@ -38,8 +34,6 @@ describe('useFreeUsePlacement', () => { beforeEach(() => { placementScope = effectScope() distribution.isCloud = true - authenticatedRemoteConfigState.value = 'unloaded' - remoteConfig.value = {} }) afterEach(() => placementScope.stop()) @@ -48,10 +42,10 @@ describe('useFreeUsePlacement', () => { const { variant, reportNotice } = useFreeUsePlacement() expect(variant.value).toBe('control') - remoteConfig.value = { - 'agent-free-use-message-placement': 'above-input' - } - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { 'agent-free-use-message-placement': 'above-input' }, + true + ) await vi.waitFor(() => expect(variant.value).toBe('above-input')) expect(useTelemetry()?.trackAgentFreeUseExposure).toHaveBeenCalledWith({ placement: 'above-input', @@ -91,8 +85,10 @@ describe('useFreeUsePlacement', () => { }) it('reports a served control arm, which is an arm like any other', () => { - remoteConfig.value = { 'agent-free-use-message-placement': 'control' } - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { 'agent-free-use-message-placement': 'control' }, + true + ) const { variant } = useFreeUsePlacement() expect(variant.value).toBe('control') @@ -111,8 +107,7 @@ describe('useFreeUsePlacement', () => { const wireConfig: Record = { [FREE_USE_PLACEMENT_FLAG]: served } - remoteConfig.value = wireConfig - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig(wireConfig, true) const { variant } = useFreeUsePlacement() expect(variant.value).toBe('control') @@ -121,8 +116,10 @@ describe('useFreeUsePlacement', () => { ) it('prefers session and dev overrides for QA', () => { - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { 'agent-free-use-message-placement': 'top-banner' } + useRemoteConfigStore().acceptConfig( + { 'agent-free-use-message-placement': 'top-banner' }, + true + ) vi.mocked(getDevOverride).mockReturnValue('near-composer') vi.mocked(getSessionOverride).mockReturnValue('inside-input') @@ -163,8 +160,10 @@ describe('useFreeUsePlacement', () => { }) it('reports exposure and the impression once per panel open', async () => { - remoteConfig.value = { 'agent-free-use-message-placement': 'top-banner' } - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { 'agent-free-use-message-placement': 'top-banner' }, + true + ) const telemetry = useTelemetry()! vi.mocked(telemetry.trackAgentFreeUseExposure).mockClear() vi.mocked(telemetry.trackAgentFreeUseNotice).mockClear() @@ -196,11 +195,10 @@ describe('useFreeUsePlacement', () => { }) it('attributes a valid arm after a later authenticated config refresh', async () => { - authenticatedRemoteConfigState.value = 'authenticated' const malformedConfig: Record = { [FREE_USE_PLACEMENT_FLAG]: 'unknown' } - remoteConfig.value = malformedConfig + useRemoteConfigStore().acceptConfig(malformedConfig, true) const { variant } = useFreeUsePlacement() const telemetry = useTelemetry()! vi.mocked(telemetry.trackAgentFreeUseExposure).mockClear() @@ -208,15 +206,20 @@ describe('useFreeUsePlacement', () => { expect(variant.value).toBe('control') expect(telemetry.trackAgentFreeUseExposure).not.toHaveBeenCalled() - remoteConfig.value = { [FREE_USE_PLACEMENT_FLAG]: 'inside-input' } + useRemoteConfigStore().acceptConfig( + { [FREE_USE_PLACEMENT_FLAG]: 'inside-input' }, + true + ) await vi.waitFor(() => expect(variant.value).toBe('inside-input')) expect(telemetry.trackAgentFreeUseExposure).toHaveBeenCalledTimes(1) }) it('returns to control when a later config refresh is invalid', async () => { - authenticatedRemoteConfigState.value = 'authenticated' - remoteConfig.value = { [FREE_USE_PLACEMENT_FLAG]: 'inside-input' } + useRemoteConfigStore().acceptConfig( + { [FREE_USE_PLACEMENT_FLAG]: 'inside-input' }, + true + ) const { variant } = useFreeUsePlacement() expect(variant.value).toBe('inside-input') @@ -224,14 +227,16 @@ describe('useFreeUsePlacement', () => { const malformedConfig: Record = { [FREE_USE_PLACEMENT_FLAG]: 'unknown' } - remoteConfig.value = malformedConfig + useRemoteConfigStore().acceptConfig(malformedConfig, true) await vi.waitFor(() => expect(variant.value).toBe('control')) }) it('re-attributes a mounted panel when it reopens', async () => { - remoteConfig.value = { [FREE_USE_PLACEMENT_FLAG]: 'top-banner' } - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { [FREE_USE_PLACEMENT_FLAG]: 'top-banner' }, + true + ) const panelStore = useAgentPanelStore() useFreeUsePlacement() const telemetry = useTelemetry()! @@ -246,8 +251,10 @@ describe('useFreeUsePlacement', () => { }) it('does not deduplicate interactions other than the impression', () => { - remoteConfig.value = { 'agent-free-use-message-placement': 'top-banner' } - authenticatedRemoteConfigState.value = 'authenticated' + useRemoteConfigStore().acceptConfig( + { 'agent-free-use-message-placement': 'top-banner' }, + true + ) const { reportNotice } = useFreeUsePlacement() reportNotice({ action: 'learn_more_clicked', placement: 'top-banner' }) diff --git a/src/workbench/extensions/agent/experiments/freeUsePlacement.ts b/src/workbench/extensions/agent/experiments/freeUsePlacement.ts index 1931ecf8b49..f0943bc9f9f 100644 --- a/src/workbench/extensions/agent/experiments/freeUsePlacement.ts +++ b/src/workbench/extensions/agent/experiments/freeUsePlacement.ts @@ -1,9 +1,6 @@ import { readonly, ref, watch } from 'vue' -import { - isAuthenticatedConfigLoaded, - remoteConfig -} from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { useTelemetry } from '@comfyorg/telemetry' import type { AgentFreeUseNoticeMetadata, @@ -32,6 +29,7 @@ function isFreeUseVariant(value: unknown): value is FreeUseVariant { export function useFreeUsePlacement(isCloudDistribution: boolean) { const panelStore = useAgentPanelStore() + const remoteConfigStore = useRemoteConfigStore() const assigned = ref('control') const sessionOverride = getSessionOverride(FREE_USE_PLACEMENT_FLAG) @@ -42,7 +40,7 @@ export function useFreeUsePlacement(isCloudDistribution: boolean) { const hasQaOverride = override !== undefined function assign(): void { - const served = remoteConfig.value[FREE_USE_PLACEMENT_FLAG] + const served = remoteConfigStore.config[FREE_USE_PLACEMENT_FLAG] if (!isFreeUseVariant(served)) { assigned.value = 'control' return @@ -62,27 +60,30 @@ export function useFreeUsePlacement(isCloudDistribution: boolean) { if (isFreeUseVariant(override)) assigned.value = override } else if (!isCloudDistribution) { assigned.value = LOCAL_FREE_USE_PLACEMENT - } else if (isAuthenticatedConfigLoaded.value) { + } else if (remoteConfigStore.isAuthenticatedConfigLoaded) { assign() } else { - const stop = watch(isAuthenticatedConfigLoaded, (authenticated) => { - if (!authenticated) return - assign() - stop() - }) + const stop = watch( + () => remoteConfigStore.isAuthenticatedConfigLoaded, + (authenticated) => { + if (!authenticated) return + assign() + stop() + } + ) } if (!hasQaOverride && isCloudDistribution) { watch( - () => remoteConfig.value[FREE_USE_PLACEMENT_FLAG], + () => remoteConfigStore.config[FREE_USE_PLACEMENT_FLAG], () => { - if (isAuthenticatedConfigLoaded.value) assign() + if (remoteConfigStore.isAuthenticatedConfigLoaded) assign() } ) watch( () => panelStore.isOpen, (isOpen) => { - if (isOpen && isAuthenticatedConfigLoaded.value) assign() + if (isOpen && remoteConfigStore.isAuthenticatedConfigLoaded) assign() } ) } diff --git a/vitest.setup.ts b/vitest.setup.ts index 5fdff97dd79..b5d8d2027b9 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -7,9 +7,26 @@ import './vitest.mocks.setup' import './vitest.network.setup' import { clearRegisteredLiteGraphTypes } from '@/lib/litegraph/src/litegraphInstance' -import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' +import { useRemoteConfigStore } from '@/platform/remoteConfig/remoteConfigStore' import { StubPath2D } from '@/utils/__tests__/stubPath2D' +function testRuntimeConfig(): Window['__CONFIG__'] { + return { + subscription_required: true, + mixpanel_token: 'test-token', + comfy_api_base_url: 'https://stagingapi.comfy.org', + comfy_platform_base_url: 'https://stagingplatform.comfy.org', + firebase_config: { + apiKey: 'test', + authDomain: 'test.firebaseapp.com', + projectId: 'test', + storageBucket: 'test.appspot.com', + messagingSenderId: '123', + appId: '123' + } + } +} + beforeEach(({ task }) => { for ( let current: typeof task | typeof task.suite = task; @@ -29,7 +46,8 @@ beforeEach(({ task }) => { vi.stubGlobal('Path2D', StubPath2D) const pinia = createTestingPinia({ stubActions: false }) setActivePinia(pinia) - remoteConfigState.value = 'anonymous' + if (globalThis.window) + useRemoteConfigStore(pinia).acceptConfig(testRuntimeConfig(), false) return () => disposePinia(pinia) }) @@ -102,24 +120,6 @@ globalThis.__USE_PROD_CONFIG__ = false globalThis.__DISTRIBUTION__ = 'localhost' globalThis.__IS_NIGHTLY__ = false -// Define runtime config for tests (absent in @vitest-environment node files) -if (globalThis.window) { - window.__CONFIG__ = { - subscription_required: true, - mixpanel_token: 'test-token', - comfy_api_base_url: 'https://stagingapi.comfy.org', - comfy_platform_base_url: 'https://stagingplatform.comfy.org', - firebase_config: { - apiKey: 'test', - authDomain: 'test.firebaseapp.com', - projectId: 'test', - storageBucket: 'test.appspot.com', - messagingSenderId: '123', - appId: '123' - } - } -} - // Mock Worker for extendable-media-recorder globalThis.Worker = vi.fn(function () { return {