From fb92f4db7d7d4d99986552fc748c8ef9f0ff745a Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Sat, 14 Nov 2026 07:39:14 +0000 Subject: [PATCH 1/5] refactor(remoteConfig): own remote config state in a Pinia store Replace the writable module-level refs exported from src/platform/remoteConfig/remoteConfig.ts (remoteConfig, remoteConfigState, authenticatedRemoteConfigState, remoteConfigRevision, remoteConfigErrorStatus, sessionAgentGrant, sessionAgentGrantValidUntil) and useRemoteConfigCache with useRemoteConfigStore. Consumers read state through getters and change it only through named actions (acceptConfig, acceptUnifiedWebSession, beginAuthenticatedLoad, abandonAuthenticatedLoad, failLoad, invalidate). remoteConfigRevision had no readers and is removed. main.ts creates and activates Pinia before bootstrap, because remote config and firebaseIdentity read the store before the app mounts. whenStoresReady therefore gates only on markStoresPending/markStoresReady. useFeatureFlags looks the store up per flag read, so a router built once keeps reading the active test's store. useFreeTierQuota becomes a store behind the same API: as a shared composable it held the first Pinia's store for the whole session. The shared __mocks__/remoteConfig.ts and its self-restoring refs are deleted, which also removes its isAuthenticatedConfigLoaded drift. Tests get a fresh anonymous store from global setup, so per-file restores are gone. Part of FRONT-4032 --- docs/FEATURE_FLAGS.md | 2 +- .../dialog/content/SignInContent.test.ts | 1 - .../dialog/content/SignInContent.vue | 7 +- .../dialog/content/signin/ApiKeyForm.vue | 7 +- src/components/topbar/WorkflowTabs.test.ts | 14 +- src/composables/auth/useTurnstile.test.ts | 24 +- src/composables/useFeatureFlags.test.ts | 292 ++++++++---------- src/composables/useFeatureFlags.ts | 104 +++---- src/config/comfyApi.test.ts | 32 +- src/config/comfyApi.ts | 10 +- src/config/firebase.test.ts | 17 +- src/config/firebase.ts | 13 +- src/config/turnstile.test.ts | 16 +- src/config/turnstile.ts | 6 +- .../widgets/dynamicGroupDiagnostics.test.ts | 12 +- .../dynamicGroupEnforcementBoundary.test.ts | 4 +- src/extensions/core/cloudBadges.ts | 13 +- src/main.ts | 19 +- .../account/auth/WorkspaceAuthGate.test.ts | 14 +- .../account/auth/WorkspaceAuthGate.vue | 12 +- src/platform/auth/firebaseIdentity.test.ts | 39 +-- src/platform/auth/firebaseIdentity.ts | 4 +- .../auth/nonWebClientsStayOnTokens.test.ts | 2 - src/platform/auth/webSessionFlagOff.test.ts | 19 +- src/platform/auth/webSessionFlagOn.test.ts | 31 +- src/platform/billing/billingWeb.test.ts | 18 +- src/platform/billing/billingWeb.ts | 4 +- ...TopUpCreditsDialogContentWorkspace.test.ts | 18 +- .../composables/useBillingContext.test.ts | 67 ++-- .../billing/composables/useBillingContext.ts | 5 +- ...illingDialogs.subscriptionRequired.test.ts | 16 +- .../billing/composables/useBillingDialogs.ts | 6 +- .../billing/hostedBillingRoutes.test.ts | 8 +- .../openHostedBillingTab.handoff.test.ts | 26 +- .../stores/localBillingWebFlagStore.test.ts | 6 +- .../composables/useFreeTierQuota.test.ts | 25 +- .../composables/useFreeTierQuota.ts | 31 +- .../composables/useSubscriptionDialog.test.ts | 19 +- .../subscription/constants/tierPricing.ts | 5 +- .../launchCancellationFlow.test.ts | 15 +- .../subscription/launchCancellationFlow.ts | 5 +- .../subscription/utils/tierBenefits.test.ts | 8 +- .../cloud/onboarding/CloudLoginView.test.ts | 5 +- .../cloud/onboarding/CloudLoginView.vue | 5 +- .../cloud/onboarding/CloudSurveyView.vue | 5 +- .../composables/useFreeTierOnboarding.test.ts | 26 +- .../composables/useFreeTierOnboarding.ts | 5 +- .../survey/ManagerSurveyDialog.test.ts | 55 ++-- .../components/survey/ManagerSurveyDialog.vue | 6 +- .../openOnCloud/desktopWorkflowRelay.test.ts | 15 +- .../openOnCloud/localHandoffProtocol.test.ts | 19 +- .../remoteConfig/__mocks__/remoteConfig.ts | 79 ----- .../remoteConfig/refreshRemoteConfig.test.ts | 201 ++++++------ .../remoteConfig/refreshRemoteConfig.ts | 148 ++------- .../remoteConfig/remoteConfig.test.ts | 20 -- src/platform/remoteConfig/remoteConfig.ts | 87 ------ .../remoteConfig/remoteConfigStore.test.ts | 55 ++++ .../remoteConfig/remoteConfigStore.ts | 156 ++++++++++ .../telemetry/hostTelemetryEnabled.ts | 4 +- .../telemetry/initHostTelemetry.test.ts | 11 +- .../cloud/MixpanelTelemetryProvider.test.ts | 4 - .../cloud/MixpanelTelemetryProvider.ts | 5 +- .../cloud/PostHogTelemetryProvider.test.ts | 52 ++-- .../cloud/PostHogTelemetryProvider.ts | 7 +- .../cloud/SyftTelemetryProvider.test.ts | 110 ++++--- .../providers/cloud/SyftTelemetryProvider.ts | 4 +- .../cloud/storeReadinessGate.test.ts | 8 +- src/platform/telemetry/storeReadiness.test.ts | 26 +- src/platform/telemetry/storeReadiness.ts | 8 +- .../updates/common/releaseService.test.ts | 16 +- .../useRemoteWidget.webSession.test.ts | 7 +- src/router.signedOutReroute.test.ts | 55 ++-- src/router.ts | 5 +- src/stores/authStore.test.ts | 9 +- src/stores/modelStore.test.ts | 25 +- src/utils/sessionFeatureFlagOverride.test.ts | 15 +- .../agent/message/AgentMessage.test.ts | 16 +- .../useAgentDockMount.billingContext.test.ts | 63 ++-- .../experiments/creditUsageSummary.test.ts | 33 +- .../agent/experiments/creditUsageSummary.ts | 13 +- .../experiments/freeUsePlacement.test.ts | 65 ++-- .../agent/experiments/freeUsePlacement.ts | 29 +- vitest.setup.ts | 40 +-- 83 files changed, 1162 insertions(+), 1351 deletions(-) delete mode 100644 src/platform/remoteConfig/__mocks__/remoteConfig.ts delete mode 100644 src/platform/remoteConfig/remoteConfig.test.ts delete mode 100644 src/platform/remoteConfig/remoteConfig.ts create mode 100644 src/platform/remoteConfig/remoteConfigStore.test.ts create mode 100644 src/platform/remoteConfig/remoteConfigStore.ts 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/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 a30f2602773..7e99f4ea2bf 100644 --- a/src/composables/useFeatureFlags.test.ts +++ b/src/composables/useFeatureFlags.test.ts @@ -14,14 +14,7 @@ import { useFeatureFlags } from '@/composables/useFeatureFlags' import * as distributionTypes from '@/platform/distribution/types' -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' @@ -42,9 +35,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( @@ -171,10 +161,6 @@ describe('useFeatureFlags', () => { }) describe('hostedBillingDestination', () => { - afterEach(() => { - remoteConfig.value = {} - }) - it('stays on stripe when the server reports nothing, even with a development URL configured', () => { vi.stubEnv('VITE_BILLING_WEB_URL', 'http://localhost:5174') vi.mocked(api.getServerFeature).mockImplementation( @@ -194,21 +180,23 @@ 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) }) }) describe('billingNewUxEnabled', () => { - afterEach(() => { - remoteConfig.value = {} - }) - it.for([ { label: 'absent', value: undefined, enabled: false }, { label: 'false', value: false, enabled: false }, @@ -217,7 +205,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) @@ -225,7 +213,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) @@ -233,10 +224,6 @@ describe('useFeatureFlags', () => { }) describe('billingSdkTopupEnabled', () => { - afterEach(() => { - remoteConfig.value = {} - }) - it.for([ ['missing', undefined, false], ['malformed', 'true', false], @@ -270,7 +257,7 @@ describe('useFeatureFlags', () => { } ])('reads the $source flag off /features', ({ config }) => { vi.mocked(api.getServerFeature).mockReturnValue(undefined) - remoteConfig.value = config + useRemoteConfigStore().acceptConfig(config, false) const { flags } = useFeatureFlags() @@ -282,16 +269,17 @@ describe('useFeatureFlags', () => { }) it('falls back to the handshake while /features omits the key', () => { - remoteConfig.value = {} + useRemoteConfigStore().acceptConfig({}, false) vi.mocked(api.getServerFeature).mockReturnValue(true) expect(useFeatureFlags().flags.billingSdkTopupEnabled).toBe(true) }) it('refuses a malformed /features value without asking the handshake', () => { - remoteConfig.value = { - billing_sdk_topup_enabled: 'true' - } as unknown as typeof remoteConfig.value + useRemoteConfigStore().acceptConfig( + JSON.parse('{"billing_sdk_topup_enabled":"true"}'), + false + ) vi.mocked(api.getServerFeature).mockReturnValue(true) expect(useFeatureFlags().flags.billingSdkTopupEnabled).toBe(false) @@ -518,7 +506,6 @@ describe('useFeatureFlags', () => { afterEach(() => { vi.mocked(distributionTypes).isNightly = false - remoteConfig.value = {} }) it('defaults on when nightly serves no value for the flag', () => { @@ -531,7 +518,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 ) @@ -559,10 +549,6 @@ describe('useFeatureFlags', () => { ) }) - afterEach(() => { - remoteConfig.value = {} - }) - it('stays off in a production build that serves no value', () => { vi.stubEnv('DEV', false) @@ -582,7 +568,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) } @@ -610,12 +599,11 @@ describe('useFeatureFlags', () => { }) describe('partnerNodeGovernanceEnabled', () => { - afterEach(() => { - remoteConfig.value = {} - }) - it('uses the workspace eligibility flag', () => { - remoteConfig.value = { partner_node_governance_enabled: true } + useRemoteConfigStore().acceptConfig( + { partner_node_governance_enabled: true }, + false + ) const { flags } = useFeatureFlags() @@ -634,12 +622,11 @@ describe('useFeatureFlags', () => { }) describe('deploymentCompatibilityMarksEnabled', () => { - afterEach(() => { - remoteConfig.value = {} - }) - it('turns on from remote config', () => { - remoteConfig.value = { deployment_compatibility_marks_enabled: true } + useRemoteConfigStore().acceptConfig( + { deployment_compatibility_marks_enabled: true }, + false + ) const { flags } = useFeatureFlags() @@ -668,12 +655,11 @@ describe('useFeatureFlags', () => { }) describe('runtimeLibraryModelsEnabled', () => { - afterEach(() => { - remoteConfig.value = {} - }) - it('turns on from remote config', () => { - remoteConfig.value = { runtime_library_models_enabled: true } + useRemoteConfigStore().acceptConfig( + { runtime_library_models_enabled: true }, + false + ) const { flags } = useFeatureFlags() @@ -702,12 +688,11 @@ describe('useFeatureFlags', () => { }) describe('modelUploadFolders', () => { - afterEach(() => { - remoteConfig.value = {} - }) - 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() @@ -784,18 +769,10 @@ describe('useFeatureFlags', () => { describe('auth-gated flags on cloud', () => { beforeEach(() => { vi.mocked(distributionTypes).isCloud = true - remoteConfigState.value = 'unloaded' - remoteConfig.value = {} - cachedBillingControlEnabled.value = undefined - cachedV1PaymentRecovery.value = undefined }) afterEach(() => { vi.mocked(distributionTypes).isCloud = false - remoteConfigState.value = 'unloaded' - remoteConfig.value = {} - cachedBillingControlEnabled.value = undefined - cachedV1PaymentRecovery.value = undefined }) it.for([ @@ -819,8 +796,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) @@ -834,12 +815,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() @@ -848,9 +830,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 @@ -895,12 +875,11 @@ describe('useFeatureFlags', () => { }) describe('supportsModelTypeTags', () => { - afterEach(() => { - remoteConfig.value = {} - }) - it('uses the remote config value', () => { - remoteConfig.value = { supports_model_type_tags: true } + useRemoteConfigStore().acceptConfig( + { supports_model_type_tags: true }, + false + ) const { flags } = useFeatureFlags() @@ -938,18 +917,17 @@ describe('useFeatureFlags', () => { describe('feature flag telemetry', () => { afterEach(() => { vi.mocked(distributionTypes).isCloud = false - remoteConfigState.value = 'unloaded' - remoteConfig.value = {} }) 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, - unified_cloud_auth: false - } + useRemoteConfigStore().acceptConfig( + { + partner_node_governance_enabled: false, + unified_cloud_auth: false + }, + true + ) vi.mocked(api.getServerFeature).mockImplementation( (_path, defaultValue) => defaultValue ) @@ -972,7 +950,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( @@ -994,9 +975,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 ) @@ -1059,7 +1041,7 @@ describe('useFeatureFlags', () => { it('is disabled outside the cloud distribution', () => { vi.mocked(distributionTypes).isCloud = false - remoteConfig.value = { unified_cloud_auth: true } + useRemoteConfigStore().acceptConfig({ unified_cloud_auth: true }, false) expect(useFeatureFlags().flags.unifiedCloudAuthEnabled).toBe(false) }) @@ -1068,7 +1050,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 ) @@ -1076,42 +1058,35 @@ describe('useFeatureFlags', () => { afterEach(() => { vi.mocked(distributionTypes).isCloud = false - authenticatedRemoteConfigState.value = 'unloaded' - remoteConfigState.value = 'unloaded' - remoteConfig.value = {} }) 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 ) @@ -1122,7 +1097,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 @@ -1133,8 +1107,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' @@ -1144,8 +1117,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' @@ -1158,7 +1130,6 @@ describe('useFeatureFlags', () => { }) it('honours the ff: localStorage dev override', () => { - remoteConfigState.value = 'authenticated' localStorage.setItem( `ff:${ServerFeatureFlag.UNIFIED_WEB_SESSION}`, 'true' @@ -1168,7 +1139,6 @@ describe('useFeatureFlags', () => { }) it('honours the ?ff= session override', () => { - remoteConfigState.value = 'authenticated' vi.mocked(getSessionOverride).mockImplementation((flagKey) => flagKey === ServerFeatureFlag.UNIFIED_WEB_SESSION ? true : undefined ) @@ -1178,8 +1148,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) }) @@ -1204,8 +1173,7 @@ describe('useFeatureFlags', () => { ])( 'is independent of unified_cloud_auth: $name', ({ config, expected }) => { - remoteConfigState.value = 'authenticated' - remoteConfig.value = config + useRemoteConfigStore().acceptConfig(config, true) const { flags } = useFeatureFlags() expect({ @@ -1219,9 +1187,6 @@ describe('useFeatureFlags', () => { describe('session override precedence', () => { afterEach(() => { vi.mocked(distributionTypes).isCloud = false - remoteConfigState.value = 'unloaded' - cachedBillingControlEnabled.value = undefined - remoteConfig.value = {} }) it('beats the dev override, remote config and the server value', () => { @@ -1232,7 +1197,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() @@ -1257,7 +1222,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() @@ -1266,8 +1234,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 ) @@ -1279,93 +1248,84 @@ describe('useFeatureFlags', () => { describe('agentInAppExperienceEnabled', () => { beforeEach(() => { vi.mocked(distributionTypes).isCloud = true - remoteConfigState.value = 'unloaded' - remoteConfig.value = {} - sessionAgentGrant.value = undefined - sessionAgentGrantValidUntil.value = undefined }) afterEach(() => { vi.mocked(distributionTypes).isCloud = false - remoteConfigState.value = 'unloaded' - remoteConfig.value = {} - sessionAgentGrant.value = undefined - sessionAgentGrantValidUntil.value = undefined }) 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 45f709649a5..7f156a0f4f8 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -1,16 +1,9 @@ import type { GetFeaturesResponse } from '@comfyorg/ingest-types' import { computed, reactive, readonly, watchEffect } from 'vue' -import type { Ref } from 'vue' import { normalizeHostedBillingDestination } from '@/platform/billing/billingWeb' 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' @@ -68,7 +61,7 @@ function resolveStrictBooleanFlag( function resolveAuthGatedFlag( flagKey: string, remoteConfigValue: boolean | undefined, - cachedValue: Ref + cachedValue: boolean | undefined ): boolean { const sessionOverride = getSessionOverride(flagKey) if (sessionOverride !== undefined) return sessionOverride @@ -77,7 +70,8 @@ function resolveAuthGatedFlag( if (override !== undefined) return override if (!isCloud) return false - if (!isAuthenticatedConfigLoaded.value) return cachedValue.value ?? false + if (!useRemoteConfigStore().isAuthenticatedConfigLoaded) + return cachedValue ?? false return remoteConfigValue ?? api.getServerFeature(flagKey, false) } @@ -92,9 +86,7 @@ function resolveAuthGatedFlag( */ function resolveWhitelistFlag( flagKey: string, - remoteConfigValue: boolean | undefined, - grantedThisSession: Ref, - grantValidUntil: Ref + remoteConfigValue: boolean | undefined ): boolean { const sessionOverride = getSessionOverride(flagKey) if (sessionOverride !== undefined) return sessionOverride @@ -103,10 +95,11 @@ function resolveWhitelistFlag( if (override !== undefined) return override if (!isCloud) return false - if (!isAuthenticatedConfigLoaded.value) + const store = useRemoteConfigStore() + if (!store.isAuthenticatedConfigLoaded) return ( - grantedThisSession.value === true && - (grantValidUntil.value ?? 0) > Date.now() + store.agentGrant === true && + (store.agentGrantValidUntil ?? 0) > Date.now() ) return remoteConfigValue === true @@ -116,11 +109,12 @@ function resolveWhitelistFlag( * Composable for reactive access to server-side feature flags */ export function useFeatureFlags() { + const remoteConfig = () => useRemoteConfigStore().config const hostedBillingDestination = () => normalizeHostedBillingDestination( resolveFlag( ServerFeatureFlag.HOSTED_BILLING_DESTINATION, - remoteConfig.value.hosted_billing_destination, + remoteConfig().hosted_billing_destination, 'stripe' ) ) @@ -146,7 +140,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 ) }, @@ -160,54 +154,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 ) }, @@ -217,7 +211,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 ) }, @@ -227,35 +221,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 ) }, @@ -263,14 +257,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 ) }, @@ -291,7 +285,7 @@ export function useFeatureFlags() { return resolveFlag( ServerFeatureFlag.UNIFIED_CLOUD_AUTH, - remoteConfig.value.unified_cloud_auth, + remoteConfig().unified_cloud_auth, false ) }, @@ -299,12 +293,10 @@ 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 ssoEnabled() { @@ -312,7 +304,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. */ @@ -321,38 +313,38 @@ export function useFeatureFlags() { return resolveStrictBooleanFlag( ServerFeatureFlag.LOCAL_WEB_SSO, - remoteConfig.value.local_web_sso + remoteConfig().local_web_sso ) }, get billingControlEnabled() { return resolveAuthGatedFlag( ServerFeatureFlag.BILLING_CONTROL_ENABLED, - remoteConfig.value.billing_control_enabled, - useRemoteConfigCache().cachedBillingControlEnabled + remoteConfig().billing_control_enabled, + useRemoteConfigStore().cachedBillingControlEnabled ) }, get memberCreditLimitsEnabled() { return resolveStrictBooleanFlag( ServerFeatureFlag.MEMBER_CREDIT_LIMITS_ENABLED, - remoteConfig.value.member_credit_limits_enabled + remoteConfig().member_credit_limits_enabled ) }, get billingNewUxEnabled() { return resolveStrictBooleanFlag( ServerFeatureFlag.BILLING_NEW_UX_ENABLED, - 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 ) }, get billingSdkTopupEnabled() { return resolveStrictBooleanFlag( ServerFeatureFlag.BILLING_SDK_TOPUP_ENABLED, - remoteConfig.value.billing_sdk_topup_enabled + remoteConfig().billing_sdk_topup_enabled ) }, /** The SDK rail runs on the unified session, so it needs both flags. */ @@ -362,7 +354,7 @@ export function useFeatureFlags() { get billingSdkSubscriptionEnabled() { return resolveStrictBooleanFlag( ServerFeatureFlag.BILLING_SDK_SUBSCRIPTION_ENABLED, - remoteConfig.value.billing_sdk_subscription_enabled + remoteConfig().billing_sdk_subscription_enabled ) }, get billingSdkSubscriptionRailEnabled() { @@ -371,40 +363,40 @@ export function useFeatureFlags() { get unifiedBillingSettingsEnabled() { 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( ServerFeatureFlag.V1_PAYMENT_RECOVERY, - remoteConfig.value.v1_payment_recovery, - useRemoteConfigCache().cachedV1PaymentRecovery + remoteConfig().v1_payment_recovery, + useRemoteConfigStore().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 ) }, @@ -414,9 +406,7 @@ export function useFeatureFlags() { get agentInAppExperienceEnabled() { return resolveWhitelistFlag( 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 a2238d9c957..b7fed338a34 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' @@ -605,7 +602,7 @@ describe('WorkspaceAuthGate', () => { }) it('shows a recoverable error when authenticated config is unavailable', async () => { - remoteConfigState.value = 'error' + useRemoteConfigStore().failLoad(true) mountComponent() await flushPromises() @@ -618,8 +615,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 41e0e67510d..510adc4f8d1 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/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 53006873a53..ce4c3e68b8f 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' @@ -340,7 +339,6 @@ describe('clients the web session leaves on tokens', () => { afterEach(() => { hooks?.stop() hooks = undefined - remoteConfig.value = {} }) it.for([...FEATURE_ROWS, ...API_KEY_SESSION_ROWS])( diff --git a/src/platform/auth/webSessionFlagOff.test.ts b/src/platform/auth/webSessionFlagOff.test.ts index 05002823407..cbc560b3733 100644 --- a/src/platform/auth/webSessionFlagOff.test.ts +++ b/src/platform/auth/webSessionFlagOff.test.ts @@ -20,7 +20,6 @@ import { import { installCloudApiAuth } from '@/platform/auth/cloudApiAuthProvider' import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore' 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' @@ -395,7 +394,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' @@ -498,7 +499,6 @@ describe('cloud auth requests with unified_web_session off', () => { afterEach(() => { hooks?.stop() hooks = undefined - remoteConfig.value = {} }) it.for([ @@ -629,7 +629,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 () => { @@ -749,10 +748,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' } @@ -777,10 +772,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({ unified_cloud_auth: false }) await refreshRemoteConfig({ useAuth: false }) @@ -801,10 +792,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 466e542f45e..2c24e2ebaac 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -63,7 +63,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' @@ -402,7 +401,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 () => { @@ -910,7 +908,6 @@ describe('cloud API requests on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -1138,7 +1135,6 @@ describe('workspace API and global settings on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -1306,7 +1302,6 @@ describe('live updates and media on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -1699,7 +1694,6 @@ describe('comfy-api calls on the shared web session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2015,7 +2009,6 @@ describe('billing SDK rails on a tab that arrived by session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2135,7 +2128,6 @@ describe.for([{ unified: false }, { unified: true }])( }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2445,7 +2437,6 @@ describe('a sibling tab under unified_cloud_auth', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2552,7 +2543,6 @@ describe('billing on a tab that arrived by session', () => { }) afterEach(() => { - remoteConfig.value = {} localStorage.clear() }) @@ -2672,10 +2662,6 @@ describe.for([{ unified: false }, { unified: true }])( vi.spyOn(api, 'resetSocket').mockResolvedValue() }) - afterEach(() => { - remoteConfig.value = {} - }) - it('takes its identity from the session', async () => { const { authStore } = await bootSessionOnly() const user = useCurrentUser() @@ -2760,10 +2746,6 @@ describe.for([{ unified: false }, { unified: true }])( 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) @@ -3013,6 +2995,7 @@ describe.for([{ unified: false }, { unified: true }])( markInteractiveSignIn('user-a') const reloaded = createDisposablePinia() setActivePinia(reloaded.pinia) + await refreshRemoteConfig({ useAuth: false }) useAuthStore() identity.resolve(USER_A) @@ -3184,6 +3167,7 @@ describe.for([{ unified: false }, { unified: true }])( const page = createDisposablePinia() pages.push(page) setActivePinia(page.pinia) + await refreshRemoteConfig({ useAuth: false }) useAuthStore() identity.resolve(user) const webSession = useCloudWebSessionStore() @@ -3215,7 +3199,6 @@ describe.for([{ unified: false }, { unified: true }])( 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 () => { @@ -3276,10 +3259,10 @@ describe.for([{ unified: false }, { unified: true }])( it('keeps the marker when a pending sign-in fails to create the session, so the next load retries', async () => { const server = installServer('revoked', { unified_cloud_auth: unified }) - 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') @@ -3301,10 +3284,10 @@ describe.for([{ unified: false }, { unified: true }])( unified_cloud_auth: unified } 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 }) @@ -3351,7 +3334,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 (session: ServerSession, ssoEnabled = true) => { @@ -3680,10 +3662,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 @@ -3843,7 +3821,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 0ffd5db8c19..a12e06c4160 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' } @@ -627,12 +627,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') @@ -1033,7 +1031,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 @@ -1055,7 +1056,6 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(window.location.href).toBe(appUrl) } finally { delete window.__comfyDesktop2 - remoteConfig.value = {} } }) diff --git a/src/platform/billing/composables/useBillingContext.test.ts b/src/platform/billing/composables/useBillingContext.test.ts index 0de31622401..0bec47168c9 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, @@ -48,16 +44,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 } = { @@ -76,18 +66,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( @@ -119,7 +97,6 @@ describe('useBillingContext', () => { currency: 'usd' }) mockIsCloud.value = true - mockFreeTierExecutionPermitted.value = true const workspaceStore = useTeamWorkspaceStore() const refs = storeToRefs(workspaceStore) @@ -138,9 +115,6 @@ describe('useBillingContext', () => { vi.mocked(useWorkspaceBillingStateStore().updateSummary).mockImplementation( () => {} ) - remoteConfig.value = {} - remoteConfigState.value = 'unloaded' - authenticatedRemoteConfigState.value = 'unloaded' mockIsPersonal.value = true mockPlans.value = [] const subscription = useSubscription() @@ -178,19 +152,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 = { @@ -198,15 +175,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 = { @@ -214,15 +192,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 = { @@ -230,15 +209,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 = { @@ -246,7 +223,6 @@ describe('useBillingContext', () => { subscription_tier: 'FREE' } mockIsCloud.value = true - mockFreeTierExecutionPermitted.value = false const context = useBillingContext() await context.initialize() expect(context.canRunWorkflows.value).toBe(true) @@ -317,8 +293,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 d2502092a8f..1b46c999706 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 8173ee1604a..1ac91a22529 100644 --- a/src/platform/billing/stores/localBillingWebFlagStore.test.ts +++ b/src/platform/billing/stores/localBillingWebFlagStore.test.ts @@ -12,7 +12,7 @@ import { stopDesktopHostSession } from '@/platform/auth/desktopHost/desktopHostSession' import { useLocalBillingWebFlagStore } 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' @@ -103,7 +103,7 @@ describe('useLocalBillingWebFlagStore', () => { }) it('exposes only local_billing_web 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, @@ -114,7 +114,7 @@ describe('useLocalBillingWebFlagStore', () => { const { store } = await signInAndRead() expect(store.enabled).toBe(true) - expect(remoteConfig.value).toEqual(localConfig) + expect(useRemoteConfigStore().config).toEqual(localConfig) }) it.for([ 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 9f58bc15cbb..837b62ecc10 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/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..c320c4c6140 100644 --- a/src/platform/remoteConfig/refreshRemoteConfig.test.ts +++ b/src/platform/remoteConfig/refreshRemoteConfig.test.ts @@ -8,22 +8,10 @@ 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')) -const { cachedBillingControlEnabled, cachedV1PaymentRecovery } = - useRemoteConfigCache() - describe('refreshRemoteConfig', () => { const mockConfig = { feature1: true, feature2: 'value' } @@ -59,41 +47,37 @@ describe('refreshRemoteConfig', () => { 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 +106,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 +120,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 +129,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 +148,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 +187,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 +204,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 +238,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 +258,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 +277,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,8 +312,8 @@ 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('does not erase authenticated config or its grant on an anonymous 401', async () => { @@ -337,22 +321,19 @@ describe('refreshRemoteConfig', () => { 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() }) }) @@ -373,7 +354,7 @@ describe('refreshRemoteConfig', () => { await refreshRemoteConfig({ useAuth: false }) - expect(remoteConfig.value).toEqual({}) + expect(useRemoteConfigStore().config).toEqual({}) expect(window.__CONFIG__).toEqual({}) }) }) @@ -384,17 +365,13 @@ describe('refreshRemoteConfig', () => { 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 +380,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 +396,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 +426,7 @@ describe('refreshRemoteConfig', () => { await refreshRemoteConfig() - expect(remoteConfig.value).toEqual({}) + expect(useRemoteConfigStore().config).toEqual({}) expect(window.__CONFIG__).toEqual({}) }) @@ -454,29 +435,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 +477,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 +496,7 @@ describe('refreshRemoteConfig', () => { await loading expect(global.fetch).toHaveBeenCalledTimes(2) - expect(remoteConfig.value).toEqual(serverConfig) + expect(useRemoteConfigStore().config).toEqual(serverConfig) vi.useRealTimers() }) @@ -571,7 +552,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..0bdfaee2dd9 100644 --- a/src/platform/telemetry/storeReadiness.ts +++ b/src/platform/telemetry/storeReadiness.ts @@ -1,10 +1,8 @@ -import { getActivePinia } from 'pinia' - -/** Gates store-backed telemetry setup until `main.ts` installs Pinia. */ +/** Gates store-backed telemetry setup until `main.ts` installs Pinia into the app. */ 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 +19,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..86c0520c2d1 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' @@ -210,6 +210,7 @@ function installCloudAuthGuards(router: Router): void { watchedAccounts.add(authStore) const apiKeyAuthStore = useApiKeyAuthStore() const webSession = useCloudWebSessionStore() + const remoteConfigStore = useRemoteConfigStore() const account = computed(() => { if (authStore.isAuthenticated || apiKeyAuthStore.isAuthenticated) return 'signed_in' @@ -224,7 +225,7 @@ function installCloudAuthGuards(router: Router): void { [ account, () => flags.signedOutRerouteEnabled, - remoteConfigState, + () => remoteConfigStore.loadState, () => authStore.currentUser?.uid ], ([state, enabled, configState, uid]) => { diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index e97ee869dd3..ecf788f38cb 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -22,11 +22,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' @@ -1446,7 +1443,7 @@ describe('useAuthStore', () => { authStateCallback(accountB) expect(accountASignal?.aborted).toBe(true) - expect(remoteConfigState.value).toBe('unloaded') + expect(useRemoteConfigStore().loadState).toBe('unloaded') await refreshRemoteConfig() resolveAccountA?.( @@ -1456,7 +1453,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 c679c4bf146..626713aad7c 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 8492e0a8b18..77379f4f41f 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' @@ -42,29 +38,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 @@ -78,18 +68,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( @@ -126,7 +104,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) @@ -141,9 +118,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 { From 3965cd3ea192b8240a399772f4e598feb8f5820a Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Sat, 14 Nov 2026 08:02:55 +0000 Subject: [PATCH 2/5] test: drive free tier quota through remote config instead of mocking its store useFreeTierQuota is now backed by a Pinia store, so mocking its module violates the global-Pinia lint rule. Tests serve free_tier_balance via the remote config store instead. Also drop the JSDoc on private store-readiness state. --- .../dialogs/settings/BillingTab.test.ts | 9 ------ .../dialogs/settings/BillingTabLegacy.test.ts | 9 ------ .../components/FreeTierQuota.test.ts | 29 ++++++++++--------- src/platform/telemetry/storeReadiness.ts | 1 - 4 files changed, 15 insertions(+), 33 deletions(-) diff --git a/src/platform/account/components/dialogs/settings/BillingTab.test.ts b/src/platform/account/components/dialogs/settings/BillingTab.test.ts index 2d6ed0e8999..88e7168def5 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' @@ -64,7 +63,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( @@ -275,13 +273,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 2d2fca9fe96..d925650eaa5 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' @@ -52,7 +51,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( @@ -236,13 +234,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/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/telemetry/storeReadiness.ts b/src/platform/telemetry/storeReadiness.ts index 0bdfaee2dd9..f56e76963b1 100644 --- a/src/platform/telemetry/storeReadiness.ts +++ b/src/platform/telemetry/storeReadiness.ts @@ -1,4 +1,3 @@ -/** Gates store-backed telemetry setup until `main.ts` installs Pinia into the app. */ let storesReady: Promise = Promise.resolve() let resolveStoresReady: (() => void) | undefined From 1be58cb2b5b8882d06f3fac46c23ae9d6bff7d8f Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Sat, 14 Nov 2026 08:23:06 +0000 Subject: [PATCH 3/5] fix: bind feature flags to the Pinia that owns them useFeatureFlags looked up the remote config store on every read, so a watcher created under one Pinia resolved whichever Pinia was active when it re-ran. It now captures the store when a Pinia is active and only falls back to a lazy lookup when called before one exists, such as the module-scope router. The router's per-account reroute watcher takes flags bound to that account's Pinia. openWorkflowOnCloud.test.ts reads the cloud origin lazily instead of at module scope. --- src/composables/useFeatureFlags.ts | 20 +++++++++++++------ .../openOnCloud/openWorkflowOnCloud.test.ts | 10 +++++----- src/router.ts | 3 ++- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index 62d26435475..6c7f3d8af7f 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -1,4 +1,5 @@ import type { GetFeaturesResponse } from '@comfyorg/ingest-types' +import { getActivePinia } from 'pinia' import { computed, reactive, readonly, watchEffect } from 'vue' import { normalizeHostedBillingDestination } from '@/platform/billing/billingWeb' @@ -53,6 +54,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 @@ -60,6 +63,7 @@ function resolveStrictBooleanFlag( * the wrong backend before authenticated config confirms the flag. */ function resolveAuthGatedFlag( + store: RemoteConfigStore, flagKey: string, remoteConfigValue: boolean | undefined, cachedValue: boolean | undefined @@ -71,8 +75,7 @@ function resolveAuthGatedFlag( if (override !== undefined) return override if (!isCloud) return false - if (!useRemoteConfigStore().isAuthenticatedConfigLoaded) - return cachedValue ?? false + if (!store.isAuthenticatedConfigLoaded) return cachedValue ?? false return remoteConfigValue ?? api.getServerFeature(flagKey, false) } @@ -86,6 +89,7 @@ function resolveAuthGatedFlag( * same account (PM-1707). */ function resolveWhitelistFlag( + store: RemoteConfigStore, flagKey: string, remoteConfigValue: boolean | undefined ): boolean { @@ -96,7 +100,6 @@ function resolveWhitelistFlag( if (override !== undefined) return override if (!isCloud) return false - const store = useRemoteConfigStore() if (!store.isAuthenticatedConfigLoaded) return ( store.agentGrant === true && @@ -110,7 +113,9 @@ function resolveWhitelistFlag( * Composable for reactive access to server-side feature flags */ export function useFeatureFlags() { - const remoteConfig = () => useRemoteConfigStore().config + const ownerStore = getActivePinia() ? useRemoteConfigStore() : undefined + const remoteConfigStore = () => ownerStore ?? useRemoteConfigStore() + const remoteConfig = () => remoteConfigStore().config const hostedBillingDestination = () => normalizeHostedBillingDestination( resolveFlag( @@ -326,9 +331,10 @@ export function useFeatureFlags() { }, get billingControlEnabled() { return resolveAuthGatedFlag( + remoteConfigStore(), ServerFeatureFlag.BILLING_CONTROL_ENABLED, remoteConfig().billing_control_enabled, - useRemoteConfigStore().cachedBillingControlEnabled + remoteConfigStore().cachedBillingControlEnabled ) }, get memberCreditLimitsEnabled() { @@ -390,9 +396,10 @@ export function useFeatureFlags() { }, get v1PaymentRecovery() { return resolveAuthGatedFlag( + remoteConfigStore(), ServerFeatureFlag.V1_PAYMENT_RECOVERY, remoteConfig().v1_payment_recovery, - useRemoteConfigStore().cachedV1PaymentRecovery + remoteConfigStore().cachedV1PaymentRecovery ) }, get signupTurnstileMode() { @@ -414,6 +421,7 @@ export function useFeatureFlags() { }, get agentInAppExperienceEnabled() { return resolveWhitelistFlag( + remoteConfigStore(), ServerFeatureFlag.AGENT_IN_APP_EXPERIENCE, remoteConfig()['agent-in-app-experience'] ) 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/router.ts b/src/router.ts index 86c0520c2d1..5a1aff01c04 100644 --- a/src/router.ts +++ b/src/router.ts @@ -211,6 +211,7 @@ function installCloudAuthGuards(router: Router): void { const apiKeyAuthStore = useApiKeyAuthStore() const webSession = useCloudWebSessionStore() const remoteConfigStore = useRemoteConfigStore() + const { flags: accountFlags } = useFeatureFlags() const account = computed(() => { if (authStore.isAuthenticated || apiKeyAuthStore.isAuthenticated) return 'signed_in' @@ -224,7 +225,7 @@ function installCloudAuthGuards(router: Router): void { watch( [ account, - () => flags.signedOutRerouteEnabled, + () => accountFlags.signedOutRerouteEnabled, () => remoteConfigStore.loadState, () => authStore.currentUser?.uid ], From c68ad10e680a679929c7b4fc0e1c8799a83b298d Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Sun, 15 Nov 2026 10:27:01 +0000 Subject: [PATCH 4/5] test: cover remote config timeout, cancellation, and superseded reads Pins the five-second /features timeout, cancellation from an already aborted or mid-flight caller signal, invalidation cancelling an in-flight read without reporting failure, and stale bodies and web-session answers dropped after invalidation. --- .../remoteConfig/refreshRemoteConfig.test.ts | 165 ++++++++++++++++++ 1 file changed, 165 insertions(+) diff --git a/src/platform/remoteConfig/refreshRemoteConfig.test.ts b/src/platform/remoteConfig/refreshRemoteConfig.test.ts index c320c4c6140..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 { @@ -11,6 +14,33 @@ import { 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 } +} + +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' } @@ -44,6 +74,7 @@ describe('refreshRemoteConfig', () => { } beforeEach(() => { + distribution.isCloud = false vi.mocked(api.apiURL).mockImplementation( (route: string) => `/ComfyUI/api${route}` ) @@ -316,6 +347,31 @@ describe('refreshRemoteConfig', () => { 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, @@ -347,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') @@ -359,6 +436,94 @@ describe('refreshRemoteConfig', () => { }) }) + 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')) From 9356fcbe0e9fcb13cdf518e21682f076f7463ec6 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 17 Nov 2026 05:21:10 +0000 Subject: [PATCH 5/5] test: mount GlobalDialog with the active Pinia Amp-Thread-ID: https://ampcode.com/threads/T-f18eb2a2-577f-42a0-ad96-90d1efa358af --- src/components/dialog/GlobalDialog.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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] } }) }