The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
AI chat: never fail silently on exhausted credits (#24175)
Félix Malfait2bde5fe9bfef
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsxindex 2e34f3454f6..199058c621d 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -19,15 +19,14 @@ import { SendMessageButton } from '@/ai/components/internal/SendMessageButton';import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';import { useAiChatEditor } from '@/ai/hooks/useAiChatEditor';import { useAiModelOptions } from '@/ai/hooks/useAiModelOptions';+import { useHasReachedAiChatCreditsCap } from '@/ai/hooks/useHasReachedAiChatCreditsCap';import { useWorkspaceAiModelAvailability } from '@/ai/hooks/useWorkspaceAiModelAvailability';import { agentChatUserSelectedModelState } from '@/ai/states/agentChatUserSelectedModelState';import { agentChatPendingQuestionComponentSelector } from '@/ai/states/selectors/agentChatPendingQuestionComponentSelector';import { Select } from '@/ui/input/components/Select';import { useIsMobile } from '@/ui/utilities/responsive/hooks/useIsMobile';import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';-import { hasReachedCurrentBillingPeriodCapSelector } from '@/workspace/states/hasReachedCurrentBillingPeriodCapSelector';import { type SelectOption } from 'twenty-ui/input';const StyledInputArea = styled.div<{ isMobile: boolean }>`@@ -119,9 +118,7 @@ const StyledRightButtonsContainer = styled.div`export const AiChatEditorSection = () => {const { t } = useLingui();const isMobile = useIsMobile();- const hasReachedCurrentBillingPeriodCap = useAtomStateValue(- hasReachedCurrentBillingPeriodCapSelector,- );+ const hasReachedAiChatCreditsCap = useHasReachedAiChatCreditsCap();const { enabledModels } = useWorkspaceAiModelAvailability();const hasNoEnabledModels = enabledModels.length === 0;const { options, pinnedOption } = useAiModelOptions({@@ -162,9 +159,7 @@ export const AiChatEditorSection = () => {variant="warning"/>)}- {hasReachedCurrentBillingPeriodCap && (- <AIChatNoMoreBillingCreditsBanner />- )}+ {hasReachedAiChatCreditsCap && <AIChatNoMoreBillingCreditsBanner />}{isDefined(pendingQuestion) ? (<AiChatQuestionCard pendingQuestion={pendingQuestion} />) : (diff --git a/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsxindex a8217903d1a..06359f81403 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx@@ -14,7 +14,8 @@ export const AiChatErrorRenderer = ({onRetry,}: AiChatErrorRendererProps) => {if (isGraphqlErrorOfType(error, AiChatErrorCode.BILLING_CREDITS_EXHAUSTED)) {- //Handle by AIChatNoMoreBillingCreditsBanner+ // Handled by AIChatNoMoreBillingCreditsBanner, which useHasReachedAiChatCreditsCap+ // keeps mounted for exactly this error so nothing is swallowed herereturn null;}diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useHasReachedAiChatCreditsCap.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useHasReachedAiChatCreditsCap.test.tsxnew file mode 100644index 00000000000..3f972e8a477--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useHasReachedAiChatCreditsCap.test.tsx@@ -0,0 +1,128 @@+import { CombinedGraphQLErrors } from '@apollo/client/errors';+import { renderHook } from '@testing-library/react';+import { Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';++import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';+import { useHasReachedAiChatCreditsCap } from '@/ai/hooks/useHasReachedAiChatCreditsCap';+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';+import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import {+ jotaiStore,+ resetJotaiStore,+} from '@/ui/utilities/state/jotai/jotaiStore';+import { mockCurrentWorkspace } from '~/testing/mock-data/users';++const INSTANCE_ID = 'useHasReachedAiChatCreditsCapTest';+const THREAD_ID = 'thread-1';++const Wrapper = ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={jotaiStore}>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: INSTANCE_ID }}+ >+ {children}+ </AgentChatComponentInstanceContext.Provider>+ </JotaiProvider>+);++const setThreadError = (error: Error | CombinedGraphQLErrors) => {+ jotaiStore.set(+ agentChatErrorComponentFamilyState.atomFamily({+ instanceId: INSTANCE_ID,+ familyKey: { threadId: THREAD_ID },+ }),+ error,+ );+};++const setWorkspaceCap = (hasReachedCurrentPeriodCap: boolean) => {+ jotaiStore.set(currentWorkspaceState.atom, {+ ...mockCurrentWorkspace,+ currentBillingSubscription: {+ ...mockCurrentWorkspace.currentBillingSubscription,+ billingSubscriptionItems:+ mockCurrentWorkspace.currentBillingSubscription.billingSubscriptionItems.map(+ (billingSubscriptionItem) => ({+ ...billingSubscriptionItem,+ hasReachedCurrentPeriodCap,+ }),+ ),+ },+ });+};++const setWorkspaceWithoutBillingSubscription = () => {+ jotaiStore.set(currentWorkspaceState.atom, {+ ...mockCurrentWorkspace,+ currentBillingSubscription: undefined,+ });+};++const creditsExhaustedError = () =>+ new CombinedGraphQLErrors({+ errors: [+ {+ message: 'Credits exhausted',+ extensions: {+ code: 'FORBIDDEN',+ subCode: 'BILLING_CREDITS_EXHAUSTED',+ },+ },+ ],+ data: null,+ });++const renderHasReachedAiChatCreditsCap = () =>+ renderHook(() => useHasReachedAiChatCreditsCap(), { wrapper: Wrapper });++describe('useHasReachedAiChatCreditsCap', () => {+ beforeEach(() => {+ resetJotaiStore();+ jotaiStore.set(agentChatDisplayedThreadState.atom, THREAD_ID);+ });++ it('should return false when the workspace has credits left and the thread has no error', () => {+ setWorkspaceCap(false);++ const { result } = renderHasReachedAiChatCreditsCap();++ expect(result.current).toBe(false);+ });++ it('should return true when the workspace subscription item reports the cap', () => {+ setWorkspaceCap(true);++ const { result } = renderHasReachedAiChatCreditsCap();++ expect(result.current).toBe(true);+ });++ it('should trust the cleared workspace flag over a leftover thread error after an upgrade', () => {+ setWorkspaceCap(false);+ setThreadError(creditsExhaustedError());++ const { result } = renderHasReachedAiChatCreditsCap();++ expect(result.current).toBe(false);+ });++ it('should fall back to the thread error when the workspace state has no resource credit item', () => {+ setWorkspaceWithoutBillingSubscription();+ setThreadError(creditsExhaustedError());++ const { result } = renderHasReachedAiChatCreditsCap();++ expect(result.current).toBe(true);+ });++ it('should return false for an unrelated thread error when the workspace state has no resource credit item', () => {+ setWorkspaceWithoutBillingSubscription();+ setThreadError(new Error('Thread not found'));++ const { result } = renderHasReachedAiChatCreditsCap();++ expect(result.current).toBe(false);+ });+});diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.tsindex 5830441284e..b2377368a33 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts@@ -35,11 +35,18 @@ import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessimport { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';import { agentChatUploadedFilesState } from '@/ai/states/agentChatUploadedFilesState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';+import {+ markWorkspaceCreditsAvailable,+ markWorkspaceCreditsExhausted,+} from '@/workspace/utils/updateWorkspaceResourceCreditCap';+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';export const useAgentChat = (ensureThreadIdForSend: () => Promise<string | null>,@@ -190,6 +197,19 @@ export const useAgentChat = (},});+ // The stream this send started can exhaust the balance and publish+ // credits-exhausted before this response resolves; that event marks the+ // thread error, so its presence means the exhaustion is newer information+ // than the gate pass this response proves.+ if (+ !isGraphqlErrorOfType(+ store.get(errorAtom),+ AiChatErrorCode.BILLING_CREDITS_EXHAUSTED,+ )+ ) {+ store.set(currentWorkspaceState.atom, markWorkspaceCreditsAvailable);+ }+if (isBrowsingContextChanged) {store.set(lastSentBrowsingContextAtom, browsingContext);}@@ -239,6 +259,12 @@ export const useAgentChat = (: new Error('An unexpected error occurred'),);+ if (+ isGraphqlErrorOfType(error, AiChatErrorCode.BILLING_CREDITS_EXHAUSTED)+ ) {+ store.set(currentWorkspaceState.atom, markWorkspaceCreditsExhausted);+ }+dispatchBrowserEvent(AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME, {content: serializedContentToSend,});diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.tsindex baef01b7232..ec2b25e204b 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts@@ -31,7 +31,7 @@ import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEventimport { sseClientState } from '@/sse-db-event/states/sseClientState';import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';-import { BillingProductKey } from '~/generated-metadata/graphql';+import { markWorkspaceCreditsExhausted } from '@/workspace/utils/updateWorkspaceResourceCreditCap';const THROTTLE_MS = 100;@@ -377,33 +377,7 @@ export const useAgentChatSubscription = (threadId: string | null) => {case 'credits-exhausted': {//TODO : add real time on currentUser- store.set(currentWorkspaceState.atom, (currentWorkspace) => {- const currentBillingSubscription =- currentWorkspace?.currentBillingSubscription;- const billingSubscriptionItems =- currentBillingSubscription?.billingSubscriptionItems;-- if (- !isDefined(currentWorkspace) ||- !isDefined(currentBillingSubscription) ||- !isDefined(billingSubscriptionItems)- ) {- return currentWorkspace;- }-- return {- ...currentWorkspace,- currentBillingSubscription: {- ...currentBillingSubscription,- billingSubscriptionItems: billingSubscriptionItems.map((item) =>- item.billingProduct.metadata?.['productKey'] ===- BillingProductKey.RESOURCE_CREDIT- ? { ...item, hasReachedCurrentPeriodCap: true }- : item,- ),- },- };- });+ store.set(currentWorkspaceState.atom, markWorkspaceCreditsExhausted);store.set(errorAtom,diff --git a/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts b/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.tsnew file mode 100644index 00000000000..b8f4f8b2814--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts@@ -0,0 +1,48 @@+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';+import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';+import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { hasReachedCurrentBillingPeriodCapSelector } from '@/workspace/states/hasReachedCurrentBillingPeriodCapSelector';+import { isResourceCreditSubscriptionItem } from '@/workspace/utils/isResourceCreditSubscriptionItem';+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';++// The credits exhausted error renders nothing on its own, so the banner must+// mount whenever the workspace is refused for lack of credits. The resource+// credit item's flag is the authoritative signal: a refused send marks it, an+// upgrade or a successful send clears it. The thread error only stands in when+// client state carries no resource credit item to hold the flag; when the item+// exists, trusting a leftover error would keep the banner up after an upgrade.+export const useHasReachedAiChatCreditsCap = () => {+ const hasReachedCurrentBillingPeriodCap = useAtomStateValue(+ hasReachedCurrentBillingPeriodCapSelector,+ );+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);++ const agentChatDisplayedThread = useAtomStateValue(+ agentChatDisplayedThreadState,+ );+ const agentChatError = useAtomComponentFamilyStateValue(+ agentChatErrorComponentFamilyState,+ { threadId: agentChatDisplayedThread },+ );++ if (hasReachedCurrentBillingPeriodCap) {+ return true;+ }++ const hasResourceCreditSubscriptionItem =+ currentWorkspace?.currentBillingSubscription?.billingSubscriptionItems?.some(+ isResourceCreditSubscriptionItem,+ ) ?? false;++ if (hasResourceCreditSubscriptionItem) {+ return false;+ }++ return isGraphqlErrorOfType(+ agentChatError,+ AiChatErrorCode.BILLING_CREDITS_EXHAUSTED,+ );+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts b/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.tsindex 3ded9733a0f..acfb8458d95 100644--- a/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts@@ -10,7 +10,14 @@ import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';+import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';+import {+ markWorkspaceCreditsAvailable,+ markWorkspaceCreditsExhausted,+} from '@/workspace/utils/updateWorkspaceResourceCreditCap';+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';export const useRetryChatMessage = () => {const apolloClient = useApolloClient();@@ -47,6 +54,18 @@ export const useRetryChatMessage = () => {},});+ // Same ordering guard as useAgentChat: a credits-exhausted event from+ // the stream this retry started may already have marked the thread error+ // before this response resolves, and that exhaustion is newer truth.+ if (+ !isGraphqlErrorOfType(+ store.get(errorAtom),+ AiChatErrorCode.BILLING_CREDITS_EXHAUSTED,+ )+ ) {+ store.set(currentWorkspaceState.atom, markWorkspaceCreditsAvailable);+ }+dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);} catch (retryError) {store.set(isAwaitingFirstChunkAtom, false);@@ -54,6 +73,15 @@ export const useRetryChatMessage = () => {errorAtom,retryError instanceof Error ? retryError : previousError,);++ if (+ isGraphqlErrorOfType(+ retryError,+ AiChatErrorCode.BILLING_CREDITS_EXHAUSTED,+ )+ ) {+ store.set(currentWorkspaceState.atom, markWorkspaceCreditsExhausted);+ }}}, [apolloClient, store, modelIdForRequest]);diff --git a/packages/twenty-front/src/modules/workspace/utils/isResourceCreditSubscriptionItem.ts b/packages/twenty-front/src/modules/workspace/utils/isResourceCreditSubscriptionItem.tsnew file mode 100644index 00000000000..8b5f73b6188--- /dev/null+++ b/packages/twenty-front/src/modules/workspace/utils/isResourceCreditSubscriptionItem.ts@@ -0,0 +1,14 @@+import { type CurrentWorkspace } from '@/auth/states/currentWorkspaceState';+import { BillingProductKey } from '~/generated-metadata/graphql';++type CurrentWorkspaceBillingSubscriptionItem = NonNullable<+ NonNullable<+ CurrentWorkspace['currentBillingSubscription']+ >['billingSubscriptionItems']+>[number];++export const isResourceCreditSubscriptionItem = (+ billingSubscriptionItem: CurrentWorkspaceBillingSubscriptionItem,+): boolean =>+ billingSubscriptionItem.billingProduct.metadata?.['productKey'] ===+ BillingProductKey.RESOURCE_CREDIT;diff --git a/packages/twenty-front/src/modules/workspace/utils/updateWorkspaceResourceCreditCap.ts b/packages/twenty-front/src/modules/workspace/utils/updateWorkspaceResourceCreditCap.tsnew file mode 100644index 00000000000..8fafe43cf50--- /dev/null+++ b/packages/twenty-front/src/modules/workspace/utils/updateWorkspaceResourceCreditCap.ts@@ -0,0 +1,46 @@+import { type CurrentWorkspace } from '@/auth/states/currentWorkspaceState';+import { isResourceCreditSubscriptionItem } from '@/workspace/utils/isResourceCreditSubscriptionItem';+import { isDefined } from 'twenty-shared/utils';++const updateWorkspaceResourceCreditCap = (+ currentWorkspace: CurrentWorkspace | null,+ hasReachedCurrentPeriodCap: boolean,+): CurrentWorkspace | null => {+ const currentBillingSubscription =+ currentWorkspace?.currentBillingSubscription;+ const billingSubscriptionItems =+ currentBillingSubscription?.billingSubscriptionItems;++ if (+ !isDefined(currentWorkspace) ||+ !isDefined(currentBillingSubscription) ||+ !isDefined(billingSubscriptionItems)+ ) {+ return currentWorkspace;+ }++ return {+ ...currentWorkspace,+ currentBillingSubscription: {+ ...currentBillingSubscription,+ billingSubscriptionItems: billingSubscriptionItems.map((item) =>+ isResourceCreditSubscriptionItem(item)+ ? { ...item, hasReachedCurrentPeriodCap }+ : item,+ ),+ },+ };+};++export const markWorkspaceCreditsExhausted = (+ currentWorkspace: CurrentWorkspace | null,+): CurrentWorkspace | null =>+ updateWorkspaceResourceCreditCap(currentWorkspace, true);++// The optimistic inverse of markWorkspaceCreditsExhausted: a send that passed+// the server credit gate proves credits are available right now, which is the+// only client-side signal after an external top-up while the app stays open.+export const markWorkspaceCreditsAvailable = (+ currentWorkspace: CurrentWorkspace | null,+): CurrentWorkspace | null =>+ updateWorkspaceResourceCreditCap(currentWorkspace, false);diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.tsindex 3f2f6e0ba56..36ab9628017 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts@@ -15,7 +15,6 @@ import {BillingExceptionCode,} from 'src/engine/core-modules/billing/billing.exception';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';-import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { BillingWebhookEvent } from 'src/engine/core-modules/billing/enums/billing-webhook-events.enum';import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';@@ -34,8 +33,6 @@ export class BillingWebhookInvoiceService {protected readonly logger = new Logger(BillingWebhookInvoiceService.name);constructor(- @InjectRepository(BillingSubscriptionItemEntity)- private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItemEntity>,// Stripe webhook: workspace discovered from BillingCustomer by stripeCustomerId.// eslint-disable-next-line twenty/prefer-workspace-scoped-repository@InjectRepository(BillingCustomerEntity)@@ -87,11 +84,6 @@ export class BillingWebhookInvoiceService {return;}- await this.billingSubscriptionItemRepository.update(- { stripeSubscriptionId },- { hasReachedCurrentPeriodCap: false },- );-if (!isDefined(stripeCustomerId) || !periodEnd || !periodStart) {return;}diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.tsnew file mode 100644index 00000000000..31ec846e6d3--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts@@ -0,0 +1,81 @@+/* @license Enterprise */++import { Logger, UseFilters, UsePipes } from '@nestjs/common';+import { Parent, ResolveField } from '@nestjs/graphql';+import { InjectRepository } from '@nestjs/typeorm';++import { isDefined } from 'twenty-shared/utils';+import { Repository } from 'typeorm';++import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';+import { BillingSubscriptionItemDTO } from 'src/engine/core-modules/billing/dtos/billing-subscription-item.dto';+import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';+import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';+import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';++@MetadataResolver(() => BillingSubscriptionItemDTO)+@UsePipes(ResolverValidationPipe)+@UseFilters(PreventNestToAutoLogGraphqlErrorsFilter)+export class BillingSubscriptionItemResolver {+ private readonly logger = new Logger(BillingSubscriptionItemResolver.name);++ constructor(+ private readonly billingUsageService: BillingUsageService,+ // Field resolver: the workspace is discovered from the parent item's+ // subscription row, so it cannot be an input here.+ // eslint-disable-next-line twenty/prefer-workspace-scoped-repository+ @InjectRepository(BillingSubscriptionEntity)+ private readonly billingSubscriptionRepository: Repository<BillingSubscriptionEntity>,+ ) {}++ // Derived from the live credit balance instead of read from the stored+ // column: a persisted flag that every balance-mutating path must remember to+ // sync drifts as soon as one path misses, and a workspace stuck with a stale+ // flag gets refused with no banner explaining why.+ @ResolveField(() => Boolean)+ async hasReachedCurrentPeriodCap(+ @Parent() billingSubscriptionItem: BillingSubscriptionItemEntity,+ ): Promise<boolean> {+ if (+ billingSubscriptionItem.billingProduct?.metadata?.productKey !==+ BillingProductKey.RESOURCE_CREDIT+ ) {+ return false;+ }++ // This field rides on the currentWorkspace query, which is app boot: a+ // billing read failure (stale period right after a rollover, ClickHouse or+ // Redis unavailable) must degrade to "no banner", never fail the query.+ // Failing open matches the usage gate, whose availability checks also fail+ // open so telemetry never blocks a paying customer.+ try {+ const billingSubscription =+ await this.billingSubscriptionRepository.findOne({+ where: { id: billingSubscriptionItem.billingSubscriptionId },+ });++ if (!isDefined(billingSubscription)) {+ return false;+ }++ const creditAvailability =+ await this.billingUsageService.getCreditAvailability(+ billingSubscription.workspaceId,+ );++ return (+ !creditAvailability.hasAvailableCredits &&+ creditAvailability.reason === 'no-credits'+ );+ } catch (error) {+ this.logger.warn(+ `Failed to derive hasReachedCurrentPeriodCap for billing subscription item ${billingSubscriptionItem.id}: ${error instanceof Error ? error.message : String(error)}`,+ );++ return false;+ }+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.module.tsindex 854908f9f96..cd4868a7977 100644--- a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts@@ -7,6 +7,7 @@ import { ClickHouseModule } from 'src/database/clickHouse/clickHouse.module';import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';import { CoreEntityCacheModule } from 'src/engine/core-entity-cache/core-entity-cache.module';import { BillingGaugeService } from 'src/engine/core-modules/billing/billing-gauge.service';+import { BillingSubscriptionItemResolver } from 'src/engine/core-modules/billing/billing-subscription-item.resolver';import { BillingResolver } from 'src/engine/core-modules/billing/billing.resolver';import { BillingSyncCustomerDataCommand } from 'src/engine/core-modules/billing/commands/billing-sync-customer-data.command';import { BillingSyncPlansDataCommand } from 'src/engine/core-modules/billing/commands/billing-sync-plans-data.command';@@ -33,7 +34,6 @@ import { BillingSubscriptionPhaseService } from 'src/engine/core-modules/billingimport { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';-import { BillingUsageCapService } from 'src/engine/core-modules/billing/services/billing-usage-cap.service';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';import { ResourceCreditService } from 'src/engine/core-modules/billing/services/resource-credit.service';@@ -88,6 +88,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingProductService,BillingSubscriptionPhaseService,BillingResolver,+ BillingSubscriptionItemResolver,BillingPlanService,BillingWorkspaceMemberListener,BillingService,@@ -97,7 +98,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingSyncPlansDataCommand,BillingUsageService,BillingUsageCacheService,- BillingUsageCapService,BillingPriceService,BillingCreditRolloverService,BillingCreditGrantService,@@ -119,7 +119,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingService,BillingUsageService,BillingUsageCacheService,- BillingUsageCapService,BillingCreditRolloverService,BillingCreditGrantService,BillingCreditService,diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription-item.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription-item.entity.tsindex 663ad541e24..53dede8117e 100644--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription-item.entity.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription-item.entity.ts@@ -74,6 +74,9 @@ export class BillingSubscriptionItemEntity {@Column({ nullable: true, type: 'numeric' })quantity: number | null;+ // No longer read or written: the GraphQL field of the same name is derived+ // from the live credit balance in BillingSubscriptionItemResolver. Kept so a+ // deploy rollback still runs; drop in a follow-up migration.@Column({ type: 'boolean', default: false })hasReachedCurrentPeriodCap: boolean;}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.tsindex aebc9f3b0b3..092ca7614d6 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts@@ -165,7 +165,6 @@ export class BillingCreditRolloverService {await this.billingCreditService.refreshWorkspaceCreditState({workspaceId,availableDeltaMicro: carriedForwardMicro,- addsCredits: true,isReplay: hasReplayedGrant,adjustmentKey: buildRolloverAdjustmentKey(nextPeriodStart),});diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.tsindex b44bb602bdd..b574db2334f 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts@@ -12,7 +12,6 @@ import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enuimport { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';-import { BillingUsageCapService } from 'src/engine/core-modules/billing/services/billing-usage-cap.service';import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';import { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';@@ -47,7 +46,6 @@ export class BillingCreditService {private readonly billingCreditGrantService: BillingCreditGrantService,private readonly billingSubscriptionService: BillingSubscriptionService,private readonly billingUsageCacheService: BillingUsageCacheService,- private readonly billingUsageCapService: BillingUsageCapService,private readonly cacheLockService: CacheLockService,private readonly workspaceCacheService: WorkspaceCacheService,@InjectWorkspaceScopedRepository(BillingCustomerEntity)@@ -120,12 +118,10 @@ export class BillingCreditService {// usage ClickHouse has not ingested yet, and that value then stands for// the period. Accepted here because the alternative is a grant that// stays invisible for the whole period, and erring high is the direction- // the grant intended. The cap is left to be derived from the rebuilt- // balance, since the replayed grant may since have been revoked.+ // the grant intended.await this.refreshWorkspaceCreditState({workspaceId,availableDeltaMicro: 0,- addsCredits: true,isReplay: true,subscription,});@@ -136,7 +132,6 @@ export class BillingCreditService {await this.refreshWorkspaceCreditState({workspaceId,availableDeltaMicro: amountMicro,- addsCredits: true,subscription,});@@ -194,7 +189,6 @@ export class BillingCreditService {await this.refreshWorkspaceCreditState({workspaceId,availableDeltaMicro: 0,- addsCredits: false,isReplay: true,adjustmentKey,});@@ -215,7 +209,6 @@ export class BillingCreditService {await this.refreshWorkspaceCreditState({workspaceId,availableDeltaMicro: wasActiveWhenRevoked ? -grant.amountMicro : 0,- addsCredits: false,adjustmentKey,});@@ -262,25 +255,20 @@ export class BillingCreditService {}// Keeps everything that reads a credit balance consistent with the ledger:- // the mirror column, the Redis counter that gates usage, the flag that drives- // the "no more credits" banner, and the cached subscription the front reads.- // Public so a caller writing several grants at once pays for this once; such- // a caller must hold buildBillingCreditStateLockKey for its own ledger writes- // and this refresh together, which is why this does not take the lock itself.+ // the mirror column, the Redis counter that gates usage, and the cached+ // subscription the front reads. Public so a caller writing several grants at+ // once pays for this once; such a caller must hold+ // buildBillingCreditStateLockKey for its own ledger writes and this refresh+ // together, which is why this does not take the lock itself.async refreshWorkspaceCreditState({workspaceId,availableDeltaMicro,- addsCredits,isReplay = false,adjustmentKey,subscription: knownSubscription,}: {workspaceId: string;availableDeltaMicro: number;- // Whether the write that led here could have made credits spendable. Only- // the caller knows: a replay of either a grant or a revocation carries a- // delta of zero, and the sign cannot tell them apart.- addsCredits: boolean;// A replay cannot know how far the original attempt got, so the counter is// recomputed from the ledger unless adjustmentKey says it already moved.isReplay?: boolean;@@ -289,7 +277,7 @@ export class BillingCreditService {// Saves a re-read for a caller that already has it in hand.subscription?: BillingSubscriptionEntity;}): Promise<void> {- const activeCreditsMicro = await this.syncMirrorBalance(workspaceId);+ await this.syncMirrorBalance(workspaceId);const subscription =knownSubscription ??@@ -315,7 +303,7 @@ export class BillingCreditService {adjustmentKey,)));- const counterAfterWriteMicro = await this.applyCounterWrite({+ await this.applyCounterWrite({workspaceId,periodStart,availableDeltaMicro,@@ -330,27 +318,9 @@ export class BillingCreditService {);}- // The banner may only come down when this write actually put something- // spendable in front of the workspace: the caller says whether it could,- // the counter says whether it did, and what is left decides. A replay that- // finds the counter already moved did nothing, and its grants may well- // have been spent since, so it leaves the banner alone, while a replay- // that rebuilt the counter is the repair that lifts it.- //- // With no counter to speak for the workspace the ledger stands in, which- // ignores usage. Erring towards lifting the banner is deliberate there:- // the counter is cold exactly after a period transition or a cache flush,- // which is when grants land, and leaving it up would hide credits someone- // deliberately gave for the rest of the period.- const spendableAfterWriteMicro =- counterAfterWriteMicro ?? activeCreditsMicro;-- return this.clearCapAndSubscriptionCache(workspaceId, {- shouldClearCap:- addsCredits &&- spendableAfterWriteMicro > 0 &&- (rebuildCounter || availableDeltaMicro > 0),- });+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [+ 'currentBillingSubscription',+ ]);}// Returns what the counter holds afterwards, or null when there is no warm@@ -403,21 +373,6 @@ export class BillingCreditService {return cachedAvailableCredits + availableDeltaMicro;}-- private async clearCapAndSubscriptionCache(- workspaceId: string,- { shouldClearCap }: { shouldClearCap: boolean },- ): Promise<void> {- if (shouldClearCap) {- await this.billingUsageCapService.clearHasReachedCapForWorkspace(- workspaceId,- );- }-- await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [- 'currentBillingSubscription',- ]);- }}// Scopes the completion marker to one revocation, so retrying it is the onlydiff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-update.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-update.service.tsindex 97f1d14e9e7..c39678b77d0 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-update.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-update.service.ts@@ -15,7 +15,6 @@ import type Stripe from 'stripe';import { billingValidator } from 'src/engine/core-modules/billing/billing.validate';import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';-import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';@@ -57,8 +56,6 @@ export class BillingSubscriptionUpdateService {private readonly billingProductService: BillingProductService,@InjectRepository(BillingPriceEntity)private readonly billingPriceRepository: Repository<BillingPriceEntity>,- @InjectRepository(BillingSubscriptionItemEntity)- private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItemEntity>,@InjectWorkspaceScopedRepository(BillingSubscriptionEntity)private readonly billingSubscriptionRepository: WorkspaceScopedRepository<BillingSubscriptionEntity>,private readonly stripeSubscriptionScheduleService: StripeSubscriptionScheduleService,@@ -301,13 +298,6 @@ export class BillingSubscriptionUpdateService {...subscriptionOptions,});- if (subscriptionUpdate.type !== SubscriptionUpdateType.SEATS) {- await this.billingSubscriptionItemRepository.update(- { stripeSubscriptionId: subscription.stripeSubscriptionId },- { hasReachedCurrentPeriodCap: false },- );- }-if (isDefined(nextPhase)) {assertIsDefinedOrThrow(schedule);const { currentPhase: refreshedCurrentPhase } =diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.tsindex 9f5c764d80d..a7c1cfd315f 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts@@ -294,11 +294,6 @@ export class BillingSubscriptionService {updatedSubscription.id,);- await this.billingSubscriptionItemRepository.update(- { stripeSubscriptionId: updatedSubscription.id },- { hasReachedCurrentPeriodCap: false },- );-await this.billingUsageCacheService.flushAvailableCredits(workspace.id);await this.workspaceCacheService.invalidateAndRecompute(workspace.id, [diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cap.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cap.service.tsdeleted file mode 100644index 9cfcb372eb3..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cap.service.ts+++ /dev/null@@ -1,79 +0,0 @@-/* @license Enterprise */--import { Injectable } from '@nestjs/common';-import { InjectRepository } from '@nestjs/typeorm';--import { In, Not, Raw, Repository } from 'typeorm';--import {- BillingException,- BillingExceptionCode,-} from 'src/engine/core-modules/billing/billing.exception';-import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';-import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';-import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';--@Injectable()-export class BillingUsageCapService {- constructor(- @InjectRepository(BillingSubscriptionItemEntity)- private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItemEntity>,- ) {}-- async setSubscriptionItemHasReachedCap(- workspaceId: string,- hasReachedCap: boolean,- ): Promise<void> {- const billingSubscriptionItems =- await this.findResourceCreditSubscriptionItems(workspaceId);-- if (billingSubscriptionItems.length !== 1) {- throw new BillingException(- `Expected 1 billing subscription item for workspace ${workspaceId}, but got ${billingSubscriptionItems.length}`,- BillingExceptionCode.BILLING_SUBSCRIPTION_ITEM_NOT_FOUND,- );- }-- await this.billingSubscriptionItemRepository.update(- { id: billingSubscriptionItems[0].id },- { hasReachedCurrentPeriodCap: hasReachedCap },- );- }-- // Lifting the cap must never fail the operation that granted the credits, so- // unlike setSubscriptionItemHasReachedCap this tolerates a workspace with no- // resource credit item.- async clearHasReachedCapForWorkspace(workspaceId: string): Promise<void> {- const billingSubscriptionItems =- await this.findResourceCreditSubscriptionItems(workspaceId);-- if (billingSubscriptionItems.length === 0) {- return;- }-- await this.billingSubscriptionItemRepository.update(- { id: In(billingSubscriptionItems.map((item) => item.id)) },- { hasReachedCurrentPeriodCap: false },- );- }-- private async findResourceCreditSubscriptionItems(- workspaceId: string,- ): Promise<BillingSubscriptionItemEntity[]> {- return this.billingSubscriptionItemRepository.find({- where: {- billingSubscription: {- workspaceId,- status: Not(SubscriptionStatus.Canceled),- },- billingProduct: {- metadata: Raw((alias) => `${alias} @> :metadata::jsonb`, {- metadata: JSON.stringify({- productKey: BillingProductKey.RESOURCE_CREDIT,- }),- }),- },- },- });- }-}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.tsindex 91b14b9cb82..91af87b5f77 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts@@ -21,7 +21,6 @@ import { BillingCreditGrantService } from 'src/engine/core-modules/billing/serviimport { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';-import { BillingUsageCapService } from 'src/engine/core-modules/billing/services/billing-usage-cap.service';import { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';@@ -50,6 +49,13 @@ type ResolvedAvailableCredits = {isCounterWarm: boolean;};+export type CreditAvailability =+ | { hasAvailableCredits: true }+ | {+ hasAvailableCredits: false;+ reason: 'workspace-suspended' | 'no-subscription' | 'no-credits';+ };+// This gate runs before every credit-consuming execution, so it waits far less// than a writer does and falls back to computing unlocked rather than failing// the execution outright.@@ -72,7 +78,6 @@ export class BillingUsageService {private readonly billingSubscriptionRepository: WorkspaceScopedRepository<BillingSubscriptionEntity>,private readonly workspaceCacheService: WorkspaceCacheService,private readonly clickHouseService: ClickHouseService,- private readonly billingUsageCapService: BillingUsageCapService,private readonly cacheLockService: CacheLockService,private readonly coreEntityCacheService: CoreEntityCacheService,) {}@@ -264,25 +269,13 @@ export class BillingUsageService {// that may predate it: incrementing an absent key would install// -usedCredits as the whole balance. Compute this turn locally instead and// let the next read rebuild once the marker lapses.- const decrementedAvailableCredits = isCounterWarm+ return isCounterWarm? await this.billingUsageCacheService.adjustAvailableCredits(workspaceId,currentPeriodStart,-usedCredits,): availableCredits - usedCredits;-- const hasJustReachedCap =- availableCredits > 0 && decrementedAvailableCredits <= 0;-- if (hasJustReachedCap) {- await this.billingUsageCapService.setSubscriptionItemHasReachedCap(- workspaceId,- true,- );- }-- return decrementedAvailableCredits;}// Warming is a read of the ledger followed by a write of what it implies, so@@ -363,9 +356,11 @@ export class BillingUsageService {return { availableCredits, isCounterWarm: true };}- async hasAvailableCredits(workspaceId: string): Promise<boolean> {+ async getCreditAvailability(+ workspaceId: string,+ ): Promise<CreditAvailability> {if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {- return true;+ return { hasAvailableCredits: true };}const workspace = await this.coreEntityCacheService.get(@@ -377,7 +372,7 @@ export class BillingUsageService {isDefined(workspace) &&workspace.activationStatus === WorkspaceActivationStatus.SUSPENDED) {- return false;+ return { hasAvailableCredits: false, reason: 'workspace-suspended' };}const { currentBillingSubscription } =@@ -386,7 +381,7 @@ export class BillingUsageService {]);if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {- return false;+ return { hasAvailableCredits: false, reason: 'no-subscription' };}const subscription = currentBillingSubscription;@@ -397,7 +392,16 @@ export class BillingUsageService {currentPeriodEnd: subscription.currentPeriodEnd,});- return availableCredits > 0;+ return availableCredits > 0+ ? { hasAvailableCredits: true }+ : { hasAvailableCredits: false, reason: 'no-credits' };+ }++ async hasAvailableCredits(workspaceId: string): Promise<boolean> {+ const { hasAvailableCredits } =+ await this.getCreditAvailability(workspaceId);++ return hasAvailableCredits;}async hasAvailableCreditsOrThrow(workspaceId: string): Promise<void> {