Line data Source code
1 : import { computed, onScopeDispose, ref, watch } from 'vue'
2 : import {
3 : createSharedComposable,
4 : defaultDocument,
5 : defaultWindow,
6 : useEventListener
7 : } from '@vueuse/core'
8 :
9 : import { useCurrentUser } from '@/composables/auth/useCurrentUser'
10 : import { useAuthActions } from '@/composables/auth/useAuthActions'
11 : import { useErrorHandling } from '@/composables/useErrorHandling'
12 : import { t } from '@/i18n'
13 : import { isCloud } from '@/platform/distribution/types'
14 : import { useTelemetry } from '@comfyorg/telemetry'
15 : import { reportError as reportTelemetryError } from '@comfyorg/telemetry/reportError'
16 : import type { SubscriptionSuccessMetadata } from '@comfyorg/telemetry/types'
17 : import type { BillingStatusResponse } from '@comfyorg/billing-core'
18 : import { billingApi } from '@/platform/billing/api/billingApi'
19 : import { WorkspaceApiError } from '@/platform/remote/ingest/ingestApiError'
20 : import { readOnRail } from '@/platform/billing/composables/readOnRail'
21 : import { useBillingReadRail } from '@/platform/billing/composables/useBillingReadRail'
22 : import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory'
23 : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
24 : import { platformLink } from '@/platform/workspace/utils/platformLink'
25 : import { AuthStoreError, useAuthStore } from '@/stores/authStore'
26 : import { toTierKey } from '@/platform/billing/subscription/constants/tierPricing'
27 : import {
28 : PENDING_SUBSCRIPTION_CHECKOUT_EVENT,
29 : PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY,
30 : clearPendingSubscriptionCheckoutAttempt,
31 : consumePendingSubscriptionCheckoutSuccess,
32 : getPendingSubscriptionCheckoutAttempt,
33 : claimPendingCheckoutTerminal,
34 : getPendingCheckoutTerminal,
35 : hasPendingSubscriptionCheckoutAttempt
36 : } from '@/platform/billing/subscription/utils/subscriptionCheckoutTracker'
37 : import type { BillingStatusReadOptions } from '@/platform/billing/composables/types'
38 :
39 2355 : const PENDING_SUBSCRIPTION_CHECKOUT_RETRY_DELAYS_MS = [3000, 10000, 30000]
40 :
41 2355 : const PENDING_CHECKOUT_COMPLETION_DEADLINE_MS = 10 * 60 * 1000
42 2355 : const PENDING_CHECKOUT_DEADLINE_REFRESH_TIMEOUT_MS = 10_000
43 2355 : const PENDING_CHECKOUT_DEADLINE_RETRY_DELAYS_MS = [
44 : 1000,
45 : 5000,
46 : 30000,
47 : 2 * 60 * 1000,
48 : 5 * 60 * 1000,
49 : 10 * 60 * 1000
50 : ] as const
51 :
52 : type CheckoutScopeOwnership = 'unresolved' | 'matched' | 'mismatched'
53 :
54 0 : function compareCheckoutScopeStamp(
55 : stampedId: string | null | undefined,
56 : currentId: string | null | undefined
57 : ): CheckoutScopeOwnership {
58 0 : if (typeof stampedId !== 'string') return 'matched'
59 0 : if (!currentId) return 'unresolved'
60 0 : return stampedId === currentId ? 'matched' : 'mismatched'
61 : }
62 :
63 0 : async function withTimeout<T>(promise: Promise<T>, timeoutMs: number) {
64 0 : let timeoutId: ReturnType<typeof setTimeout> | undefined
65 0 : try {
66 0 : return await Promise.race([
67 : promise,
68 : new Promise<never>((_, reject) => {
69 0 : timeoutId = setTimeout(
70 : () => reject(new Error('Billing status deadline refresh timed out')),
71 : timeoutMs
72 : )
73 : })
74 : ])
75 : } finally {
76 0 : clearTimeout(timeoutId)
77 : }
78 : }
79 :
80 0 : function useSubscriptionInternal() {
81 0 : const subscriptionStatus = ref<BillingStatusResponse | null>(null)
82 0 : const telemetry = useTelemetry()
83 0 : const isInitialized = ref(false)
84 :
85 0 : const canAccessSubscriptionFeatures = computed(() => {
86 0 : if (!isCloud || !window.__CONFIG__?.subscription_required) return true
87 :
88 : return subscriptionStatus.value?.is_active ?? false
89 : })
90 0 : const { reportError } = useAuthActions()
91 :
92 0 : const authStore = useAuthStore()
93 0 : const workspaceStore = useWorkspaceIdentity()
94 0 : const { wrapWithErrorHandlingAsync } = useErrorHandling()
95 :
96 0 : const { isLoggedIn } = useCurrentUser()
97 :
98 : // Web-session billing reads need the workspace the gate selects after sign-in.
99 0 : const awaitingSessionWorkspace = computed(
100 : () => !!authStore.sessionUser && !workspaceStore.activeWorkspaceId
101 : )
102 :
103 0 : const isCancelled = computed(() => {
104 0 : return !!subscriptionStatus.value?.cancel_at
105 : })
106 :
107 0 : const formattedRenewalDate = computed(() => {
108 0 : if (!subscriptionStatus.value?.renewal_date) return ''
109 :
110 : const renewalDate = new Date(subscriptionStatus.value.renewal_date)
111 :
112 0 : return renewalDate.toLocaleDateString('en-US', {
113 : month: 'short',
114 : day: 'numeric',
115 : year: 'numeric'
116 : })
117 : })
118 :
119 0 : const formattedEndDate = computed(() => {
120 0 : if (!subscriptionStatus.value?.cancel_at) return ''
121 :
122 : const endDate = new Date(subscriptionStatus.value.cancel_at)
123 :
124 0 : return endDate.toLocaleDateString('en-US', {
125 : month: 'short',
126 : day: 'numeric',
127 : year: 'numeric'
128 : })
129 : })
130 :
131 0 : const subscriptionTier = computed(
132 : () => subscriptionStatus.value?.subscription_tier ?? null
133 : )
134 :
135 0 : const isFreeTier = computed(() => subscriptionTier.value === 'FREE')
136 :
137 0 : const subscriptionDuration = computed(
138 : () => subscriptionStatus.value?.subscription_duration ?? null
139 : )
140 :
141 0 : const isYearlySubscription = computed(
142 : () => subscriptionDuration.value === 'ANNUAL'
143 : )
144 :
145 0 : const subscriptionTierName = computed(() => {
146 0 : const tier = subscriptionTier.value
147 0 : if (!tier) return ''
148 : // TEAM and ENTERPRISE map to no catalog key (see toTierKey); reuse their
149 : // existing copy instead of mislabeling them as Standard.
150 0 : if (tier === 'TEAM') return t('subscription.teamPlanName')
151 0 : if (tier === 'ENTERPRISE') return t('subscription.tiers.enterprise.name')
152 0 : const key = toTierKey(tier)
153 0 : const baseName = key
154 : ? t(`subscription.tiers.${key}.name`)
155 : : t('subscription.unknownTierName')
156 0 : return isYearlySubscription.value
157 : ? t('subscription.tierNameYearly', { name: baseName })
158 : : baseName
159 : })
160 :
161 : interface PendingCheckoutSchedule {
162 : timeoutId: number | null
163 : retryRung: number
164 : deadlineRung: number
165 : }
166 :
167 0 : const IDLE_PENDING_CHECKOUT_SCHEDULE: PendingCheckoutSchedule = {
168 : timeoutId: null,
169 : retryRung: 0,
170 : deadlineRung: 0
171 : }
172 :
173 0 : let pendingCheckoutSchedule = IDLE_PENDING_CHECKOUT_SCHEDULE
174 0 : let activePendingCheckoutRead: {
175 : attemptId: string
176 : promise: Promise<BillingStatusResponse | null>
177 : } | null = null
178 0 : let lastPendingCheckoutStatus: BillingStatusResponse | null = null
179 0 : let isDisposed = false
180 :
181 0 : const stopPendingCheckoutRecovery = () => {
182 0 : if (pendingCheckoutSchedule.timeoutId !== null && defaultWindow) {
183 0 : defaultWindow.clearTimeout(pendingCheckoutSchedule.timeoutId)
184 : }
185 0 : pendingCheckoutSchedule = IDLE_PENDING_CHECKOUT_SCHEDULE
186 : }
187 :
188 0 : const armPendingCheckoutTimer = (delayMs: number, onFire: () => void) => {
189 0 : if (!defaultWindow) return
190 0 : const timeoutId = defaultWindow.setTimeout(() => {
191 0 : pendingCheckoutSchedule = { ...pendingCheckoutSchedule, timeoutId: null }
192 0 : onFire()
193 : }, delayMs)
194 0 : pendingCheckoutSchedule = { ...pendingCheckoutSchedule, timeoutId }
195 : }
196 :
197 0 : onScopeDispose(() => {
198 0 : isDisposed = true
199 0 : stopPendingCheckoutRecovery()
200 : })
201 :
202 : /**
203 : * The retry ladder is exhausted by the time the deadline matters, so without
204 : * this the report would wait on the next `pageshow`/`visibilitychange` and
205 : * never fire for a user who simply leaves the tab open.
206 : */
207 0 : const armMissingCheckoutCompletionWakeUp = (remainingMs: number) => {
208 0 : if (isDisposed || pendingCheckoutSchedule.timeoutId !== null) return
209 :
210 0 : armPendingCheckoutTimer(Math.max(remainingMs, 0), () => {
211 0 : void recoverPendingSubscriptionCheckout('deadline')
212 : })
213 : }
214 :
215 0 : const getCurrentPendingCheckoutAttempt = (attemptId: string) => {
216 0 : const attempt = getPendingSubscriptionCheckoutAttempt()
217 0 : return attempt?.attempt_id === attemptId ? attempt : null
218 : }
219 :
220 0 : const getReportableMissingCheckout = (attemptId: string) => {
221 0 : const attempt = getCurrentPendingCheckoutAttempt(attemptId)
222 0 : if (!attempt || getPendingCheckoutTerminal(attempt.attempt_id)) {
223 0 : return null
224 : }
225 :
226 0 : const attemptAgeMs = Date.now() - attempt.started_at_ms
227 0 : if (attemptAgeMs < PENDING_CHECKOUT_COMPLETION_DEADLINE_MS) {
228 0 : armMissingCheckoutCompletionWakeUp(
229 : PENDING_CHECKOUT_COMPLETION_DEADLINE_MS - attemptAgeMs
230 : )
231 0 : return null
232 : }
233 :
234 : // Any authoritative snapshot that did not consume the attempt proves its
235 : // target tier and cycle were not observed, including plan-change checkouts
236 : // whose previous subscription remains active.
237 0 : if (lastPendingCheckoutStatus === null) return null
238 :
239 0 : return { attempt, attemptAgeMs }
240 : }
241 :
242 0 : const reportMissingCheckoutCompletion = (attemptId: string): boolean => {
243 0 : const reportable = getReportableMissingCheckout(attemptId)
244 0 : if (!reportable) return false
245 0 : const { attemptAgeMs } = reportable
246 0 : const attempt = claimPendingCheckoutTerminal(
247 : attemptId,
248 : 'completion_missing'
249 : )
250 0 : if (!attempt) return false
251 :
252 0 : reportTelemetryError(
253 : new Error('Pending subscription checkout recovery timed out'),
254 : {
255 : errorType: 'failure_completing_cloud_checkout',
256 : surface: 'billing',
257 : context: {
258 : checkout_attempt_id: attempt.attempt_id,
259 : checkout_type: attempt.checkout_type,
260 : attempt_age_ms: attemptAgeMs,
261 : tier: attempt.tier,
262 : cycle: attempt.cycle,
263 : ...(attempt.operation
264 : ? { checkout_operation: attempt.operation }
265 : : {})
266 : },
267 : level: 'warning'
268 : }
269 : )
270 0 : telemetry?.trackBillingEvent({
271 : operation: 'subscription_checkout',
272 : stage: 'timeout',
273 : outcome: 'failure',
274 : checkout_attempt_id: attempt.attempt_id,
275 : failure_category: 'poll_timeout',
276 : tier: attempt.tier,
277 : cycle: attempt.cycle,
278 : checkout_type: attempt.checkout_type,
279 : duration_ms: attemptAgeMs
280 : })
281 0 : if (attempt.operation === 'resubscribe') {
282 0 : telemetry?.trackBillingEvent({
283 : operation: 'resubscribe',
284 : stage: 'failed',
285 : outcome: 'failure',
286 : source: attempt.resubscribe_source ?? 'settings_billing_panel',
287 : checkout_attempt_id: attempt.attempt_id,
288 : failure_category: 'poll_timeout',
289 : ...(attempt.payment_intent_source
290 : ? { payment_intent_source: attempt.payment_intent_source }
291 : : {})
292 : })
293 : }
294 0 : return true
295 : }
296 :
297 0 : const canSchedulePendingCheckoutRecovery = (
298 : attempt: ReturnType<typeof getPendingSubscriptionCheckoutAttempt>
299 : ) =>
300 : !(
301 : isDisposed ||
302 : !defaultWindow ||
303 : pendingCheckoutSchedule.timeoutId !== null ||
304 : !isLoggedIn.value ||
305 : !attempt
306 : )
307 :
308 0 : const schedulePendingCheckoutRecovery = () => {
309 0 : const attempt = getPendingSubscriptionCheckoutAttempt()
310 0 : if (!canSchedulePendingCheckoutRecovery(attempt) || !attempt) return
311 :
312 0 : const nextDelay = getPendingCheckoutRetryDelay(
313 : pendingCheckoutSchedule.retryRung
314 : )
315 :
316 0 : if (nextDelay === undefined) {
317 0 : const isPastDeadline =
318 : Date.now() - attempt.started_at_ms >=
319 : PENDING_CHECKOUT_COMPLETION_DEADLINE_MS
320 0 : if (
321 : !reportMissingCheckoutCompletion(attempt.attempt_id) &&
322 : isPastDeadline
323 : ) {
324 0 : rearmBoundedDeadlineWakeUp()
325 : }
326 0 : return
327 : }
328 :
329 0 : armPendingCheckoutTimer(nextDelay, () => {
330 0 : pendingCheckoutSchedule = {
331 : ...pendingCheckoutSchedule,
332 : retryRung: pendingCheckoutSchedule.retryRung + 1
333 : }
334 0 : void recoverPendingSubscriptionCheckout('retry')
335 : })
336 : }
337 :
338 0 : const getPendingAttemptOwnership = (): CheckoutScopeOwnership => {
339 0 : const attempt = getPendingSubscriptionCheckoutAttempt()
340 0 : if (!attempt) return 'matched'
341 0 : const owner = compareCheckoutScopeStamp(attempt.owner_id, authStore.userId)
342 0 : const workspace = compareCheckoutScopeStamp(
343 : attempt.workspace_id,
344 : workspaceStore.activeWorkspaceId
345 : )
346 0 : if (owner === 'mismatched' || workspace === 'mismatched')
347 0 : return 'mismatched'
348 0 : if (owner === 'unresolved' || workspace === 'unresolved')
349 0 : return 'unresolved'
350 0 : return 'matched'
351 : }
352 :
353 : const trackSubscriptionCheckoutSuccess = (
354 : metadata: SubscriptionSuccessMetadata,
355 : startReported: boolean,
356 : startedAtMs: number
357 : ) => {
358 : if (!startReported && metadata.recovery_outcome !== 'late_success') return
359 : telemetry?.trackBillingEvent({
360 : operation: 'subscription_checkout',
361 : stage: 'succeeded',
362 : outcome: 'success',
363 : checkout_attempt_id: metadata.checkout_attempt_id,
364 : tier: metadata.tier,
365 : cycle: metadata.cycle,
366 : checkout_type: metadata.checkout_type,
367 : payment_intent_source: metadata.payment_intent_source,
368 : recovery_outcome: metadata.recovery_outcome,
369 : duration_ms: Date.now() - startedAtMs
370 : })
371 : }
372 :
373 : const trackResubscribeSuccess = (metadata: SubscriptionSuccessMetadata) => {
374 : if (metadata.operation !== 'resubscribe') return
375 : telemetry?.trackBillingEvent({
376 : operation: 'resubscribe',
377 : stage: 'succeeded',
378 : outcome: 'success',
379 : source: metadata.resubscribe_source ?? 'settings_billing_panel',
380 : checkout_attempt_id: metadata.checkout_attempt_id,
381 : payment_intent_source: metadata.payment_intent_source,
382 : recovery_outcome: metadata.recovery_outcome
383 : })
384 : }
385 :
386 : const syncPendingSubscriptionSuccess = (
387 : statusData: BillingStatusResponse
388 : ) => {
389 : const ownership = getPendingAttemptOwnership()
390 : if (ownership === 'mismatched') {
391 : stopPendingCheckoutRecovery()
392 : return
393 : }
394 : if (ownership === 'unresolved') return
395 : const consumed = consumePendingSubscriptionCheckoutSuccess(statusData)
396 :
397 : if (!consumed) {
398 : if (hasPendingSubscriptionCheckoutAttempt()) {
399 : schedulePendingCheckoutRecovery()
400 : } else {
401 : stopPendingCheckoutRecovery()
402 : }
403 : return
404 : }
405 :
406 : const {
407 : start_reported: startReported,
408 : started_at_ms: startedAtMs,
409 : ...metadata
410 : } = consumed
411 :
412 : telemetry?.trackMonthlySubscriptionSucceeded({
413 : ...(authStore.userId ? { user_id: authStore.userId } : {}),
414 : ...metadata
415 : })
416 :
417 : trackSubscriptionCheckoutSuccess(
418 : metadata,
419 : startReported === true,
420 : startedAtMs
421 : )
422 :
423 : // The recovery flow is shared with plain (non-resubscribe) legacy subscribes,
424 : // which all funnel through the same subscribeDirect(). Only emit the canonical
425 : // resubscribe terminal when the attempt that just resolved was itself tagged
426 : // as a resubscribe at click time — otherwise a plain new subscribe would be
427 : // mislabeled as a resubscribe success. Without this, the legacy rail's
428 : // `billing.resubscribe.started` (emitted at checkout-tab-open) never gets a
429 : // matching terminal, so resubscribe conversion permanently reads ~0%.
430 : trackResubscribeSuccess(metadata)
431 :
432 : stopPendingCheckoutRecovery()
433 : }
434 :
435 0 : const fetchStatus = wrapWithErrorHandlingAsync(
436 : fetchSubscriptionStatus,
437 : reportError
438 : )
439 :
440 : /**
441 : * Whether cloud subscription mode is enabled (cloud distribution with subscription_required config).
442 : */
443 0 : const isSubscriptionEnabled = (): boolean =>
444 : Boolean(isCloud && window.__CONFIG__?.subscription_required)
445 :
446 0 : const handleViewUsageHistory = () => {
447 0 : window.open(platformLink('/profile/usage'), '_blank')
448 : }
449 :
450 0 : const handleLearnMore = () => {
451 0 : window.open('https://docs.comfy.org', '_blank')
452 : }
453 :
454 : type PendingCheckoutRecoverySource =
455 : | 'bootstrap'
456 : | 'pageshow'
457 : | 'visibilitychange'
458 : | 'retry'
459 : | 'deadline'
460 :
461 0 : const canRecoverPendingCheckout = () =>
462 : isCloud &&
463 : isLoggedIn.value &&
464 : !awaitingSessionWorkspace.value &&
465 : hasOwnedPendingCheckoutAttempt()
466 :
467 : const hasOwnedPendingCheckoutAttempt = () => {
468 : const attempt = getPendingSubscriptionCheckoutAttempt()
469 : if (!attempt) return false
470 : return getPendingAttemptOwnership() === 'matched'
471 : }
472 :
473 0 : const handlePendingCheckoutRecoveryError = (
474 : source: PendingCheckoutRecoverySource,
475 : attemptId: string,
476 : error: unknown
477 : ) => {
478 0 : console.error(
479 : `[Subscription] Failed to recover pending checkout on ${source}:`,
480 : error
481 : )
482 0 : const attempt = getCurrentPendingCheckoutAttempt(attemptId)
483 0 : if (!attempt) return
484 0 : const isPastDeadline =
485 : Date.now() - attempt.started_at_ms >=
486 : PENDING_CHECKOUT_COMPLETION_DEADLINE_MS
487 0 : if (source === 'deadline' || isPastDeadline) {
488 0 : reportRecoveryUnreachable(attemptId, error)
489 0 : rearmBoundedDeadlineWakeUp()
490 : } else {
491 0 : schedulePendingCheckoutRecovery()
492 : }
493 : }
494 :
495 0 : const reportRecoveryUnreachable = (attemptId: string, error?: unknown) => {
496 0 : if (isDisposed) return
497 0 : const attempt = claimPendingCheckoutTerminal(
498 : attemptId,
499 : 'recovery_unreachable'
500 : )
501 0 : if (!attempt) return
502 0 : reportTelemetryError(
503 : new Error(
504 : 'Pending subscription checkout recovery could not reach billing'
505 : ),
506 : {
507 : errorType: 'failure_recovering_cloud_checkout',
508 : surface: 'billing',
509 : context: {
510 : checkout_attempt_id: attempt.attempt_id,
511 : checkout_type: attempt.checkout_type,
512 : attempt_age_ms: Date.now() - attempt.started_at_ms,
513 : tier: attempt.tier,
514 : cycle: attempt.cycle
515 : },
516 : level: 'warning'
517 : }
518 : )
519 0 : telemetry?.trackBillingEvent({
520 : operation: 'subscription_checkout',
521 : stage: 'failed',
522 : outcome: 'failure',
523 : checkout_attempt_id: attempt.attempt_id,
524 : failure_category: categorizeBillingApiError(error),
525 : tier: attempt.tier,
526 : cycle: attempt.cycle,
527 : checkout_type: attempt.checkout_type,
528 : duration_ms: Date.now() - attempt.started_at_ms
529 : })
530 0 : if (attempt.operation === 'resubscribe') {
531 0 : telemetry?.trackBillingEvent({
532 : operation: 'resubscribe',
533 : stage: 'failed',
534 : outcome: 'failure',
535 : source: attempt.resubscribe_source ?? 'settings_billing_panel',
536 : checkout_attempt_id: attempt.attempt_id,
537 : failure_category: categorizeBillingApiError(error)
538 : })
539 : }
540 : }
541 :
542 0 : const waitForActiveRecoveryAtDeadline = async (
543 : source: PendingCheckoutRecoverySource,
544 : attemptId: string
545 : ): Promise<boolean> => {
546 0 : if (activePendingCheckoutRead?.attemptId !== attemptId) return false
547 0 : if (source !== 'deadline') return true
548 :
549 0 : try {
550 : const status = await withTimeout(
551 : activePendingCheckoutRead.promise,
552 : PENDING_CHECKOUT_DEADLINE_REFRESH_TIMEOUT_MS
553 : )
554 0 : return status !== null
555 : } catch (error) {
556 0 : console.error(
557 : '[Subscription] Pending checkout recovery was still running at the deadline:',
558 : error
559 : )
560 0 : reportRecoveryUnreachable(attemptId, error)
561 0 : rearmBoundedDeadlineWakeUp()
562 0 : return false
563 : }
564 : }
565 :
566 0 : const fetchPendingCheckoutStatus = async (attemptId: string) => {
567 0 : lastPendingCheckoutStatus = null
568 0 : const statusFetch = fetchSubscriptionStatus()
569 0 : activePendingCheckoutRead = { attemptId, promise: statusFetch }
570 0 : try {
571 0 : return await withTimeout(
572 : statusFetch,
573 : PENDING_CHECKOUT_DEADLINE_REFRESH_TIMEOUT_MS
574 : )
575 : } catch (error) {
576 0 : clearInFlightStatusFetch(statusFetch)
577 0 : throw error
578 : }
579 : }
580 :
581 0 : const rearmBoundedDeadlineWakeUp = () => {
582 : const attempt = getPendingSubscriptionCheckoutAttempt()
583 0 : if (!attempt) return
584 0 : const { deadlineRung } = pendingCheckoutSchedule
585 0 : if (deadlineRung >= PENDING_CHECKOUT_DEADLINE_RETRY_DELAYS_MS.length) return
586 0 : const delay = PENDING_CHECKOUT_DEADLINE_RETRY_DELAYS_MS[deadlineRung]
587 0 : pendingCheckoutSchedule = {
588 : ...pendingCheckoutSchedule,
589 : deadlineRung: deadlineRung + 1
590 : }
591 0 : armMissingCheckoutCompletionWakeUp(delay)
592 : }
593 :
594 0 : const retryUnavailableDeadline = (source: PendingCheckoutRecoverySource) => {
595 0 : if (source !== 'deadline') return
596 :
597 : const attempt = getPendingSubscriptionCheckoutAttempt()
598 0 : if (attempt) rearmBoundedDeadlineWakeUp()
599 : }
600 :
601 0 : const handleEmptyPendingCheckoutStatus = (
602 : source: PendingCheckoutRecoverySource
603 : ) => {
604 0 : if (source === 'deadline') {
605 0 : rearmBoundedDeadlineWakeUp()
606 : } else {
607 0 : schedulePendingCheckoutRecovery()
608 : }
609 : }
610 :
611 0 : const recoverPendingSubscriptionCheckout = async (
612 : source: PendingCheckoutRecoverySource
613 : ) => {
614 0 : if (!canRecoverPendingCheckout()) {
615 0 : retryUnavailableDeadline(source)
616 0 : return
617 : }
618 0 : const attempt = getPendingSubscriptionCheckoutAttempt()
619 0 : if (!attempt) return
620 0 : const attemptId = attempt.attempt_id
621 0 : if (activePendingCheckoutRead?.attemptId === attemptId) {
622 0 : await joinActivePendingCheckoutRecovery(source, attemptId)
623 0 : return
624 : }
625 :
626 0 : if (!(await runPendingCheckoutRecovery(source, attemptId))) return
627 :
628 0 : if (source === 'deadline') reportMissingCheckoutCompletion(attemptId)
629 : }
630 :
631 0 : const joinActivePendingCheckoutRecovery = async (
632 : source: PendingCheckoutRecoverySource,
633 : attemptId: string
634 : ) => {
635 0 : const didObserveStatus = await waitForActiveRecoveryAtDeadline(
636 : source,
637 : attemptId
638 : )
639 0 : if (isDisposed || source !== 'deadline') return
640 0 : if (didObserveStatus) reportMissingCheckoutCompletion(attemptId)
641 0 : else retryUnavailableDeadline(source)
642 : }
643 :
644 0 : const runPendingCheckoutRecovery = async (
645 : source: PendingCheckoutRecoverySource,
646 : attemptId: string
647 : ): Promise<boolean> => {
648 0 : try {
649 0 : const status = await fetchPendingCheckoutStatus(attemptId)
650 0 : if (isDisposed) return false
651 0 : if (status === null) {
652 0 : handleEmptyPendingCheckoutStatus(source)
653 0 : return false
654 : }
655 0 : return true
656 : } catch (error) {
657 0 : handlePendingCheckoutRecoveryError(source, attemptId, error)
658 0 : return false
659 : } finally {
660 0 : if (activePendingCheckoutRead?.attemptId === attemptId) {
661 0 : activePendingCheckoutRead = null
662 : }
663 : }
664 : }
665 :
666 : // Coalesce concurrent callers so an auth/session-rotation burst mints one fetch.
667 0 : let inFlightStatusRead: {
668 : promise: Promise<BillingStatusResponse | null>
669 : ownerId: string | null
670 : workspaceId: string | null
671 : pendingAttemptId: string | null
672 : } | null = null
673 0 : let nextStatusFetchSequence = 0
674 0 : let statusScopeGeneration = 0
675 0 : let observedStatusScope = `${authStore.userId ?? ''}\0${workspaceStore.activeWorkspaceId ?? ''}`
676 :
677 0 : const observeStatusScope = (
678 : ownerId: string | null,
679 : workspaceId: string | null
680 : ) => {
681 0 : const scope = `${ownerId ?? ''}\0${workspaceId ?? ''}`
682 0 : if (scope === observedStatusScope) return
683 0 : observedStatusScope = scope
684 0 : statusScopeGeneration += 1
685 : // The invoice link is a bearer payment URL: never carry it across scopes.
686 0 : if (subscriptionStatus.value?.renewal_invoice) {
687 0 : subscriptionStatus.value = {
688 : ...subscriptionStatus.value,
689 : renewal_invoice: undefined
690 : }
691 : }
692 : }
693 :
694 0 : watch(
695 : () =>
696 : [
697 : authStore.userId,
698 : workspaceStore.activeWorkspaceId,
699 : awaitingSessionWorkspace.value
700 : ] as const,
701 : ([ownerId, workspaceId], [, , wasAwaitingWorkspace]) => {
702 0 : observeStatusScope(ownerId ?? null, workspaceId)
703 : // The bootstrap watcher reads for the session's first workspace.
704 0 : if (wasAwaitingWorkspace) return
705 0 : if (
706 : workspaceId &&
707 : hasPendingSubscriptionCheckoutAttempt() &&
708 : getPendingAttemptOwnership() === 'matched'
709 : ) {
710 0 : void recoverPendingSubscriptionCheckout('retry')
711 : }
712 : }
713 : )
714 :
715 0 : const clearInFlightStatusFetch = (
716 : fetchPromise: Promise<BillingStatusResponse | null>
717 : ) => {
718 0 : if (inFlightStatusRead?.promise === fetchPromise) inFlightStatusRead = null
719 : }
720 :
721 0 : const sharedStatusRead = (
722 : ownerId: string | null,
723 : workspaceId: string | null,
724 : pendingAttemptId: string | null
725 : ): Promise<BillingStatusResponse | null> | null =>
726 : inFlightStatusRead?.ownerId === ownerId &&
727 : inFlightStatusRead.workspaceId === workspaceId &&
728 : inFlightStatusRead.pendingAttemptId === pendingAttemptId
729 : ? inFlightStatusRead.promise
730 : : null
731 :
732 0 : function fetchSubscriptionStatus(
733 : options?: BillingStatusReadOptions
734 : ): Promise<BillingStatusResponse | null> {
735 0 : const ownerId = authStore.userId ?? null
736 0 : const workspaceId = workspaceStore.activeWorkspaceId
737 0 : const pendingAttemptId =
738 : getPendingSubscriptionCheckoutAttempt()?.attempt_id ?? null
739 0 : observeStatusScope(ownerId, workspaceId)
740 0 : const shared = sharedStatusRead(ownerId, workspaceId, pendingAttemptId)
741 0 : if (shared) {
742 0 : if (!options?.fresh) return shared
743 0 : return shared
744 : .catch(() => null)
745 : .then(() => fetchSubscriptionStatus(options))
746 : }
747 :
748 : const sequence = ++nextStatusFetchSequence
749 : const scopeGeneration = statusScopeGeneration
750 0 : const fetchPromise = performFetchSubscriptionStatus(
751 : ownerId,
752 : workspaceId,
753 : sequence,
754 : scopeGeneration
755 : )
756 0 : inFlightStatusRead = {
757 : promise: fetchPromise,
758 : ownerId,
759 : workspaceId,
760 : pendingAttemptId
761 : }
762 0 : void fetchPromise
763 : .catch(() => undefined)
764 : .finally(() => {
765 0 : clearInFlightStatusFetch(fetchPromise)
766 : })
767 0 : return fetchPromise
768 : }
769 :
770 : /**
771 : * The status read on whichever rail is on, in the failure shape the legacy
772 : * client threw in. The rail is taken before the read and held for it: a flag
773 : * flip mid-read must not start on one client and publish through the other.
774 : */
775 : async function readSubscriptionStatus(): Promise<
776 : BillingStatusResponse | undefined
777 : > {
778 : const rail = useBillingReadRail()
779 : try {
780 : const status = rail
781 : ? await readOnRail(rail.readStatus, 'getBillingStatus')
782 : : await billingApi.getBillingStatus()
783 : return status
784 : } catch (error) {
785 : const status =
786 : error instanceof WorkspaceApiError || error instanceof AuthStoreError
787 : ? error.status
788 : : undefined
789 : throw new AuthStoreError(
790 : t('toastMessages.failedToFetchSubscription', {
791 : error: error instanceof Error ? error.message : String(error)
792 : }),
793 : status
794 : )
795 : }
796 : }
797 :
798 0 : async function performFetchSubscriptionStatus(
799 : ownerId: string | null,
800 : workspaceId: string | null,
801 : sequence: number,
802 : scopeGeneration: number
803 : ): Promise<BillingStatusResponse | null> {
804 0 : if (!isCloud) return null
805 :
806 : const statusData = await readSubscriptionStatus()
807 : if (
808 : !isPublishableStatusRead(
809 : statusData,
810 : ownerId,
811 : workspaceId,
812 : sequence,
813 : scopeGeneration
814 : )
815 : )
816 : return null
817 : publishSubscriptionStatus(statusData)
818 :
819 : return statusData
820 : }
821 :
822 : function isPublishableStatusRead(
823 : statusData: BillingStatusResponse | undefined,
824 : ownerId: string | null,
825 : workspaceId: string | null,
826 : sequence: number,
827 : scopeGeneration: number
828 : ): statusData is BillingStatusResponse {
829 : return (
830 : !isDisposed &&
831 : statusData !== undefined &&
832 : scopeGeneration === statusScopeGeneration &&
833 : sequence === nextStatusFetchSequence &&
834 : (authStore.userId ?? null) === ownerId &&
835 : workspaceStore.activeWorkspaceId === workspaceId
836 : )
837 : }
838 :
839 : function publishSubscriptionStatus(statusData: BillingStatusResponse): void {
840 : // Only a current, publishable read proves billing is reachable.
841 : lastPendingCheckoutStatus = statusData
842 : subscriptionStatus.value = statusData
843 : syncPendingSubscriptionSuccess(statusData)
844 : }
845 :
846 0 : const handlePendingSubscriptionCheckoutChange = () => {
847 0 : if (!hasPendingSubscriptionCheckoutAttempt()) {
848 0 : stopPendingCheckoutRecovery()
849 0 : return
850 : }
851 :
852 0 : stopPendingCheckoutRecovery()
853 0 : void recoverPendingSubscriptionCheckout('retry')
854 : }
855 :
856 0 : useEventListener(defaultWindow, PENDING_SUBSCRIPTION_CHECKOUT_EVENT, () => {
857 0 : handlePendingSubscriptionCheckoutChange()
858 : })
859 :
860 0 : useEventListener(defaultWindow, 'storage', (event: StorageEvent) => {
861 0 : if (event.key === PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) {
862 0 : handlePendingSubscriptionCheckoutChange()
863 : }
864 : })
865 :
866 0 : useEventListener(defaultWindow, 'pageshow', () => {
867 0 : void recoverPendingSubscriptionCheckout('pageshow')
868 : })
869 :
870 0 : useEventListener(defaultDocument, 'visibilitychange', () => {
871 0 : if (defaultDocument?.visibilityState === 'visible') {
872 0 : void recoverPendingSubscriptionCheckout('visibilitychange')
873 : }
874 : })
875 :
876 0 : watch(
877 : () =>
878 : [
879 : authStore.isInitialized,
880 : isLoggedIn.value,
881 : authStore.userId,
882 : awaitingSessionWorkspace.value
883 : ] as const,
884 : async ([authInitialized, loggedIn, , awaitingWorkspace]) => {
885 0 : if (!authInitialized) {
886 0 : return
887 : }
888 :
889 : if (loggedIn && isCloud) {
890 : if (awaitingWorkspace) return
891 : try {
892 : if (hasOwnedPendingCheckoutAttempt()) {
893 : await recoverPendingSubscriptionCheckout('bootstrap')
894 : } else {
895 : await fetchSubscriptionStatus()
896 : }
897 : } catch (error) {
898 : // Network errors are expected during navigation/component unmount
899 : // and when offline - log for debugging but don't surface to user
900 : console.error('Failed to fetch subscription status:', error)
901 : } finally {
902 : isInitialized.value = true
903 : }
904 : } else {
905 0 : subscriptionStatus.value = null
906 0 : clearPendingSubscriptionCheckoutAttempt()
907 0 : stopPendingCheckoutRecovery()
908 0 : isInitialized.value = true
909 : }
910 : },
911 : { immediate: true }
912 : )
913 :
914 0 : return {
915 : // State
916 : canAccessSubscriptionFeatures: canAccessSubscriptionFeatures,
917 : isInitialized,
918 : isCancelled,
919 : formattedRenewalDate,
920 : formattedEndDate,
921 : subscriptionTier,
922 : isFreeTier,
923 : subscriptionDuration,
924 : isYearlySubscription,
925 : subscriptionTierName,
926 : subscriptionStatus,
927 :
928 : // Utilities
929 : isSubscriptionEnabled,
930 :
931 : // Actions
932 : fetchStatus,
933 : fetchStatusDirect: fetchSubscriptionStatus,
934 : handleViewUsageHistory,
935 : handleLearnMore
936 : }
937 : }
938 :
939 0 : function getPendingCheckoutRetryDelay(attempt: number): number | undefined {
940 0 : return PENDING_SUBSCRIPTION_CHECKOUT_RETRY_DELAYS_MS[attempt]
941 : }
942 :
943 2355 : export const useSubscription = createSharedComposable(useSubscriptionInternal)
|