LCOV - code coverage report
Current view: top level - src/platform/billing/composables - useBillingCapabilities.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 74.1 % 212 157
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import {
       2              :   createSharedComposable,
       3              :   defaultDocument,
       4              :   useEventListener
       5              : } from '@vueuse/core'
       6              : import { computed, onScopeDispose, shallowRef, watch } from 'vue'
       7              : 
       8              : import { receiveServerFact } from '@/platform/serverFacts/serverFact'
       9              : import { useTelemetry } from '@comfyorg/telemetry'
      10              : import { reportError } from '@comfyorg/telemetry/reportError'
      11              : import { onCapabilityRevision } from '@/platform/remote/ingest/capabilityRevision'
      12              : import type { BillingCapabilitiesRead } from '@comfyorg/billing-core'
      13              : import { parseBillingTopUpDenial } from '@comfyorg/billing-core'
      14              : import { billingApi } from '@/platform/billing/api/billingApi'
      15              : import { localBillingWebEnabled } from '@/platform/billing/localBillingWebEnabled'
      16              : import { WorkspaceApiError } from '@/platform/remote/ingest/ingestApiError'
      17              : import { readOnRail } from '@/platform/billing/composables/readOnRail'
      18              : import { useBillingReadRail } from '@/platform/billing/composables/useBillingReadRail'
      19              : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
      20              : import { reportWorkspaceScopeMismatch } from '@/platform/billing/telemetry/workspaceTelemetryContext'
      21              : import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
      22              : import { useAuthStore } from '@/stores/authStore'
      23              : import { useFeatureFlags } from '@/composables/useFeatureFlags'
      24              : import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore'
      25              : 
      26              : type CapabilityReadState =
      27              :   | { status: 'idle' }
      28              :   | {
      29              :       status: 'pending'
      30              :       authUid: string
      31              :       workspaceId: string
      32              :     }
      33              :   | {
      34              :       status: 'denied'
      35              :       authUid: string
      36              :       workspaceId: string
      37              :       sessionLapsed: boolean
      38              :     }
      39              :   | {
      40              :       status: 'unavailable'
      41              :       authUid: string
      42              :       workspaceId: string
      43              :       retryAt: number
      44              :     }
      45              :   | {
      46              :       status: 'resolved'
      47              :       authUid: string
      48              :       workspaceId: string
      49              :       response: BillingCapabilitiesRead
      50              :       refreshAt: number
      51              :     }
      52              : 
      53              : // A remaining lifetime below the floor means the client clock disagrees with
      54              : // the server's, so it cannot pace the refetch and the fixed interval is used
      55              : // instead; clamping it would only slow the loop. The ceiling bounds the
      56              : // opposite skew, where a lagging clock reads expires_at as far in the future.
      57         2356 : const MIN_REFRESH_DELAY_MS = 5_000
      58         2356 : const MAX_REFRESH_DELAY_MS = 60 * 60 * 1000
      59         2356 : const FALLBACK_REFRESH_DELAY_MS = 60_000
      60              : // An outage fails every visible session at once, so a flat retry interval would
      61              : // keep them retrying in lockstep. Consecutive failures double up to this
      62              : // ceiling, and each delay is jittered to spread the sessions apart.
      63         2356 : const MAX_RETRY_DELAY_MS = 5 * 60 * 1000
      64              : 
      65              : interface ActiveCapabilityRequest {
      66              :   requestId: number
      67              :   authUid: string
      68              :   workspaceId: string
      69              :   controller: AbortController
      70              :   promise: Promise<void>
      71              : }
      72              : 
      73              : /**
      74              :  * The read itself, on whichever rail the tab is on. A revalidation already
      75              :  * knows the snapshot is stale — a mutation or the expiry timer said so — so it
      76              :  * bypasses the SDK's cache; the first read for a scope takes what the SDK
      77              :  * already holds, which is what the shared top-up flow read.
      78              :  */
      79           25 : function readCapabilitiesResponse(
      80              :   signal: AbortSignal,
      81              :   revalidating: boolean
      82              : ): Promise<BillingCapabilitiesRead | undefined> {
      83           25 :   const rail = useBillingReadRail()
      84           25 :   if (rail === null) return billingApi.getBillingCapabilities(signal)
      85            0 :   return readOnRail(
      86              :     () => rail.readCapabilities({ signal, forceRefresh: revalidating }),
      87              :     'getBillingCapabilities'
      88              :   )
      89              : }
      90              : 
      91         2355 : function useBillingCapabilitiesInternal() {
      92         2355 :   const authStore = useAuthStore()
      93         2355 :   const webSession = useCloudWebSessionStore()
      94         2355 :   const { flags } = useFeatureFlags()
      95         7091 :   function lapseRecoveryEnabled(): boolean {
      96         7091 :     return flags.webSessionLapseRecoveryEnabled
      97              :   }
      98         2355 :   const apiKeyAuthStore = useApiKeyAuthStore()
      99         2355 :   const workspaceStore = useWorkspaceIdentity()
     100         2355 :   const actorId = computed(
     101              :     () => authStore.userId ?? apiKeyAuthStore.currentUser?.id
     102              :   )
     103         2355 :   const readState = shallowRef<CapabilityReadState>({ status: 'idle' })
     104         2355 :   let initialized = false
     105         2355 :   let latestRequestId = 0
     106         2355 :   let activeRequest: ActiveCapabilityRequest | null = null
     107         2355 :   let refreshTimer: ReturnType<typeof setTimeout> | null = null
     108         2355 :   let readFailures = 0
     109         2355 :   let invalidatedRequestId = 0
     110              : 
     111         2355 :   const resolvedResponse = computed(() => {
     112           17 :     const userId = actorId.value
     113           17 :     const workspaceId = workspaceStore.activeWorkspaceId
     114           17 :     const state = readState.value
     115           17 :     if (
     116              :       !userId ||
     117              :       !workspaceId ||
     118              :       state.status !== 'resolved' ||
     119              :       state.authUid !== userId ||
     120              :       state.workspaceId !== workspaceId ||
     121              :       state.response.resolved_for.workspace_id !== workspaceId
     122              :     ) {
     123            1 :       return null
     124              :     }
     125              : 
     126           16 :     return state.response
     127              :   })
     128         2355 :   const capabilities = computed(
     129              :     () => resolvedResponse.value?.capabilities ?? null
     130              :   )
     131         2355 :   const hasResolvedCapabilities = computed(() => capabilities.value !== null)
     132         2355 :   const canTopUp = computed(() => capabilities.value?.can_top_up ?? false)
     133         2355 :   const topUpDenial = computed(() =>
     134              :     parseBillingTopUpDenial(resolvedResponse.value?.denied_reasons?.can_top_up)
     135              :   )
     136         2355 :   const canManageBilling = computed(() =>
     137              :     receiveServerFact(
     138              :       'can_manage_billing',
     139              :       capabilities.value?.can_manage_billing ?? false
     140              :     )
     141              :   )
     142         2355 :   const canSubscribeSelfServe = computed(
     143              :     () => capabilities.value?.can_subscribe_self_serve ?? false
     144              :   )
     145         2355 :   const canOpenPlans = computed(() =>
     146              :     receiveServerFact(
     147              :       'can_open_plans',
     148              :       capabilities.value?.can_open_plans ?? false
     149              :     )
     150              :   )
     151         2355 :   const canCancel = computed(() => capabilities.value?.can_cancel ?? false)
     152         2355 :   const canReactivate = computed(
     153              :     () => capabilities.value?.can_reactivate ?? false
     154              :   )
     155         2355 :   const canRevertScheduledChange = computed(() =>
     156              :     receiveServerFact(
     157              :       'can_revert_scheduled_change',
     158              :       capabilities.value?.can_revert_scheduled_change ?? false
     159              :     )
     160              :   )
     161         2355 :   const canChangeSeats = computed(
     162              :     () => capabilities.value?.can_change_seats ?? false
     163              :   )
     164         2355 :   const canManageMembers = computed(() =>
     165              :     receiveServerFact(
     166              :       'can_manage_members',
     167              :       capabilities.value?.can_manage_members ?? false
     168              :     )
     169              :   )
     170         2355 :   const canInviteMembers = computed(() =>
     171              :     receiveServerFact(
     172              :       'can_invite_members',
     173              :       capabilities.value?.can_invite_members ?? false
     174              :     )
     175              :   )
     176         2355 :   const canDeleteWorkspace = computed(() =>
     177              :     receiveServerFact(
     178              :       'can_delete_workspace',
     179              :       capabilities.value?.can_delete_workspace ?? false
     180              :     )
     181              :   )
     182         2355 :   const deleteWorkspaceDenial = computed<string | undefined>(
     183              :     () => resolvedResponse.value?.denied_reasons?.can_delete_workspace
     184              :   )
     185         2355 :   const canEditWorkspace = computed(() =>
     186              :     receiveServerFact(
     187              :       'can_edit_workspace',
     188              :       capabilities.value?.can_edit_workspace ?? false
     189              :     )
     190              :   )
     191         2355 :   const canLeaveWorkspace = computed(() =>
     192              :     receiveServerFact(
     193              :       'can_leave_workspace',
     194              :       capabilities.value?.can_leave_workspace ?? false
     195              :     )
     196              :   )
     197         2355 :   const leaveWorkspaceDenial = computed<string | undefined>(
     198              :     () => resolvedResponse.value?.denied_reasons?.can_leave_workspace
     199              :   )
     200         2355 :   const canManageSubscription = computed(() =>
     201              :     receiveServerFact(
     202              :       'can_manage_subscription',
     203              :       capabilities.value?.can_manage_subscription ?? false
     204              :     )
     205              :   )
     206         2355 :   const canDowngradeToPersonal = computed(
     207              :     () => capabilities.value?.can_downgrade_to_personal ?? false
     208              :   )
     209         2355 :   const canManageAutoTopUp = computed(() =>
     210              :     receiveServerFact(
     211              :       'can_manage_auto_top_up',
     212              :       capabilities.value?.can_manage_auto_top_up ?? false
     213              :     )
     214              :   )
     215         2355 :   const canViewAutoTopUpCard = computed(() =>
     216              :     receiveServerFact(
     217              :       'can_view_auto_top_up',
     218              :       capabilities.value?.can_view_auto_top_up ?? false
     219              :     )
     220              :   )
     221         2355 :   const canViewAutoTopUpMemberNotice = computed(() =>
     222              :     receiveServerFact(
     223              :       'can_view_auto_top_up_member_notice',
     224              :       capabilities.value?.can_view_auto_top_up_member_notice ?? false
     225              :     )
     226              :   )
     227         2355 :   const autoTopUpEnabled = computed(() =>
     228              :     receiveServerFact(
     229              :       'auto_top_up_enabled',
     230              :       resolvedResponse.value?.auto_top_up_enabled ?? false
     231              :     )
     232              :   )
     233         2355 :   const autoTopUpSetup = computed(
     234              :     () => resolvedResponse.value?.auto_top_up_setup ?? null
     235              :   )
     236         2355 :   const autoTopUpMemberView = computed(() =>
     237              :     receiveServerFact(
     238              :       'auto_top_up_member_view',
     239              :       resolvedResponse.value?.auto_top_up_member_view ?? null
     240              :     )
     241              :   )
     242         2355 :   const canRunWorkflows = computed(
     243              :     () => capabilities.value?.can_run_workflows ?? false
     244              :   )
     245         2355 :   const planKind = computed(() =>
     246              :     receiveServerFact('plan_kind', resolvedResponse.value?.plan_kind ?? null)
     247              :   )
     248         2355 :   const paymentRecoveryAvailable = computed(() =>
     249              :     receiveServerFact(
     250              :       'payment_recovery_available',
     251              :       resolvedResponse.value?.payment_recovery_available ?? false
     252              :     )
     253              :   )
     254         2355 :   const hasParkedBillingOperation = computed(() =>
     255              :     receiveServerFact(
     256              :       'has_parked_billing_operation',
     257              :       resolvedResponse.value?.has_parked_billing_operation === true
     258              :     )
     259              :   )
     260         2355 :   const billingNoticeAudience = computed(() =>
     261              :     receiveServerFact(
     262              :       'billing_notice_audience',
     263              :       resolvedResponse.value?.billing_notice_audience ?? null
     264              :     )
     265              :   )
     266         2355 :   const endingNoticeStartsAt = computed(() =>
     267              :     receiveServerFact(
     268              :       'ending_notice_starts_at',
     269              :       resolvedResponse.value?.ending_notice_starts_at ?? null
     270              :     )
     271              :   )
     272         2355 :   const runWorkflowsDenial = computed(() =>
     273              :     receiveServerFact(
     274              :       'denied_reasons.can_run_workflows',
     275              :       resolvedResponse.value?.denied_reasons?.can_run_workflows
     276              :     )
     277              :   )
     278         2355 :   const runDeniedPaymentPastDue = computed(
     279              :     () => runWorkflowsDenial.value === 'payment_past_due'
     280              :   )
     281         2355 :   const isReady = computed(() => {
     282           24 :     const state = readState.value
     283           24 :     if (state.status === 'idle' || state.status === 'pending') return false
     284           24 :     return (
     285              :       state.authUid === actorId.value &&
     286              :       state.workspaceId === workspaceStore.activeWorkspaceId
     287              :     )
     288              :   })
     289              : 
     290         2355 :   const snapshotAuthoritative = computed(() => {
     291            0 :     const state = readState.value
     292            0 :     if (state.status !== 'resolved' && state.status !== 'denied') return false
     293            0 :     return (
     294              :       state.authUid === actorId.value &&
     295              :       state.workspaceId === workspaceStore.activeWorkspaceId
     296              :     )
     297              :   })
     298              : 
     299           25 :   function trackCapabilityRead(succeeded: boolean): void {
     300           25 :     useTelemetry()?.trackBillingEvent({
     301              :       operation: 'capability_read',
     302              :       ...(succeeded
     303              :         ? { stage: 'succeeded', outcome: 'success' }
     304              :         : { stage: 'failed', outcome: 'failure' })
     305              :     })
     306              :   }
     307              : 
     308          171 :   function clearRefreshTimer(): void {
     309          171 :     if (refreshTimer === null) return
     310            9 :     clearTimeout(refreshTimer)
     311            9 :     refreshTimer = null
     312              :   }
     313              : 
     314           26 :   function scheduledRefreshAt(state: CapabilityReadState): number | null {
     315           26 :     if (state.status === 'resolved') return state.refreshAt
     316           26 :     return state.status === 'unavailable' ? state.retryAt : null
     317              :   }
     318              : 
     319              :   /** Requires `readFailures` to already count this failure. */
     320            0 :   function unavailableState(
     321              :     authUid: string,
     322              :     workspaceId: string
     323              :   ): CapabilityReadState {
     324            0 :     const delay = Math.min(
     325              :       FALLBACK_REFRESH_DELAY_MS * 2 ** (readFailures - 1),
     326              :       MAX_RETRY_DELAY_MS
     327              :     )
     328            0 :     return {
     329              :       status: 'unavailable',
     330              :       authUid,
     331              :       workspaceId,
     332              :       retryAt: Date.now() + delay / 2 + Math.random() * (delay / 2)
     333              :     }
     334              :   }
     335              : 
     336              :   // NaN from an unparseable timestamp fails the comparison and lands on the
     337              :   // fixed interval.
     338           25 :   function nextRefreshAt(response: BillingCapabilitiesRead): number {
     339           25 :     const now = Date.now()
     340           25 :     const remaining = Date.parse(response.expires_at) - now
     341           25 :     if (remaining >= MIN_REFRESH_DELAY_MS) {
     342           25 :       return now + Math.min(remaining, MAX_REFRESH_DELAY_MS)
     343              :     }
     344            0 :     return now + FALLBACK_REFRESH_DELAY_MS
     345              :   }
     346              : 
     347              :   // `capabilities` is a computed, and wall-clock time is not a reactive
     348              :   // dependency, so expiry has to be pushed rather than read lazily. The timer
     349              :   // runs only while the document is visible: staleness is unobservable in a
     350              :   // hidden tab, and returning to the tab is itself a visibility transition.
     351           25 :   function scheduleRefresh(): void {
     352           25 :     clearRefreshTimer()
     353           25 :     const refreshAt = scheduledRefreshAt(readState.value)
     354           25 :     if (refreshAt === null) return
     355           25 :     if (defaultDocument?.visibilityState === 'hidden') return
     356              : 
     357           25 :     const delay = Math.max(0, refreshAt - Date.now())
     358           25 :     refreshTimer = setTimeout(() => {
     359            0 :       refreshTimer = null
     360            0 :       void fetchCapabilities()
     361              :     }, delay)
     362              :   }
     363              : 
     364         2355 :   useEventListener(defaultDocument, 'visibilitychange', () => {
     365          100 :     if (defaultDocument?.visibilityState === 'hidden') {
     366           99 :       clearRefreshTimer()
     367           99 :       return
     368              :     }
     369            1 :     const refreshAt = scheduledRefreshAt(readState.value)
     370            1 :     if (refreshAt === null) return
     371            0 :     if (refreshAt <= Date.now()) void fetchCapabilities()
     372            0 :     else scheduleRefresh()
     373              :   })
     374              : 
     375         2355 :   const stopRevisionListener = onCapabilityRevision((revision) => {
     376              :     // A read already in flight may have loaded its data before this mutation
     377              :     // committed, and the revision it returns cannot rule that out: the server
     378              :     // mints that number when it serializes the response, not when it read. So
     379              :     // the read is refetched once it settles - the dedupe below would otherwise
     380              :     // hand back the very request that missed the mutation.
     381            0 :     if (activeRequest) invalidatedRequestId = activeRequest.requestId
     382            0 :     const state = readState.value
     383            0 :     if (state.status !== 'resolved' || state.response.revision === revision) {
     384            0 :       return
     385              :     }
     386            0 :     void fetchCapabilities()
     387              :   })
     388              : 
     389         2355 :   let disposed = false
     390         2355 :   onScopeDispose(() => {
     391            0 :     disposed = true
     392            0 :     clearRefreshTimer()
     393            0 :     stopRevisionListener()
     394              :   })
     395              : 
     396              :   /** Cancels the in-flight read and its timer, leaving the snapshot in place. */
     397           47 :   function cancelActiveRead(): void {
     398           47 :     clearRefreshTimer()
     399           47 :     latestRequestId++
     400           47 :     activeRequest?.controller.abort()
     401           47 :     activeRequest = null
     402              :   }
     403              : 
     404           41 :   function resetRead(): void {
     405           41 :     cancelActiveRead()
     406           41 :     readState.value = { status: 'idle' }
     407              :   }
     408              : 
     409           26 :   async function fetchCapabilities(signal?: AbortSignal): Promise<void> {
     410           26 :     const userId = actorId.value
     411           26 :     const workspaceId = workspaceStore.activeWorkspaceId
     412           26 :     if (!userId || !workspaceId) {
     413            1 :       resetRead()
     414            1 :       return
     415              :     }
     416              : 
     417           26 :     if (
     418              :       activeRequest?.authUid === userId &&
     419              :       activeRequest.workspaceId === workspaceId &&
     420              :       !activeRequest.controller.signal.aborted
     421              :     ) {
     422            0 :       return activeRequest.promise
     423              :     }
     424              : 
     425              :     // Refetching the same scope revalidates in the background, keeping the
     426              :     // prior read - a resolved snapshot or the unavailable fallback - readable
     427              :     // so its affordances do not blink out once per refresh. A scope change
     428              :     // makes it wrong, not stale, so it resets.
     429           25 :     const currentState = readState.value
     430           26 :     const revalidating =
     431              :       (currentState.status === 'resolved' ||
     432              :         currentState.status === 'unavailable') &&
     433              :       currentState.authUid === userId &&
     434              :       currentState.workspaceId === workspaceId
     435           26 :     const priorSnapshot =
     436              :       revalidating && currentState.status === 'resolved' ? currentState : null
     437              : 
     438           26 :     if (revalidating) cancelActiveRead()
     439           19 :     else resetRead()
     440              : 
     441           25 :     const requestId = ++latestRequestId
     442           25 :     const recoveryEnabledAtStart = lapseRecoveryEnabled()
     443           25 :     const controller = new AbortController()
     444           25 :     const abortRequest = () => controller.abort()
     445           26 :     if (signal?.aborted) controller.abort()
     446           25 :     else signal?.addEventListener('abort', abortRequest, { once: true })
     447           25 :     if (!revalidating) {
     448           19 :       readState.value = {
     449              :         status: 'pending',
     450              :         authUid: userId,
     451              :         workspaceId
     452              :       }
     453              :     }
     454              : 
     455           25 :     const promise = (async () => {
     456           25 :       let refetchAfterSettle = false
     457           25 :       try {
     458           25 :         const response = await readCapabilitiesResponse(
     459              :           controller.signal,
     460              :           revalidating
     461              :         )
     462           25 :         if (
     463              :           requestId !== latestRequestId ||
     464              :           userId !== actorId.value ||
     465              :           workspaceId !== workspaceStore.activeWorkspaceId
     466              :         ) {
     467            0 :           return
     468              :         }
     469              :         // The SDK's scope moved on under the read while the stores' did not:
     470              :         // a switch mid-flight. It retries on the outage timer, unreported,
     471              :         // because the next read answers for whichever scope settles.
     472           25 :         if (response === undefined) {
     473            0 :           readFailures++
     474            0 :           readState.value = priorSnapshot
     475              :             ? {
     476              :                 ...priorSnapshot,
     477              :                 refreshAt: Date.now() + FALLBACK_REFRESH_DELAY_MS
     478              :               }
     479              :             : unavailableState(userId, workspaceId)
     480            0 :           scheduleRefresh()
     481            0 :           return
     482              :         }
     483              : 
     484           25 :         const resolvedForScope =
     485              :           response.resolved_for.workspace_id === workspaceId
     486           25 :         trackCapabilityRead(resolvedForScope)
     487           25 :         if (resolvedForScope) {
     488           25 :           readFailures = 0
     489           25 :           readState.value = {
     490              :             status: 'resolved',
     491              :             authUid: userId,
     492              :             workspaceId,
     493              :             response,
     494              :             refreshAt: nextRefreshAt(response)
     495              :           }
     496              :         } else {
     497            0 :           readFailures++
     498            0 :           readState.value = unavailableState(userId, workspaceId)
     499            0 :           reportWorkspaceScopeMismatch(
     500              :             workspaceId,
     501              :             response.resolved_for.workspace_id
     502              :           )
     503              :         }
     504           25 :         scheduleRefresh()
     505           25 :         refetchAfterSettle =
     506              :           resolvedForScope && invalidatedRequestId === requestId
     507              :       } catch (error) {
     508            0 :         if (
     509              :           requestId !== latestRequestId ||
     510              :           userId !== actorId.value ||
     511              :           workspaceId !== workspaceStore.activeWorkspaceId
     512              :         ) {
     513            0 :           return
     514              :         }
     515            0 :         if (controller.signal.aborted) {
     516            0 :           if (!revalidating) readState.value = { status: 'idle' }
     517            0 :           return
     518              :         }
     519              : 
     520            0 :         const denied =
     521              :           (error instanceof WorkspaceApiError &&
     522              :             (error.status === 401 || error.status === 403)) ||
     523              :           (error instanceof Error && error.name === 'AuthStoreError')
     524            0 :         const sessionLapsed =
     525              :           error instanceof WorkspaceApiError && error.status === 401
     526            0 :         if (!denied) trackCapabilityRead(false)
     527              :         // A transient failure keeps the last good snapshot - stale, not wrong -
     528              :         // and retries. A denial is the server answering about this actor, so it
     529              :         // replaces the snapshot even mid-revalidation.
     530            0 :         const firstFailure = readFailures === 0
     531            0 :         if (!denied) readFailures++
     532            0 :         if (priorSnapshot && !denied) {
     533            0 :           readState.value = {
     534              :             ...priorSnapshot,
     535              :             refreshAt: Date.now() + FALLBACK_REFRESH_DELAY_MS
     536              :           }
     537              :         } else {
     538            0 :           readState.value = denied
     539              :             ? { status: 'denied', authUid: userId, workspaceId, sessionLapsed }
     540              :             : unavailableState(userId, workspaceId)
     541              :         }
     542            0 :         scheduleRefresh()
     543            0 :         refetchAfterSettle =
     544              :           sessionLapsed &&
     545              :           !recoveryEnabledAtStart &&
     546              :           lapseRecoveryEnabled() &&
     547              :           webSession.state.phase === 'signed_in'
     548              :         // A sustained outage retries on a timer, so reporting every attempt
     549              :         // would emit one warning a minute for as long as the tab is open.
     550            0 :         if (!denied && !firstFailure) return
     551            0 :         reportError(error, {
     552              :           surface: 'workspace',
     553              :           errorType: 'billing_capabilities_read_failure',
     554              :           level: 'warning',
     555              :           tags: {
     556              :             status:
     557              :               error instanceof WorkspaceApiError
     558              :                 ? (error.status ?? 'unknown')
     559              :                 : 'unknown',
     560              :             outcome: denied ? 'denied' : 'unavailable'
     561              :           }
     562              :         })
     563              :       } finally {
     564           25 :         signal?.removeEventListener('abort', abortRequest)
     565           25 :         if (activeRequest?.requestId === requestId) {
     566           25 :           activeRequest = null
     567              :           // Deferred to here so the refetch is not deduped onto the request
     568              :           // it replaces. It cannot loop: this one is issued after the revision
     569              :           // that marked it, so only a further mutation can mark it in turn.
     570           25 :           if (refetchAfterSettle && !disposed) void fetchCapabilities()
     571              :         }
     572              :       }
     573              :     })()
     574              : 
     575           25 :     activeRequest = {
     576              :       requestId,
     577              :       authUid: userId,
     578              :       workspaceId,
     579              :       controller,
     580              :       promise
     581              :     }
     582           25 :     return promise
     583              :   }
     584              : 
     585           23 :   async function initialize(signal?: AbortSignal): Promise<void> {
     586           23 :     initialized = true
     587           23 :     do {
     588           23 :       await fetchCapabilities(signal)
     589              :     } while (
     590              :       !signal?.aborted &&
     591              :       !!actorId.value &&
     592              :       !!workspaceStore.activeWorkspaceId &&
     593              :       !isReady.value
     594              :     )
     595              :   }
     596              : 
     597            0 :   async function refresh(): Promise<void> {
     598            0 :     const requestIdAtCall = latestRequestId
     599            0 :     await initialize()
     600            0 :     if (!localBillingWebEnabled.value || disposed) return
     601              :     const noReadStartedSinceCall = latestRequestId === requestIdAtCall
     602            0 :     if (noReadStartedSinceCall) await initialize()
     603            0 :     else await activeRequest?.promise
     604              :   }
     605              : 
     606         2355 :   watch(
     607              :     [
     608              :       () => actorId.value,
     609              :       () => workspaceStore.activeWorkspaceId,
     610              :       () => workspaceStore.activeWorkspace?.role
     611              :     ],
     612              :     () => {
     613           21 :       readFailures = 0
     614           21 :       resetRead()
     615           21 :       if (initialized) void fetchCapabilities()
     616              :     }
     617              :   )
     618              : 
     619         2355 :   watch(
     620              :     [() => webSession.state, lapseRecoveryEnabled],
     621              :     ([state, recoveryEnabled]) => {
     622            0 :       const read = readState.value
     623            0 :       if (
     624              :         state.phase === 'signed_in' &&
     625              :         read.status === 'denied' &&
     626              :         read.sessionLapsed &&
     627              :         recoveryEnabled
     628              :       ) {
     629            0 :         void fetchCapabilities()
     630              :       }
     631              :     }
     632              :   )
     633              : 
     634         2355 :   return {
     635              :     canTopUp,
     636              :     topUpDenial,
     637              :     canManageBilling,
     638              :     canSubscribeSelfServe,
     639              :     canOpenPlans,
     640              :     canCancel,
     641              :     canReactivate,
     642              :     canRevertScheduledChange,
     643              :     canChangeSeats,
     644              :     canInviteMembers,
     645              :     canManageMembers,
     646              :     canDeleteWorkspace,
     647              :     deleteWorkspaceDenial,
     648              :     canEditWorkspace,
     649              :     canLeaveWorkspace,
     650              :     leaveWorkspaceDenial,
     651              :     canManageSubscription,
     652              :     canDowngradeToPersonal,
     653              :     canManageAutoTopUp,
     654              :     canViewAutoTopUpCard,
     655              :     canViewAutoTopUpMemberNotice,
     656              :     autoTopUpEnabled,
     657              :     autoTopUpSetup,
     658              :     autoTopUpMemberView,
     659              :     canRunWorkflows,
     660              :     planKind,
     661              :     paymentRecoveryAvailable,
     662              :     runWorkflowsDenial,
     663              :     hasParkedBillingOperation,
     664              :     billingNoticeAudience,
     665              :     endingNoticeStartsAt,
     666              :     runDeniedPaymentPastDue,
     667              :     isReady,
     668              :     hasResolvedCapabilities,
     669              :     snapshotAuthoritative,
     670              :     initialize,
     671              :     refresh
     672              :   }
     673              : }
     674              : 
     675         2356 : export const useBillingCapabilities = createSharedComposable(
     676              :   useBillingCapabilitiesInternal
     677              : )
        

Generated by: LCOV version 2.0-1