Skip to content

The open alternative to Salesforce, designed for AI.

[BREAKING_CHANGE] feat(usage): spend user credits on AI chat and web search before workspace credits (server) (#27944)

Etienne664899f1a275
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 1eb12efc6ae..2bb2686ae5f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -745,6 +745,7 @@ type Billing {
type BillingCustomer {
hasPaymentMethod: Boolean
id: UUID!
+ userCreditsFallback: UserCreditsFallback!
}
type BillingEndTrialPeriod {
@@ -870,14 +871,15 @@ type BillingProductMetadata {
}
type BillingResourceCreditUsage {
- grantedCredits: Float!
periodEnd: DateTime!
periodStart: DateTime!
productKey: BillingProductKey!
- rolloverCredits: Float!
- totalGrantedCredits: Float!
unitPriceCents: Float!
- usedCredits: Float!
+ userCreditsUsed: Float!
+ workspaceCreditsExtraGranted: Float!
+ workspaceCreditsGranted: Float!
+ workspaceCreditsTotalGranted: Float!
+ workspaceCreditsUsed: Float!
}
type BillingSession {
@@ -3227,6 +3229,7 @@ type Mutation {
updateTimelineActivityType(input: UpdateTimelineActivityTypeInput!): TimelineActivityType!
updateUnsubscribeTopic(input: UpdateUnsubscribeTopicInput!): UnsubscribeTopic!
updateUsageLimit(input: UpdateUsageLimitInput!): UsageLimit!
+ updateUserCreditsFallback(userCreditsFallback: UserCreditsFallback!): BillingCustomer!
updateUserEmail(newEmail: String!, verifyEmailRedirectPath: String): Boolean!
updateValidationRule(input: UpdateValidationRuleInput!): ValidationRule!
updateView(id: String!, input: UpdateViewInput!): View!
@@ -5306,6 +5309,8 @@ type UsageBreakdownItem {
creditsUsed: Float!
key: String!
label: String
+ userCreditsUsed: Float!
+ workspaceCreditsUsed: Float!
}
type UsageLimit {
@@ -5332,6 +5337,7 @@ type UsageLimitOperationDefinition {
enum UsageOperationType {
AI_CHAT_TOKEN
AI_WORKFLOW_TOKEN
+ AI_WORKFLOW_WEB_SEARCH
ALL
API_REQUEST
CALL_RECORDING
@@ -5415,6 +5421,7 @@ enum UsageResourceType {
type UsageTimeSeries {
creditsUsed: Float!
date: String!
+ workspaceCreditsUsed: Float!
}
enum UsageUnit {
@@ -5429,6 +5436,7 @@ enum UsageUnit {
REQUEST
SEAT
TOKEN
+ USER_CREDIT
}
type UsageUserDaily {
@@ -5477,6 +5485,11 @@ type UserApplicationVariableValue {
value: String!
}
+enum UserCreditsFallback {
+ STOP
+ WORKSPACE_CREDITS
+}
+
type UserSession {
authProvider: String!
createdAt: DateTime!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 845804912ee..989b6b11fed 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -660,6 +660,7 @@ export interface Billing {
export interface BillingCustomer {
hasPaymentMethod?: Scalars['Boolean']
id: Scalars['UUID']
+ userCreditsFallback: UserCreditsFallback
__typename: 'BillingCustomer'
}
@@ -772,14 +773,15 @@ export interface BillingProductMetadata {
}
export interface BillingResourceCreditUsage {
- grantedCredits: Scalars['Float']
periodEnd: Scalars['DateTime']
periodStart: Scalars['DateTime']
productKey: BillingProductKey
- rolloverCredits: Scalars['Float']
- totalGrantedCredits: Scalars['Float']
unitPriceCents: Scalars['Float']
- usedCredits: Scalars['Float']
+ userCreditsUsed: Scalars['Float']
+ workspaceCreditsExtraGranted: Scalars['Float']
+ workspaceCreditsGranted: Scalars['Float']
+ workspaceCreditsTotalGranted: Scalars['Float']
+ workspaceCreditsUsed: Scalars['Float']
__typename: 'BillingResourceCreditUsage'
}
@@ -2272,6 +2274,7 @@ export interface Mutation {
updateTimelineActivityType: TimelineActivityType
updateUnsubscribeTopic: UnsubscribeTopic
updateUsageLimit: UsageLimit
+ updateUserCreditsFallback: BillingCustomer
updateUserEmail: Scalars['Boolean']
updateValidationRule: ValidationRule
updateView: View
@@ -3393,6 +3396,8 @@ export interface UsageBreakdownItem {
creditsUsed: Scalars['Float']
key: Scalars['String']
label?: Scalars['String']
+ userCreditsUsed: Scalars['Float']
+ workspaceCreditsUsed: Scalars['Float']
__typename: 'UsageBreakdownItem'
}
@@ -3419,7 +3424,7 @@ export interface UsageLimitOperationDefinition {
__typename: 'UsageLimitOperationDefinition'
}
-export type UsageOperationType = 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'ALL' | 'API_REQUEST' | 'CALL_RECORDING' | 'CODE_EXECUTION' | 'EMAIL_SEND' | 'MESSAGE_CAMPAIGN_SEND' | 'RECORD_WRITE' | 'STORAGE_FILE' | 'SUBSCRIPTION' | 'WEBHOOK_CALL' | 'WEB_SEARCH' | 'WORKFLOW_EXECUTION'
+export type UsageOperationType = 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'AI_WORKFLOW_WEB_SEARCH' | 'ALL' | 'API_REQUEST' | 'CALL_RECORDING' | 'CODE_EXECUTION' | 'EMAIL_SEND' | 'MESSAGE_CAMPAIGN_SEND' | 'RECORD_WRITE' | 'STORAGE_FILE' | 'SUBSCRIPTION' | 'WEBHOOK_CALL' | 'WEB_SEARCH' | 'WORKFLOW_EXECUTION'
export interface UsageQuotaDefinition {
allowedOperations: UsageLimitOperationDefinition[]
@@ -3475,10 +3480,11 @@ export type UsageResourceType = 'AI' | 'ALL' | 'API' | 'APP' | 'EMAIL' | 'LOGIC_
export interface UsageTimeSeries {
creditsUsed: Scalars['Float']
date: Scalars['String']
+ workspaceCreditsUsed: Scalars['Float']
__typename: 'UsageTimeSeries'
}
-export type UsageUnit = 'BYTE' | 'COMPLEXITY' | 'CREDIT' | 'FILE' | 'INVOCATION' | 'MILLISECOND' | 'MINUTE' | 'RECORD' | 'REQUEST' | 'SEAT' | 'TOKEN'
+export type UsageUnit = 'BYTE' | 'COMPLEXITY' | 'CREDIT' | 'FILE' | 'INVOCATION' | 'MILLISECOND' | 'MINUTE' | 'RECORD' | 'REQUEST' | 'SEAT' | 'TOKEN' | 'USER_CREDIT'
export interface UsageUserDaily {
dailyUsage: UsageTimeSeries[]
@@ -3529,6 +3535,8 @@ export interface UserApplicationVariableValue {
__typename: 'UserApplicationVariableValue'
}
+export type UserCreditsFallback = 'STOP' | 'WORKSPACE_CREDITS'
+
export interface UserSession {
authProvider: Scalars['String']
createdAt: Scalars['DateTime']
@@ -4649,6 +4657,7 @@ export interface BillingGenqlSelection{
export interface BillingCustomerGenqlSelection{
hasPaymentMethod?: boolean | number
id?: boolean | number
+ userCreditsFallback?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -4772,14 +4781,15 @@ export interface BillingProductMetadataGenqlSelection{
}
export interface BillingResourceCreditUsageGenqlSelection{
- grantedCredits?: boolean | number
periodEnd?: boolean | number
periodStart?: boolean | number
productKey?: boolean | number
- rolloverCredits?: boolean | number
- totalGrantedCredits?: boolean | number
unitPriceCents?: boolean | number
- usedCredits?: boolean | number
+ userCreditsUsed?: boolean | number
+ workspaceCreditsExtraGranted?: boolean | number
+ workspaceCreditsGranted?: boolean | number
+ workspaceCreditsTotalGranted?: boolean | number
+ workspaceCreditsUsed?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -6501,6 +6511,7 @@ export interface MutationGenqlSelection{
updateTimelineActivityType?: (TimelineActivityTypeGenqlSelection & { __args: {input: UpdateTimelineActivityTypeInput} })
updateUnsubscribeTopic?: (UnsubscribeTopicGenqlSelection & { __args: {input: UpdateUnsubscribeTopicInput} })
updateUsageLimit?: (UsageLimitGenqlSelection & { __args: {input: UpdateUsageLimitInput} })
+ updateUserCreditsFallback?: (BillingCustomerGenqlSelection & { __args: {userCreditsFallback: UserCreditsFallback} })
updateUserEmail?: { __args: {newEmail: Scalars['String'], verifyEmailRedirectPath?: (Scalars['String'] | null)} }
updateValidationRule?: (ValidationRuleGenqlSelection & { __args: {input: UpdateValidationRuleInput} })
updateView?: (ViewGenqlSelection & { __args: {id: Scalars['String'], input: UpdateViewInput} })
@@ -7971,6 +7982,8 @@ export interface UsageBreakdownItemGenqlSelection{
creditsUsed?: boolean | number
key?: boolean | number
label?: boolean | number
+ userCreditsUsed?: boolean | number
+ workspaceCreditsUsed?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -8059,6 +8072,7 @@ export interface UsageQuotaWithConsumptionGenqlSelection{
export interface UsageTimeSeriesGenqlSelection{
creditsUsed?: boolean | number
date?: boolean | number
+ workspaceCreditsUsed?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -11994,6 +12008,7 @@ export const enumUnsubscribeTopicVisibility = {
export const enumUsageOperationType = {
AI_CHAT_TOKEN: 'AI_CHAT_TOKEN' as const,
AI_WORKFLOW_TOKEN: 'AI_WORKFLOW_TOKEN' as const,
+ AI_WORKFLOW_WEB_SEARCH: 'AI_WORKFLOW_WEB_SEARCH' as const,
ALL: 'ALL' as const,
API_REQUEST: 'API_REQUEST' as const,
CALL_RECORDING: 'CALL_RECORDING' as const,
@@ -12032,7 +12047,13 @@ export const enumUsageUnit = {
RECORD: 'RECORD' as const,
REQUEST: 'REQUEST' as const,
SEAT: 'SEAT' as const,
- TOKEN: 'TOKEN' as const
+ TOKEN: 'TOKEN' as const,
+ USER_CREDIT: 'USER_CREDIT' as const
+}
+
+export const enumUserCreditsFallback = {
+ STOP: 'STOP' as const,
+ WORKSPACE_CREDITS: 'WORKSPACE_CREDITS' as const
}
export const enumViewCalendarLayout = {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index f48fe6777ea..33cc57eda96 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -99,24 +99,25 @@ export default {
578,
585,
587,
- 601,
- 607,
+ 591,
+ 602,
608,
- 610,
+ 609,
611,
- 613,
+ 612,
614,
615,
- 618,
+ 616,
619,
- 624,
- 626,
- 629,
- 634,
+ 620,
+ 625,
+ 627,
+ 630,
635,
636,
- 639,
- 640
+ 637,
+ 640,
+ 641
],
"types": {
"ActivateWorkspaceInput": {
@@ -509,7 +510,7 @@ export default {
20
],
"configurationType": [
- 618
+ 619
],
"description": [
1
@@ -1219,7 +1220,7 @@ export default {
8
],
"versionDistribution": [
- 599
+ 600
],
"__typename": [
1
@@ -1456,7 +1457,7 @@ export default {
436
],
"workspaceUrls": [
- 641
+ 642
],
"__typename": [
1
@@ -1499,7 +1500,7 @@ export default {
1
],
"configurationType": [
- 618
+ 619
],
"description": [
1
@@ -1667,6 +1668,9 @@ export default {
"id": [
494
],
+ "userCreditsFallback": [
+ 591
+ ],
"__typename": [
1
]
@@ -1894,9 +1898,6 @@ export default {
]
},
"BillingResourceCreditUsage": {
- "grantedCredits": [
- 11
- ],
"periodEnd": [
188
],
@@ -1906,16 +1907,22 @@ export default {
"productKey": [
97
],
- "rolloverCredits": [
+ "unitPriceCents": [
11
],
- "totalGrantedCredits": [
+ "userCreditsUsed": [
11
],
- "unitPriceCents": [
+ "workspaceCreditsExtraGranted": [
11
],
- "usedCredits": [
+ "workspaceCreditsGranted": [
+ 11
+ ],
+ "workspaceCreditsTotalGranted": [
+ 11
+ ],
+ "workspaceCreditsUsed": [
11
],
"__typename": [
@@ -2101,7 +2108,7 @@ export default {
"CalendarChannelVisibility": {},
"CalendarConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -2109,7 +2116,7 @@ export default {
},
"CallRecordingSummaryConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -2117,7 +2124,7 @@ export default {
},
"CallRecordingTranscriptConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -2194,7 +2201,7 @@ export default {
"ChartNumberFormat": {},
"ChatConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -2227,7 +2234,7 @@ export default {
},
"ChatThreadsConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -3334,7 +3341,7 @@ export default {
1
],
"type": [
- 619
+ 620
],
"__typename": [
1
@@ -3556,7 +3563,7 @@ export default {
494
],
"logicalOperator": [
- 607
+ 608
],
"parentViewFilterGroupId": [
494
@@ -3579,7 +3586,7 @@ export default {
494
],
"operand": [
- 608
+ 609
],
"positionInViewFilterGroup": [
11
@@ -3634,7 +3641,7 @@ export default {
494
],
"calendarLayout": [
- 601
+ 602
],
"groupLoadLimit": [
8
@@ -3658,7 +3665,7 @@ export default {
8
],
"key": [
- 610
+ 611
],
"mainGroupByFieldMetadataId": [
494
@@ -3670,7 +3677,7 @@ export default {
494
],
"openRecordIn": [
- 611
+ 612
],
"position": [
11
@@ -3679,10 +3686,10 @@ export default {
4
],
"type": [
- 614
+ 615
],
"visibility": [
- 615
+ 616
],
"__typename": [
1
@@ -3690,7 +3697,7 @@ export default {
},
"CreateViewSortInput": {
"direction": [
- 613
+ 614
],
"fieldMetadataId": [
494
@@ -4059,7 +4066,7 @@ export default {
},
"EmailThreadConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -4088,7 +4095,7 @@ export default {
188
],
"verificationRecords": [
- 596
+ 597
],
"verifiedAt": [
188
@@ -4101,7 +4108,7 @@ export default {
"EmailingDomainTenantStatus": {},
"EmailsConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -4479,7 +4486,7 @@ export default {
},
"FieldConfiguration": {
"configurationType": [
- 618
+ 619
],
"fieldDisplayMode": [
246
@@ -4595,7 +4602,7 @@ export default {
},
"FieldRichTextConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -4603,7 +4610,7 @@ export default {
},
"FieldsConfiguration": {
"configurationType": [
- 618
+ 619
],
"newFieldDefaultVisibility": [
4
@@ -4686,7 +4693,7 @@ export default {
},
"FilesConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -4709,7 +4716,7 @@ export default {
273
],
"workspace": [
- 638
+ 639
],
"__typename": [
1
@@ -4737,7 +4744,7 @@ export default {
},
"FormFieldConfiguration": {
"configurationType": [
- 618
+ 619
],
"fieldMetadataId": [
1
@@ -4810,7 +4817,7 @@ export default {
},
"FrontComponentConfiguration": {
"configurationType": [
- 618
+ 619
],
"frontComponentId": [
494
@@ -4909,7 +4916,7 @@ export default {
"IdentityProviderType": {},
"IframeConfiguration": {
"configurationType": [
- 618
+ 619
],
"url": [
1
@@ -4968,7 +4975,7 @@ export default {
66
],
"workspace": [
- 642
+ 643
],
"__typename": [
1
@@ -5164,7 +5171,7 @@ export default {
1
],
"configurationType": [
- 618
+ 619
],
"description": [
1
@@ -5683,7 +5690,7 @@ export default {
},
"MessageCampaignBodyConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -5691,7 +5698,7 @@ export default {
},
"MessageCampaignDetailsConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -5989,13 +5996,13 @@ export default {
494
],
"key": [
- 610
+ 611
],
"objectMetadataId": [
494
],
"type": [
- 614
+ 615
],
"__typename": [
1
@@ -6013,7 +6020,7 @@ export default {
}
],
"activateWorkspace": [
- 623,
+ 624,
{
"data": [
0,
@@ -6386,7 +6393,7 @@ export default {
}
],
"createManyViewFieldGroups": [
- 604,
+ 605,
{
"inputs": [
178,
@@ -6395,7 +6402,7 @@ export default {
}
],
"createManyViewFields": [
- 603,
+ 604,
{
"inputs": [
179,
@@ -6404,7 +6411,7 @@ export default {
}
],
"createManyViewGroups": [
- 609,
+ 610,
{
"inputs": [
182,
@@ -6631,7 +6638,7 @@ export default {
}
],
"createValidationRule": [
- 595,
+ 596,
{
"input": [
177,
@@ -6640,7 +6647,7 @@ export default {
}
],
"createView": [
- 600,
+ 601,
{
"input": [
183,
@@ -6649,7 +6656,7 @@ export default {
}
],
"createViewField": [
- 603,
+ 604,
{
"input": [
179,
@@ -6658,7 +6665,7 @@ export default {
}
],
"createViewFieldGroup": [
- 604,
+ 605,
{
"input": [
178,
@@ -6667,7 +6674,7 @@ export default {
}
],
"createViewFilter": [
- 605,
+ 606,
{
"input": [
181,
@@ -6676,7 +6683,7 @@ export default {
}
],
"createViewFilterGroup": [
- 606,
+ 607,
{
"input": [
180,
@@ -6685,7 +6692,7 @@ export default {
}
],
"createViewGroup": [
- 609,
+ 610,
{
"input": [
182,
@@ -6694,7 +6701,7 @@ export default {
}
],
"createViewSort": [
- 612,
+ 613,
{
"input": [
184,
@@ -6703,7 +6710,7 @@ export default {
}
],
"createWebhook": [
- 616,
+ 617,
{
"input": [
185,
@@ -6778,7 +6785,7 @@ export default {
}
],
"deleteCurrentWorkspace": [
- 623
+ 624
],
"deleteEmailGroupChannel": [
318,
@@ -6955,7 +6962,7 @@ export default {
589
],
"deleteUserFromWorkspace": [
- 592,
+ 593,
{
"workspaceMemberIdToDelete": [
1,
@@ -6964,7 +6971,7 @@ export default {
}
],
"deleteValidationRule": [
- 595,
+ 596,
{
"id": [
494,
@@ -6982,7 +6989,7 @@ export default {
}
],
"deleteViewField": [
- 603,
+ 604,
{
"input": [
197,
@@ -6991,7 +6998,7 @@ export default {
}
],
"deleteViewFieldGroup": [
- 604,
+ 605,
{
"input": [
196,
@@ -7000,7 +7007,7 @@ export default {
}
],
"deleteViewFilter": [
- 605,
+ 606,
{
"input": [
198,
@@ -7018,7 +7025,7 @@ export default {
}
],
"deleteViewGroup": [
- 609,
+ 610,
{
"input": [
199,
@@ -7036,7 +7043,7 @@ export default {
}
],
"deleteWebhook": [
- 616,
+ 617,
{
"id": [
494,
@@ -7090,7 +7097,7 @@ export default {
}
],
"destroyViewField": [
- 603,
+ 604,
{
"input": [
203,
@@ -7099,7 +7106,7 @@ export default {
}
],
"destroyViewFieldGroup": [
- 604,
+ 605,
{
"input": [
202,
@@ -7108,7 +7115,7 @@ export default {
}
],
"destroyViewFilter": [
- 605,
+ 606,
{
"input": [
204,
@@ -7126,7 +7133,7 @@ export default {
}
],
"destroyViewGroup": [
- 609,
+ 610,
{
"input": [
205,
@@ -7216,7 +7223,7 @@ export default {
}
],
"enrichWorkspaceCompany": [
- 627
+ 628
],
"executeOneLogicFunction": [
304,
@@ -7959,7 +7966,7 @@ export default {
107
],
"syncApplication": [
- 637,
+ 638,
{
"dryRun": [
4
@@ -8199,7 +8206,7 @@ export default {
}
],
"updateManyViewGroups": [
- 609,
+ 610,
{
"inputs": [
548,
@@ -8422,6 +8429,15 @@ export default {
]
}
],
+ "updateUserCreditsFallback": [
+ 83,
+ {
+ "userCreditsFallback": [
+ 591,
+ "UserCreditsFallback!"
+ ]
+ }
+ ],
"updateUserEmail": [
4,
{
@@ -8435,7 +8451,7 @@ export default {
}
],
"updateValidationRule": [
- 595,
+ 596,
{
"input": [
539,
@@ -8444,7 +8460,7 @@ export default {
}
],
"updateView": [
- 600,
+ 601,
{
"id": [
1,
@@ -8457,7 +8473,7 @@ export default {
}
],
"updateViewField": [
- 603,
+ 604,
{
"input": [
543,
@@ -8466,7 +8482,7 @@ export default {
}
],
"updateViewFieldGroup": [
- 604,
+ 605,
{
"input": [
541,
@@ -8475,7 +8491,7 @@ export default {
}
],
"updateViewFilter": [
- 605,
+ 606,
{
"input": [
546,
@@ -8484,7 +8500,7 @@ export default {
}
],
"updateViewFilterGroup": [
- 606,
+ 607,
{
"id": [
1,
@@ -8497,7 +8513,7 @@ export default {
}
],
"updateViewGroup": [
- 609,
+ 610,
{
"input": [
548,
@@ -8506,7 +8522,7 @@ export default {
}
],
"updateViewSort": [
- 612,
+ 613,
{
"input": [
551,
@@ -8515,7 +8531,7 @@ export default {
}
],
"updateWebhook": [
- 616,
+ 617,
{
"input": [
553,
@@ -8524,7 +8540,7 @@ export default {
}
],
"updateWorkspace": [
- 623,
+ 624,
{
"data": [
556,
@@ -8533,7 +8549,7 @@ export default {
}
],
"updateWorkspaceAllowedIframeOrigins": [
- 623,
+ 624,
{
"data": [
555,
@@ -8542,7 +8558,7 @@ export default {
}
],
"updateWorkspaceMemberRole": [
- 632,
+ 633,
{
"roleId": [
494,
@@ -8663,7 +8679,7 @@ export default {
}
],
"upsertFieldsWidget": [
- 600,
+ 601,
{
"input": [
562,
@@ -8699,7 +8715,7 @@ export default {
}
],
"upsertViewWidget": [
- 600,
+ 601,
{
"input": [
567,
@@ -8711,13 +8727,13 @@ export default {
63,
{
"input": [
- 593,
+ 594,
"ValidateApprovedAccessDomainInput!"
]
}
],
"verifyEmailAndGetLoginToken": [
- 597,
+ 598,
{
"captchaToken": [
1
@@ -8762,7 +8778,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 598,
+ 599,
{
"otp": [
1,
@@ -8844,7 +8860,7 @@ export default {
"NavigationMenuItemType": {},
"NotesConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -9326,7 +9342,7 @@ export default {
290
],
"configuration": [
- 617
+ 618
],
"createdAt": [
188
@@ -9362,7 +9378,7 @@ export default {
1
],
"type": [
- 619
+ 620
],
"universalIdentifier": [
494
@@ -9486,7 +9502,7 @@ export default {
1
],
"configurationType": [
- 618
+ 619
],
"dateGranularity": [
364
@@ -9732,7 +9748,7 @@ export default {
1
],
"workspaceUrls": [
- 641
+ 642
],
"__typename": [
1
@@ -9935,7 +9951,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 631,
+ 632,
{
"inviteHash": [
1,
@@ -9971,10 +9987,10 @@ export default {
38
],
"currentUserSessions": [
- 591
+ 592
],
"currentWorkspace": [
- 623
+ 624
],
"enterpriseCheckoutSession": [
1,
@@ -10190,10 +10206,10 @@ export default {
}
],
"findWorkspaceAiStats": [
- 625
+ 626
],
"findWorkspaceFromInviteHash": [
- 623,
+ 624,
{
"inviteHash": [
1,
@@ -10202,7 +10218,7 @@ export default {
}
],
"findWorkspaceInvitations": [
- 630
+ 631
],
"frontComponent": [
263,
@@ -10414,7 +10430,7 @@ export default {
}
],
"getView": [
- 600,
+ 601,
{
"id": [
1,
@@ -10423,7 +10439,7 @@ export default {
}
],
"getViewField": [
- 603,
+ 604,
{
"id": [
1,
@@ -10432,7 +10448,7 @@ export default {
}
],
"getViewFieldGroup": [
- 604,
+ 605,
{
"id": [
1,
@@ -10441,7 +10457,7 @@ export default {
}
],
"getViewFieldGroups": [
- 604,
+ 605,
{
"viewId": [
1,
@@ -10450,7 +10466,7 @@ export default {
}
],
"getViewFields": [
- 603,
+ 604,
{
"viewId": [
1,
@@ -10459,7 +10475,7 @@ export default {
}
],
"getViewFilter": [
- 605,
+ 606,
{
"id": [
1,
@@ -10468,7 +10484,7 @@ export default {
}
],
"getViewFilterGroup": [
- 606,
+ 607,
{
"id": [
1,
@@ -10477,7 +10493,7 @@ export default {
}
],
"getViewFilterGroups": [
- 606,
+ 607,
{
"viewId": [
1
@@ -10485,7 +10501,7 @@ export default {
}
],
"getViewFilters": [
- 605,
+ 606,
{
"viewId": [
1
@@ -10493,7 +10509,7 @@ export default {
}
],
"getViewGroup": [
- 609,
+ 610,
{
"id": [
1,
@@ -10502,7 +10518,7 @@ export default {
}
],
"getViewGroups": [
- 609,
+ 610,
{
"viewId": [
1
@@ -10510,7 +10526,7 @@ export default {
}
],
"getViewSort": [
- 612,
+ 613,
{
"id": [
1,
@@ -10519,7 +10535,7 @@ export default {
}
],
"getViewSorts": [
- 612,
+ 613,
{
"viewId": [
1
@@ -10527,19 +10543,19 @@ export default {
}
],
"getViews": [
- 600,
+ 601,
{
"objectMetadataId": [
1
],
"viewTypes": [
- 614,
+ 615,
"[ViewType!]"
]
}
],
"getWorkspaceCreationDefaults": [
- 628
+ 629
],
"githubClaimAuthorizationUrl": [
1,
@@ -10629,7 +10645,7 @@ export default {
}
],
"myUserApplicationVariables": [
- 633
+ 634
],
"navigationMenuItem": [
347,
@@ -10768,7 +10784,7 @@ export default {
584
],
"validatePasswordResetToken": [
- 594,
+ 595,
{
"passwordResetToken": [
1,
@@ -10777,7 +10793,7 @@ export default {
}
],
"validationRules": [
- 595,
+ 596,
{
"objectMetadataId": [
494,
@@ -10786,7 +10802,7 @@ export default {
}
],
"webhook": [
- 616,
+ 617,
{
"id": [
494,
@@ -10795,7 +10811,7 @@ export default {
}
],
"webhooks": [
- 616
+ 617
],
"__typename": [
1
@@ -10963,7 +10979,7 @@ export default {
},
"RecordTableConfiguration": {
"configurationType": [
- 618
+ 619
],
"isUIEditable": [
4
@@ -11130,7 +11146,7 @@ export default {
494
],
"workspaceMembers": [
- 632
+ 633
],
"__typename": [
1
@@ -11555,7 +11571,7 @@ export default {
1
],
"result": [
- 630
+ 631
],
"success": [
4
@@ -11741,7 +11757,7 @@ export default {
66
],
"workspace": [
- 642
+ 643
],
"__typename": [
1
@@ -11807,7 +11823,7 @@ export default {
420
],
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -11815,7 +11831,7 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 640
+ 641
],
"thread": [
9
@@ -11919,7 +11935,7 @@ export default {
"SupportDriver": {},
"TasksConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -12002,7 +12018,7 @@ export default {
},
"TimelineConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -12889,7 +12905,7 @@ export default {
1
],
"type": [
- 619
+ 620
],
"__typename": [
1
@@ -12921,7 +12937,7 @@ export default {
1
],
"type": [
- 619
+ 620
],
"__typename": [
1
@@ -13174,7 +13190,7 @@ export default {
494
],
"logicalOperator": [
- 607
+ 608
],
"parentViewFilterGroupId": [
494
@@ -13205,7 +13221,7 @@ export default {
494
],
"operand": [
- 608
+ 609
],
"positionInViewFilterGroup": [
11
@@ -13265,7 +13281,7 @@ export default {
494
],
"calendarLayout": [
- 601
+ 602
],
"groupLoadLimit": [
8
@@ -13295,7 +13311,7 @@ export default {
1
],
"openRecordIn": [
- 611
+ 612
],
"position": [
11
@@ -13304,10 +13320,10 @@ export default {
4
],
"type": [
- 614
+ 615
],
"visibility": [
- 615
+ 616
],
"__typename": [
1
@@ -13326,7 +13342,7 @@ export default {
},
"UpdateViewSortInputUpdates": {
"direction": [
- 613
+ 614
],
"subFieldName": [
1
@@ -13457,7 +13473,7 @@ export default {
11
],
"workspaceDiscoverability": [
- 629
+ 630
],
"__typename": [
1
@@ -13638,7 +13654,7 @@ export default {
494
],
"logicalOperator": [
- 607
+ 608
],
"parentViewFilterGroupId": [
494
@@ -13658,7 +13674,7 @@ export default {
494
],
"operand": [
- 608
+ 609
],
"positionInViewFilterGroup": [
11
@@ -13687,7 +13703,7 @@ export default {
494
],
"calendarLayout": [
- 601
+ 602
],
"kanbanAggregateOperation": [
20
@@ -13702,13 +13718,13 @@ export default {
494
],
"openRecordIn": [
- 611
+ 612
],
"shouldHideEmptyGroups": [
4
],
"type": [
- 614
+ 615
],
"__typename": [
1
@@ -13716,7 +13732,7 @@ export default {
},
"UpsertViewWidgetViewSortInput": {
"direction": [
- 613
+ 614
],
"fieldMetadataId": [
494
@@ -13784,6 +13800,12 @@ export default {
"label": [
1
],
+ "userCreditsUsed": [
+ 11
+ ],
+ "workspaceCreditsUsed": [
+ 11
+ ],
"__typename": [
1
]
@@ -13987,6 +14009,9 @@ export default {
"date": [
1
],
+ "workspaceCreditsUsed": [
+ 11
+ ],
"__typename": [
1
]
@@ -14017,10 +14042,10 @@ export default {
188
],
"currentUserWorkspace": [
- 592
+ 593
],
"currentWorkspace": [
- 623
+ 624
],
"deletedAt": [
188
@@ -14071,16 +14096,16 @@ export default {
291
],
"userWorkspaces": [
- 592
+ 593
],
"workspaceMember": [
- 632
+ 633
],
"workspaceMembers": [
- 632
+ 633
],
"workspaces": [
- 592
+ 593
],
"__typename": [
1
@@ -14118,6 +14143,7 @@ export default {
1
]
},
+ "UserCreditsFallback": {},
"UserSession": {
"authProvider": [
1
@@ -14276,7 +14302,7 @@ export default {
66
],
"workspaceUrls": [
- 641
+ 642
],
"__typename": [
1
@@ -14315,7 +14341,7 @@ export default {
494
],
"calendarLayout": [
- 601
+ 602
],
"createdAt": [
188
@@ -14357,7 +14383,7 @@ export default {
8
],
"key": [
- 610
+ 611
],
"mainGroupByFieldMetadataId": [
494
@@ -14369,7 +14395,7 @@ export default {
494
],
"openRecordIn": [
- 611
+ 612
],
"position": [
11
@@ -14378,7 +14404,7 @@ export default {
4
],
"type": [
- 614
+ 615
],
"universalIdentifier": [
494
@@ -14387,25 +14413,25 @@ export default {
188
],
"viewFieldGroups": [
- 604
+ 605
],
"viewFields": [
- 603
+ 604
],
"viewFilterGroups": [
- 606
+ 607
],
"viewFilters": [
- 605
+ 606
],
"viewGroups": [
- 609
+ 610
],
"viewSorts": [
- 612
+ 613
],
"visibility": [
- 615
+ 616
],
"workspaceId": [
494
@@ -14417,7 +14443,7 @@ export default {
"ViewCalendarLayout": {},
"ViewConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -14508,7 +14534,7 @@ export default {
188
],
"viewFields": [
- 603
+ 604
],
"viewId": [
494
@@ -14534,7 +14560,7 @@ export default {
494
],
"operand": [
- 608
+ 609
],
"positionInViewFilterGroup": [
11
@@ -14575,7 +14601,7 @@ export default {
494
],
"logicalOperator": [
- 607
+ 608
],
"parentViewFilterGroupId": [
494
@@ -14640,7 +14666,7 @@ export default {
188
],
"direction": [
- 613
+ 614
],
"fieldMetadataId": [
494
@@ -14776,16 +14802,16 @@ export default {
475
],
"on_ViewConfiguration": [
- 602
+ 603
],
"on_WorkflowConfiguration": [
- 620
+ 621
],
"on_WorkflowRunConfiguration": [
- 621
+ 622
],
"on_WorkflowVersionConfiguration": [
- 622
+ 623
],
"__typename": [
1
@@ -14795,7 +14821,7 @@ export default {
"WidgetType": {},
"WorkflowConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -14803,7 +14829,7 @@ export default {
},
"WorkflowRunConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -14811,7 +14837,7 @@ export default {
},
"WorkflowVersionConfiguration": {
"configurationType": [
- 618
+ 619
],
"__typename": [
1
@@ -14819,7 +14845,7 @@ export default {
},
"Workspace": {
"activationStatus": [
- 624
+ 625
],
"aiAdditionalInstructions": [
1
@@ -14954,22 +14980,22 @@ export default {
188
],
"viewFields": [
- 603
+ 604
],
"viewFilterGroups": [
- 606
+ 607
],
"viewFilters": [
- 605
+ 606
],
"viewGroups": [
- 609
+ 610
],
"viewSorts": [
- 612
+ 613
],
"views": [
- 600
+ 601
],
"workspaceCustomApplication": [
37
@@ -14978,13 +15004,13 @@ export default {
1
],
"workspaceDiscoverability": [
- 629
+ 630
],
"workspaceMembersCount": [
11
],
"workspaceUrls": [
- 641
+ 642
],
"__typename": [
1
@@ -15014,13 +15040,13 @@ export default {
4
],
"outcome": [
- 626
+ 627
],
"personEnrichment": [
290
],
"personOutcome": [
- 639
+ 640
],
"__typename": [
1
@@ -15074,7 +15100,7 @@ export default {
1
],
"dateFormat": [
- 634
+ 635
],
"id": [
494
@@ -15086,7 +15112,7 @@ export default {
266
],
"numberFormat": [
- 635
+ 636
],
"openRecordIn": [
369
@@ -15095,7 +15121,7 @@ export default {
421
],
"timeFormat": [
- 636
+ 637
],
"timeZone": [
1
@@ -15173,7 +15199,7 @@ export default {
494
],
"workspaceUrls": [
- 641
+ 642
],
"__typename": [
1
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index 6e02e30a169..0947f19e9c8 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -215,13 +215,14 @@ export type AdminPanelWorkspaceSubscriptionItem = {
export type AdminPanelWorkspaceUsage = {
__typename?: 'AdminPanelWorkspaceUsage';
- grantedCredits: Scalars['Float']['output'];
periodEnd: Scalars['DateTime']['output'];
periodStart: Scalars['DateTime']['output'];
- remainingCredits: Scalars['Float']['output'];
- rolloverCredits: Scalars['Float']['output'];
- totalGrantedCredits: Scalars['Float']['output'];
- usedCredits: Scalars['Float']['output'];
+ userCreditsUsed: Scalars['Float']['output'];
+ workspaceCreditsExtraGranted: Scalars['Float']['output'];
+ workspaceCreditsGranted: Scalars['Float']['output'];
+ workspaceCreditsRemaining: Scalars['Float']['output'];
+ workspaceCreditsTotalGranted: Scalars['Float']['output'];
+ workspaceCreditsUsed: Scalars['Float']['output'];
};
export type AdminPanelWorkspaceUsageLimits = {
@@ -1059,11 +1060,14 @@ export type UsageBreakdownItem = {
creditsUsed: Scalars['Float']['output'];
key: Scalars['String']['output'];
label?: Maybe<Scalars['String']['output']>;
+ userCreditsUsed: Scalars['Float']['output'];
+ workspaceCreditsUsed: Scalars['Float']['output'];
};
export enum UsageOperationType {
AI_CHAT_TOKEN = 'AI_CHAT_TOKEN',
AI_WORKFLOW_TOKEN = 'AI_WORKFLOW_TOKEN',
+ AI_WORKFLOW_WEB_SEARCH = 'AI_WORKFLOW_WEB_SEARCH',
ALL = 'ALL',
API_REQUEST = 'API_REQUEST',
CALL_RECORDING = 'CALL_RECORDING',
@@ -1102,7 +1106,8 @@ export enum UsageUnit {
RECORD = 'RECORD',
REQUEST = 'REQUEST',
SEAT = 'SEAT',
- TOKEN = 'TOKEN'
+ TOKEN = 'TOKEN',
+ USER_CREDIT = 'USER_CREDIT'
}
export type UserInfo = {
@@ -1506,7 +1511,7 @@ export type WorkspaceBillingAdminPanelQueryVariables = Exact<{
}>;
-export type WorkspaceBillingAdminPanelQuery = { __typename?: 'Query', workspaceBillingAdminPanel?: { __typename?: 'AdminPanelWorkspaceBilling', stripeCustomerId?: string | null, creditBalance?: number | null, creditGrants: Array<{ __typename?: 'AdminPanelWorkspaceCreditGrant', id: string, amount: number, type: BillingCreditGrantType, effectiveAt: string, expiresAt?: string | null, revokedAt?: string | null, sourceGrantId?: string | null, reason?: string | null, isActive: boolean, createdAt: string }>, usage?: { __typename?: 'AdminPanelWorkspaceUsage', periodStart: string, periodEnd: string, usedCredits: number, grantedCredits: number, rolloverCredits: number, totalGrantedCredits: number, remainingCredits: number } | null, subscription?: { __typename?: 'AdminPanelWorkspaceSubscription', stripeSubscriptionId: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, currency: string, planKey?: string | null, currentPeriodStart: string, currentPeriodEnd: string, trialStart?: string | null, trialEnd?: string | null, cancelAt?: string | null, canceledAt?: string | null, cancelAtPeriodEnd: boolean, items: Array<{ __typename?: 'AdminPanelWorkspaceSubscriptionItem', productName: string, productKey?: string | null, stripePriceId: string, quantity?: number | null, unitAmount?: number | null, includedCredits?: number | null }> } | null } | null };
+export type WorkspaceBillingAdminPanelQuery = { __typename?: 'Query', workspaceBillingAdminPanel?: { __typename?: 'AdminPanelWorkspaceBilling', stripeCustomerId?: string | null, creditBalance?: number | null, creditGrants: Array<{ __typename?: 'AdminPanelWorkspaceCreditGrant', id: string, amount: number, type: BillingCreditGrantType, effectiveAt: string, expiresAt?: string | null, revokedAt?: string | null, sourceGrantId?: string | null, reason?: string | null, isActive: boolean, createdAt: string }>, usage?: { __typename?: 'AdminPanelWorkspaceUsage', periodStart: string, periodEnd: string, workspaceCreditsUsed: number, workspaceCreditsGranted: number, workspaceCreditsExtraGranted: number, workspaceCreditsTotalGranted: number, workspaceCreditsRemaining: number } | null, subscription?: { __typename?: 'AdminPanelWorkspaceSubscription', stripeSubscriptionId: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, currency: string, planKey?: string | null, currentPeriodStart: string, currentPeriodEnd: string, trialStart?: string | null, trialEnd?: string | null, cancelAt?: string | null, canceledAt?: string | null, cancelAtPeriodEnd: boolean, items: Array<{ __typename?: 'AdminPanelWorkspaceSubscriptionItem', productName: string, productKey?: string | null, stripePriceId: string, quantity?: number | null, unitAmount?: number | null, includedCredits?: number | null }> } | null } | null };
export type UserLookupAdminPanelQueryVariables = Exact<{
userIdentifier: Scalars['String']['input'];
@@ -1662,7 +1667,7 @@ export const GetAdminWorkspaceChatThreadsDocument = {"kind":"Document","definiti
export const GetServerAdminsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetServerAdmins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getServerAdmins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}}]}}]}}]} as unknown as DocumentNode<GetServerAdminsQuery, GetServerAdminsQueryVariables>;
export const GetUpgradeStatusDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUpgradeStatus"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getUpgradeStatus"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceIds"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"inferredVersion"}},{"kind":"Field","name":{"kind":"Name","value":"health"}},{"kind":"Field","name":{"kind":"Name","value":"latestCommand"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"executedByVersion"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]}}]} as unknown as DocumentNode<GetUpgradeStatusQuery, GetUpgradeStatusQueryVariables>;
export const GetVersionInfoDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetVersionInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"versionInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentVersion"}},{"kind":"Field","name":{"kind":"Name","value":"latestVersion"}}]}}]}}]} as unknown as DocumentNode<GetVersionInfoQuery, GetVersionInfoQueryVariables>;
-export const WorkspaceBillingAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceBillingAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceBillingAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeCustomerId"}},{"kind":"Field","name":{"kind":"Name","value":"creditBalance"}},{"kind":"Field","name":{"kind":"Name","value":"creditGrants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"sourceGrantId"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"usedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"grantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"rolloverCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalGrantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"remainingCredits"}}]}},{"kind":"Field","name":{"kind":"Name","value":"subscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeSubscriptionId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"currency"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodStart"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"trialStart"}},{"kind":"Field","name":{"kind":"Name","value":"trialEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"canceledAt"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAtPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productName"}},{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"includedCredits"}}]}}]}}]}}]}}]} as unknown as DocumentNode<WorkspaceBillingAdminPanelQuery, WorkspaceBillingAdminPanelQueryVariables>;
+export const WorkspaceBillingAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceBillingAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceBillingAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeCustomerId"}},{"kind":"Field","name":{"kind":"Name","value":"creditBalance"}},{"kind":"Field","name":{"kind":"Name","value":"creditGrants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"sourceGrantId"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsExtraGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsTotalGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsRemaining"}}]}},{"kind":"Field","name":{"kind":"Name","value":"subscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeSubscriptionId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"currency"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodStart"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"trialStart"}},{"kind":"Field","name":{"kind":"Name","value":"trialEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"canceledAt"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAtPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productName"}},{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"includedCredits"}}]}}]}}]}}]}}]} as unknown as DocumentNode<WorkspaceBillingAdminPanelQuery, WorkspaceBillingAdminPanelQueryVariables>;
export const UserLookupAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UserLookupAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userLookupAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"UserInfoFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"totalUsers"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customUrl"}},{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"users"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserInfoFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"UserInfo"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]} as unknown as DocumentNode<UserLookupAdminPanelQuery, UserLookupAdminPanelQueryVariables>;
export const WorkspaceLookupAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceLookupAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceLookupAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"UserInfoFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"totalUsers"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customUrl"}},{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"users"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserInfoFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"UserInfo"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]} as unknown as DocumentNode<WorkspaceLookupAdminPanelQuery, WorkspaceLookupAdminPanelQueryVariables>;
export const WorkspaceUsageLimitsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceUsageLimits"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceUsageLimits"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"defaults"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderType"}},{"kind":"Field","name":{"kind":"Name","value":"limitKind"}},{"kind":"Field","name":{"kind":"Name","value":"periodCount"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}},{"kind":"Field","name":{"kind":"Name","value":"unit"}},{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"isOverridable"}},{"kind":"Field","name":{"kind":"Name","value":"overriddenByUsageLimitId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"limits"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"periodCount"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}},{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"burstValue"}}]}}]}}]}}]} as unknown as DocumentNode<WorkspaceUsageLimitsQuery, WorkspaceUsageLimitsQueryVariables>;
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index e9e39e0d689..7d1b57e77d0 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -818,6 +818,7 @@ export type BillingCustomer = {
__typename?: 'BillingCustomer';
hasPaymentMethod?: Maybe<Scalars['Boolean']['output']>;
id: Scalars['UUID']['output'];
+ userCreditsFallback: UserCreditsFallback;
};
export type BillingEndTrialPeriod = {
@@ -949,14 +950,15 @@ export type BillingProductMetadata = {
export type BillingResourceCreditUsage = {
__typename?: 'BillingResourceCreditUsage';
- grantedCredits: Scalars['Float']['output'];
periodEnd: Scalars['DateTime']['output'];
periodStart: Scalars['DateTime']['output'];
productKey: BillingProductKey;
- rolloverCredits: Scalars['Float']['output'];
- totalGrantedCredits: Scalars['Float']['output'];
unitPriceCents: Scalars['Float']['output'];
- usedCredits: Scalars['Float']['output'];
+ userCreditsUsed: Scalars['Float']['output'];
+ workspaceCreditsExtraGranted: Scalars['Float']['output'];
+ workspaceCreditsGranted: Scalars['Float']['output'];
+ workspaceCreditsTotalGranted: Scalars['Float']['output'];
+ workspaceCreditsUsed: Scalars['Float']['output'];
};
export type BillingSession = {
@@ -3395,6 +3397,7 @@ export type Mutation = {
updateTimelineActivityType: TimelineActivityType;
updateUnsubscribeTopic: UnsubscribeTopic;
updateUsageLimit: UsageLimit;
+ updateUserCreditsFallback: BillingCustomer;
updateUserEmail: Scalars['Boolean']['output'];
updateValidationRule: ValidationRule;
updateView: View;
@@ -4649,6 +4652,11 @@ export type MutationUpdateUsageLimitArgs = {
};
+export type MutationUpdateUserCreditsFallbackArgs = {
+ userCreditsFallback: UserCreditsFallback;
+};
+
+
export type MutationUpdateUserEmailArgs = {
newEmail: Scalars['String']['input'];
verifyEmailRedirectPath?: InputMaybe<Scalars['String']['input']>;
@@ -7428,6 +7436,8 @@ export type UsageBreakdownItem = {
creditsUsed: Scalars['Float']['output'];
key: Scalars['String']['output'];
label?: Maybe<Scalars['String']['output']>;
+ userCreditsUsed: Scalars['Float']['output'];
+ workspaceCreditsUsed: Scalars['Float']['output'];
};
export type UsageLimit = {
@@ -7456,6 +7466,7 @@ export type UsageLimitOperationDefinition = {
export enum UsageOperationType {
AI_CHAT_TOKEN = 'AI_CHAT_TOKEN',
AI_WORKFLOW_TOKEN = 'AI_WORKFLOW_TOKEN',
+ AI_WORKFLOW_WEB_SEARCH = 'AI_WORKFLOW_WEB_SEARCH',
ALL = 'ALL',
API_REQUEST = 'API_REQUEST',
CALL_RECORDING = 'CALL_RECORDING',
@@ -7545,6 +7556,7 @@ export type UsageTimeSeries = {
__typename?: 'UsageTimeSeries';
creditsUsed: Scalars['Float']['output'];
date: Scalars['String']['output'];
+ workspaceCreditsUsed: Scalars['Float']['output'];
};
export enum UsageUnit {
@@ -7558,7 +7570,8 @@ export enum UsageUnit {
RECORD = 'RECORD',
REQUEST = 'REQUEST',
SEAT = 'SEAT',
- TOKEN = 'TOKEN'
+ TOKEN = 'TOKEN',
+ USER_CREDIT = 'USER_CREDIT'
}
export type UsageUserDaily = {
@@ -7610,6 +7623,11 @@ export type UserApplicationVariableValue = {
value: Scalars['String']['output'];
};
+export enum UserCreditsFallback {
+ STOP = 'STOP',
+ WORKSPACE_CREDITS = 'WORKSPACE_CREDITS'
+}
+
export type UserSession = {
__typename?: 'UserSession';
authProvider: Scalars['String']['output'];
@@ -10096,7 +10114,7 @@ export type BillingPortalSessionQuery = { __typename?: 'Query', billingPortalSes
export type GetResourceCreditUsageQueryVariables = Exact<{ [key: string]: never; }>;
-export type GetResourceCreditUsageQuery = { __typename?: 'Query', getResourceCreditUsage: Array<{ __typename?: 'BillingResourceCreditUsage', productKey: BillingProductKey, usedCredits: number, grantedCredits: number, rolloverCredits: number, totalGrantedCredits: number, unitPriceCents: number }> };
+export type GetResourceCreditUsageQuery = { __typename?: 'Query', getResourceCreditUsage: Array<{ __typename?: 'BillingResourceCreditUsage', productKey: BillingProductKey, workspaceCreditsUsed: number, workspaceCreditsGranted: number, workspaceCreditsExtraGranted: number, workspaceCreditsTotalGranted: number, unitPriceCents: number }> };
export type ListPlansQueryVariables = Exact<{ [key: string]: never; }>;
@@ -10543,7 +10561,7 @@ export type GetUsageAnalyticsQueryVariables = Exact<{
}>;
-export type GetUsageAnalyticsQuery = { __typename?: 'Query', getUsageAnalytics: { __typename?: 'UsageAnalytics', periodStart: string, periodEnd: string, usageByUser: Array<{ __typename?: 'UsageBreakdownItem', key: string, label?: string | null, creditsUsed: number }>, usageByOperationType: Array<{ __typename?: 'UsageBreakdownItem', key: string, creditsUsed: number }>, usageByApplication: Array<{ __typename?: 'UsageBreakdownItem', key: string, label?: string | null, creditsUsed: number }>, usageByModel: Array<{ __typename?: 'UsageBreakdownItem', key: string, creditsUsed: number }>, timeSeries: Array<{ __typename?: 'UsageTimeSeries', date: string, creditsUsed: number }>, userDailyUsage?: { __typename?: 'UsageUserDaily', userWorkspaceId: string, dailyUsage: Array<{ __typename?: 'UsageTimeSeries', date: string, creditsUsed: number }> } | null } };
+export type GetUsageAnalyticsQuery = { __typename?: 'Query', getUsageAnalytics: { __typename?: 'UsageAnalytics', periodStart: string, periodEnd: string, usageByUser: Array<{ __typename?: 'UsageBreakdownItem', key: string, label?: string | null, workspaceCreditsUsed: number }>, usageByOperationType: Array<{ __typename?: 'UsageBreakdownItem', key: string, workspaceCreditsUsed: number }>, usageByApplication: Array<{ __typename?: 'UsageBreakdownItem', key: string, label?: string | null, workspaceCreditsUsed: number }>, usageByModel: Array<{ __typename?: 'UsageBreakdownItem', key: string, workspaceCreditsUsed: number }>, timeSeries: Array<{ __typename?: 'UsageTimeSeries', date: string, workspaceCreditsUsed: number }>, userDailyUsage?: { __typename?: 'UsageUserDaily', userWorkspaceId: string, dailyUsage: Array<{ __typename?: 'UsageTimeSeries', date: string, workspaceCreditsUsed: number }> } | null } };
export type AddQueryToEventStreamMutationVariables = Exact<{
input: AddQuerySubscriptionInput;
@@ -10576,7 +10594,7 @@ export type CurrentBillingSubscriptionFragmentFragment = { __typename?: 'Billing
export type UserQueryFragmentFragment = { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, hasPassword: boolean, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, previousOnboardingStatus?: OnboardingStatus | null, isWorkspaceCreator?: boolean | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, uiScale: string, openRecordIn: OpenRecordIn, avatarUrl?: string | null, locale?: string | null, userEmail: string, userId: string, userWorkspaceId?: string | null, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, userId: string, userWorkspaceId?: string | null, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', id: string, permissionFlags?: Array<PermissionFlagType> | null, isImpersonating?: boolean | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null, rowLevelPermissionPredicates?: Array<{ __typename?: 'RowLevelPermissionPredicate', id: string, fieldMetadataId: string, objectMetadataId: string, operand: RowLevelPermissionPredicateOperand, subFieldName?: string | null, workspaceMemberFieldMetadataId?: string | null, workspaceMemberSubFieldName?: string | null, rowLevelPermissionPredicateGroupId?: string | null, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, value?: any | null }> | null, rowLevelPermissionPredicateGroups?: Array<{ __typename?: 'RowLevelPermissionPredicateGroup', id: string, parentRowLevelPermissionPredicateGroupId?: string | null, logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, objectMetadataId: string }> | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodSummary', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isCampaignClickTrackingEnabled: boolean, isCampaignOpenTrackingEnabled: boolean, workspaceDiscoverability: WorkspaceDiscoverability, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, isGoogleAuthBypassEnabled: boolean, isMicrosoftAuthBypassEnabled: boolean, isPasswordAuthBypassEnabled: boolean, subdomain: string, customDomain?: string | null, hasValidSignedEnterpriseKey: boolean, hasValidEnterpriseValidityToken: boolean, isCustomDomainEnabled: boolean, workspaceMembersCount?: number | null, aiChatModelTier: AiModelTier, aiAgentModelTier: AiModelTier, isAutoModelSelectionEnabled: boolean, aiModelIdByTier: any, aiAdditionalInstructions?: string | null, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, eventLogRetentionDays: number, editableProfileFields?: Array<string> | null, isInternalMessagesImportEnabled: boolean, workspaceCustomApplication?: { __typename?: 'Application', id: string } | null, installedApplications: Array<{ __typename?: 'Application', id: string, name: string, universalIdentifier: string, logoUrl?: string | null, createdAt: string }>, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlag', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, cancelAt?: string | null, collectionMethod?: BillingSubscriptionCollectionMethod | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItem', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, unitAmount?: number | null, creditAmount?: number | null, billingProduct:
| { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType, isLegacy?: string | null } }
| { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType, isLegacy?: string | null } }
- }> | null } | null, billingCustomer?: { __typename?: 'BillingCustomer', id: string, hasPaymentMethod?: boolean | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, cancelAt?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, billingEntitlements: Array<{ __typename?: 'BillingEntitlement', key: BillingEntitlementKey, value: boolean }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean, applicationId: string } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } };
+ }> | null } | null, billingCustomer?: { __typename?: 'BillingCustomer', id: string, hasPaymentMethod?: boolean | null, userCreditsFallback: UserCreditsFallback } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, cancelAt?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, billingEntitlements: Array<{ __typename?: 'BillingEntitlement', key: BillingEntitlementKey, value: boolean }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean, applicationId: string } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } };
export type WorkspaceUrlsFragmentFragment = { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null };
@@ -10598,7 +10616,7 @@ export type GetCurrentUserQueryVariables = Exact<{ [key: string]: never; }>;
export type GetCurrentUserQuery = { __typename?: 'Query', currentUser: { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, hasPassword: boolean, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, previousOnboardingStatus?: OnboardingStatus | null, isWorkspaceCreator?: boolean | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, uiScale: string, openRecordIn: OpenRecordIn, avatarUrl?: string | null, locale?: string | null, userEmail: string, userId: string, userWorkspaceId?: string | null, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, userId: string, userWorkspaceId?: string | null, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', id: string, permissionFlags?: Array<PermissionFlagType> | null, isImpersonating?: boolean | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null, rowLevelPermissionPredicates?: Array<{ __typename?: 'RowLevelPermissionPredicate', id: string, fieldMetadataId: string, objectMetadataId: string, operand: RowLevelPermissionPredicateOperand, subFieldName?: string | null, workspaceMemberFieldMetadataId?: string | null, workspaceMemberSubFieldName?: string | null, rowLevelPermissionPredicateGroupId?: string | null, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, value?: any | null }> | null, rowLevelPermissionPredicateGroups?: Array<{ __typename?: 'RowLevelPermissionPredicateGroup', id: string, parentRowLevelPermissionPredicateGroupId?: string | null, logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, objectMetadataId: string }> | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodSummary', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isCampaignClickTrackingEnabled: boolean, isCampaignOpenTrackingEnabled: boolean, workspaceDiscoverability: WorkspaceDiscoverability, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, isGoogleAuthBypassEnabled: boolean, isMicrosoftAuthBypassEnabled: boolean, isPasswordAuthBypassEnabled: boolean, subdomain: string, customDomain?: string | null, hasValidSignedEnterpriseKey: boolean, hasValidEnterpriseValidityToken: boolean, isCustomDomainEnabled: boolean, workspaceMembersCount?: number | null, aiChatModelTier: AiModelTier, aiAgentModelTier: AiModelTier, isAutoModelSelectionEnabled: boolean, aiModelIdByTier: any, aiAdditionalInstructions?: string | null, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, eventLogRetentionDays: number, editableProfileFields?: Array<string> | null, isInternalMessagesImportEnabled: boolean, workspaceCustomApplication?: { __typename?: 'Application', id: string } | null, installedApplications: Array<{ __typename?: 'Application', id: string, name: string, universalIdentifier: string, logoUrl?: string | null, createdAt: string }>, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlag', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, cancelAt?: string | null, collectionMethod?: BillingSubscriptionCollectionMethod | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItem', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, unitAmount?: number | null, creditAmount?: number | null, billingProduct:
| { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType, isLegacy?: string | null } }
| { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType, isLegacy?: string | null } }
- }> | null } | null, billingCustomer?: { __typename?: 'BillingCustomer', id: string, hasPaymentMethod?: boolean | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, cancelAt?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, billingEntitlements: Array<{ __typename?: 'BillingEntitlement', key: BillingEntitlementKey, value: boolean }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean, applicationId: string } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } } };
+ }> | null } | null, billingCustomer?: { __typename?: 'BillingCustomer', id: string, hasPaymentMethod?: boolean | null, userCreditsFallback: UserCreditsFallback } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, cancelAt?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, billingEntitlements: Array<{ __typename?: 'BillingEntitlement', key: BillingEntitlementKey, value: boolean }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean, applicationId: string } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } } };
export type ValidationRuleFragmentFragment = { __typename?: 'ValidationRule', id: string, objectMetadataId: string, name: string, description?: string | null, icon?: string | null, errorFieldMetadataId?: string | null, expression: string, message: string, isActive: boolean };
@@ -10947,7 +10965,7 @@ export const BillingSubscriptionFragmentFragmentDoc = {"kind":"Document","defini
export const RoleFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RoleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Role"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"isEditable"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToUsers"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToAgents"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToApiKeys"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}}]}}]} as unknown as DocumentNode<RoleFragmentFragment, unknown>;
export const AvailableWorkspaceFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspaceFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspace"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"loginToken"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"personalInviteToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"sso"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}}]} as unknown as DocumentNode<AvailableWorkspaceFragmentFragment, unknown>;
export const AvailableWorkspacesFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspacesFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspaces"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignIn"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignUp"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspaceFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspace"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"loginToken"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"personalInviteToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"sso"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}}]} as unknown as DocumentNode<AvailableWorkspacesFragmentFragment, unknown>;
-export const UserQueryFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"User"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"hasPassword"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}},{"kind":"Field","name":{"kind":"Name","value":"supportUserHash"}},{"kind":"Field","name":{"kind":"Name","value":"onboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"previousOnboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"isWorkspaceCreator"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMember"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMembers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PartialWorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"deletedWorkspaceMembers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"DeletedWorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentUserWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"permissionFlags"}},{"kind":"Field","name":{"kind":"Name","value":"isImpersonating"}},{"kind":"Field","name":{"kind":"Name","value":"objectsPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ObjectPermissionFragment"}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RowLevelPermissionPredicateFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicateGroups"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroupFragment"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationMethodSummary"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationMethodId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"strategy"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"isPublicInviteLinkEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isCampaignClickTrackingEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isCampaignOpenTrackingEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceDiscoverability"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"subdomain"}},{"kind":"Field","name":{"kind":"Name","value":"customDomain"}},{"kind":"Field","name":{"kind":"Name","value":"hasValidSignedEnterpriseKey"}},{"kind":"Field","name":{"kind":"Name","value":"hasValidEnterpriseValidityToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCustomApplication"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}},{"kind":"Field","name":{"kind":"Name","value":"installedApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"isCustomDomainEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceUrlsFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentBillingSubscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingCustomer"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasPaymentMethod"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingEntitlements"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMembersCount"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRole"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RoleFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"aiChatModelTier"}},{"kind":"Field","name":{"kind":"Name","value":"aiAgentModelTier"}},{"kind":"Field","name":{"kind":"Name","value":"isAutoModelSelectionEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"aiModelIdByTier"}},{"kind":"Field","name":{"kind":"Name","value":"aiAdditionalInstructions"}},{"kind":"Field","name":{"kind":"Name","value":"isTwoFactorAuthenticationEnforced"}},{"kind":"Field","name":{"kind":"Name","value":"trashRetentionDays"}},{"kind":"Field","name":{"kind":"Name","value":"eventLogRetentionDays"}},{"kind":"Field","name":{"kind":"Name","value":"editableProfileFields"}},{"kind":"Field","name":{"kind":"Name","value":"isInternalMessagesImportEnabled"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspacesFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"userVars"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"price"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhase"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"start_date"}},{"kind":"Field","name":{"kind":"Name","value":"end_date"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspaceFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspace"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"loginToken"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"personalInviteToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"sso"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"colorScheme"}},{"kind":"Field","name":{"kind":"Name","value":"uiScale"}},{"kind":"Field","name":{"kind":"Name","value":"openRecordIn"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"locale"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","name":{"kind":"Name","value":"dateFormat"}},{"kind":"Field","name":{"kind":"Name","value":"timeFormat"}},{"kind":"Field","name":{"kind":"Name","value":"calendarStartDay"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PartialWorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"DeletedWorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"DeletedWorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ObjectPermissionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ObjectPermission"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"canReadObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"restrictedFields"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RowLevelPermissionPredicateFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RowLevelPermissionPredicate"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"operand"}},{"kind":"Field","name":{"kind":"Name","value":"subFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberSubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicateGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"positionInRowLevelPermissionPredicateGroup"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroupFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroup"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"parentRowLevelPermissionPredicateGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"logicalOperator"}},{"kind":"Field","name":{"kind":"Name","value":"positionInRowLevelPermissionPredicateGroup"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceUrlsFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceUrls"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"collectionMethod"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptionItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasReachedCurrentPeriodCap"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"billingProduct"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RoleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Role"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"isEditable"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToUsers"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToAgents"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToApiKeys"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspacesFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspaces"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignIn"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignUp"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}}]}}]} as unknown as DocumentNode<UserQueryFragmentFragment, unknown>;
+export const UserQueryFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"User"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"hasPassword"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}},{"kind":"Field","name":{"kind":"Name","value":"supportUserHash"}},{"kind":"Field","name":{"kind":"Name","value":"onboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"previousOnboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"isWorkspaceCreator"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMember"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMembers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PartialWorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"deletedWorkspaceMembers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"DeletedWorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentUserWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"permissionFlags"}},{"kind":"Field","name":{"kind":"Name","value":"isImpersonating"}},{"kind":"Field","name":{"kind":"Name","value":"objectsPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ObjectPermissionFragment"}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RowLevelPermissionPredicateFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicateGroups"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroupFragment"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationMethodSummary"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationMethodId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"strategy"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"isPublicInviteLinkEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isCampaignClickTrackingEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isCampaignOpenTrackingEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceDiscoverability"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"subdomain"}},{"kind":"Field","name":{"kind":"Name","value":"customDomain"}},{"kind":"Field","name":{"kind":"Name","value":"hasValidSignedEnterpriseKey"}},{"kind":"Field","name":{"kind":"Name","value":"hasValidEnterpriseValidityToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCustomApplication"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}},{"kind":"Field","name":{"kind":"Name","value":"installedApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"isCustomDomainEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceUrlsFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentBillingSubscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingCustomer"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasPaymentMethod"}},{"kind":"Field","name":{"kind":"Name","value":"userCreditsFallback"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingEntitlements"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMembersCount"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRole"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RoleFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"aiChatModelTier"}},{"kind":"Field","name":{"kind":"Name","value":"aiAgentModelTier"}},{"kind":"Field","name":{"kind":"Name","value":"isAutoModelSelectionEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"aiModelIdByTier"}},{"kind":"Field","name":{"kind":"Name","value":"aiAdditionalInstructions"}},{"kind":"Field","name":{"kind":"Name","value":"isTwoFactorAuthenticationEnforced"}},{"kind":"Field","name":{"kind":"Name","value":"trashRetentionDays"}},{"kind":"Field","name":{"kind":"Name","value":"eventLogRetentionDays"}},{"kind":"Field","name":{"kind":"Name","value":"editableProfileFields"}},{"kind":"Field","name":{"kind":"Name","value":"isInternalMessagesImportEnabled"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspacesFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"userVars"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"price"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhase"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"start_date"}},{"kind":"Field","name":{"kind":"Name","value":"end_date"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspaceFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspace"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"loginToken"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"personalInviteToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"sso"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"colorScheme"}},{"kind":"Field","name":{"kind":"Name","value":"uiScale"}},{"kind":"Field","name":{"kind":"Name","value":"openRecordIn"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"locale"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","name":{"kind":"Name","value":"dateFormat"}},{"kind":"Field","name":{"kind":"Name","value":"timeFormat"}},{"kind":"Field","name":{"kind":"Name","value":"calendarStartDay"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PartialWorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"DeletedWorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"DeletedWorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ObjectPermissionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ObjectPermission"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"canReadObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"restrictedFields"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RowLevelPermissionPredicateFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RowLevelPermissionPredicate"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"operand"}},{"kind":"Field","name":{"kind":"Name","value":"subFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberSubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicateGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"positionInRowLevelPermissionPredicateGroup"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroupFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroup"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"parentRowLevelPermissionPredicateGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"logicalOperator"}},{"kind":"Field","name":{"kind":"Name","value":"positionInRowLevelPermissionPredicateGroup"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceUrlsFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceUrls"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"collectionMethod"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptionItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasReachedCurrentPeriodCap"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"billingProduct"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RoleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Role"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"isEditable"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToUsers"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToAgents"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToApiKeys"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspacesFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspaces"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignIn"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignUp"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}}]}}]} as unknown as DocumentNode<UserQueryFragmentFragment, unknown>;
export const ValidationRuleFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ValidationRuleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ValidationRule"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"errorFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"expression"}},{"kind":"Field","name":{"kind":"Name","value":"message"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]} as unknown as DocumentNode<ValidationRuleFragmentFragment, unknown>;
export const ViewFieldFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ViewFieldFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ViewField"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"isVisible"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"size"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"viewFieldGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}}]}}]} as unknown as DocumentNode<ViewFieldFragmentFragment, unknown>;
export const ViewFieldGroupFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ViewFieldGroupFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ViewFieldGroup"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"isVisible"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewFields"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ViewFieldFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ViewFieldFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ViewField"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"isVisible"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"size"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"viewFieldGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}}]}}]} as unknown as DocumentNode<ViewFieldGroupFragmentFragment, unknown>;
@@ -11164,7 +11182,7 @@ export const SwitchBillingPlanDocument = {"kind":"Document","definitions":[{"kin
export const SwitchSubscriptionIntervalDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SwitchSubscriptionInterval"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"switchSubscriptionInterval"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentBillingSubscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"price"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhase"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"start_date"}},{"kind":"Field","name":{"kind":"Name","value":"end_date"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"collectionMethod"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptionItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasReachedCurrentPeriodCap"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"billingProduct"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}}]}}]} as unknown as DocumentNode<SwitchSubscriptionIntervalMutation, SwitchSubscriptionIntervalMutationVariables>;
export const UpdateUsageLimitDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateUsageLimit"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateUsageLimitInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateUsageLimit"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<UpdateUsageLimitMutation, UpdateUsageLimitMutationVariables>;
export const BillingPortalSessionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"BillingPortalSession"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"returnUrlPath"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"forPaymentMethodUpdate"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"billingPortalSession"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"returnUrlPath"},"value":{"kind":"Variable","name":{"kind":"Name","value":"returnUrlPath"}}},{"kind":"Argument","name":{"kind":"Name","value":"forPaymentMethodUpdate"},"value":{"kind":"Variable","name":{"kind":"Name","value":"forPaymentMethodUpdate"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"url"}}]}}]}}]} as unknown as DocumentNode<BillingPortalSessionQuery, BillingPortalSessionQueryVariables>;
-export const GetResourceCreditUsageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"usedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"grantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"rolloverCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalGrantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"unitPriceCents"}}]}}]}}]} as unknown as DocumentNode<GetResourceCreditUsageQuery, GetResourceCreditUsageQueryVariables>;
+export const GetResourceCreditUsageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsExtraGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsTotalGranted"}},{"kind":"Field","name":{"kind":"Name","value":"unitPriceCents"}}]}}]}}]} as unknown as DocumentNode<GetResourceCreditUsageQuery, GetResourceCreditUsageQueryVariables>;
export const ListPlansDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"listPlans"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"listPlans"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"isSellable"}},{"kind":"Field","name":{"kind":"Name","value":"upgradePlanKeys"}},{"kind":"Field","name":{"kind":"Name","value":"downgradePlanKeys"}},{"kind":"Field","name":{"kind":"Name","value":"baseProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingLicensedProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceLicensedFragment"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"resourceCreditProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingLicensedProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceLicensedFragment"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"meteredProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingMeteredProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceMeteredFragment"}}]}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingPriceLicensedFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingPriceLicensed"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"recurringInterval"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageType"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"isSellable"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingPriceMeteredFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingPriceMetered"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"priceUsageType"}},{"kind":"Field","name":{"kind":"Name","value":"recurringInterval"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"tiers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"flatAmount"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"upTo"}}]}}]}}]} as unknown as DocumentNode<ListPlansQuery, ListPlansQueryVariables>;
export const UsageQuotaDefinitionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotaDefinitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotaDefinitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"definitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"allowedOperations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"allowedUnits"}}]}},{"kind":"Field","name":{"kind":"Name","value":"allowedSpenderTypes"}},{"kind":"Field","name":{"kind":"Name","value":"operatorOnlyScopes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderType"}},{"kind":"Field","name":{"kind":"Name","value":"unit"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"isIntraWorkspaceLimitEntitled"}},{"kind":"Field","name":{"kind":"Name","value":"hasAllowancePeriod"}}]}}]}}]} as unknown as DocumentNode<UsageQuotaDefinitionsQuery, UsageQuotaDefinitionsQueryVariables>;
export const UsageQuotaScopeConsumptionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotaScopeConsumption"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UsageQuotaScopeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotaScopeConsumption"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"consumedValue"}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}}]}}]}}]} as unknown as DocumentNode<UsageQuotaScopeConsumptionQuery, UsageQuotaScopeConsumptionQueryVariables>;
@@ -11229,13 +11247,13 @@ export const CreateUnsubscribeTopicDocument = {"kind":"Document","definitions":[
export const DeleteUnsubscribeTopicDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteUnsubscribeTopic"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteUnsubscribeTopic"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}]}}]} as unknown as DocumentNode<DeleteUnsubscribeTopicMutation, DeleteUnsubscribeTopicMutationVariables>;
export const UpdateUnsubscribeTopicDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateUnsubscribeTopic"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateUnsubscribeTopicInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateUnsubscribeTopic"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}}]}}]}}]} as unknown as DocumentNode<UpdateUnsubscribeTopicMutation, UpdateUnsubscribeTopicMutationVariables>;
export const MessageSuppressionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MessageSuppressions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"FindMessageSuppressionsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"messageSuppressions"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"records"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"emailAddress"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"unsubscribeTopicId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}}]}}]}}]} as unknown as DocumentNode<MessageSuppressionsQuery, MessageSuppressionsQueryVariables>;
-export const GetUsageAnalyticsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUsageAnalytics"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UsageAnalyticsInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getUsageAnalytics"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageByUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByOperationType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByApplication"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByModel"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"timeSeries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"userDailyUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"dailyUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetUsageAnalyticsQuery, GetUsageAnalyticsQueryVariables>;
+export const GetUsageAnalyticsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUsageAnalytics"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UsageAnalyticsInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getUsageAnalytics"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageByUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByOperationType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByApplication"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByModel"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"timeSeries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"userDailyUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"dailyUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetUsageAnalyticsQuery, GetUsageAnalyticsQueryVariables>;
export const AddQueryToEventStreamDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AddQueryToEventStream"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AddQuerySubscriptionInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"addQueryToEventStream"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<AddQueryToEventStreamMutation, AddQueryToEventStreamMutationVariables>;
export const RemoveQueryFromEventStreamDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RemoveQueryFromEventStream"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"RemoveQueryFromEventStreamInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"removeQueryFromEventStream"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<RemoveQueryFromEventStreamMutation, RemoveQueryFromEventStreamMutationVariables>;
export const OnEventSubscriptionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"OnEventSubscription"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"eventStreamId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"onEventSubscription"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"eventStreamId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"eventStreamId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"eventStreamId"}},{"kind":"Field","name":{"kind":"Name","value":"objectRecordEventsWithQueryIds"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectRecordEvent"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"action"}},{"kind":"Field","name":{"kind":"Name","value":"objectNameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"recordId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updatedFields"}},{"kind":"Field","name":{"kind":"Name","value":"before"}},{"kind":"Field","name":{"kind":"Name","value":"after"}},{"kind":"Field","name":{"kind":"Name","value":"diff"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"queryIds"}}]}},{"kind":"Field","name":{"kind":"Name","value":"metadataEvents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"metadataName"}},{"kind":"Field","name":{"kind":"Name","value":"recordId"}},{"kind":"Field","name":{"kind":"Name","value":"updatedCollectionHash"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updatedFields"}},{"kind":"Field","name":{"kind":"Name","value":"before"}},{"kind":"Field","name":{"kind":"Name","value":"after"}},{"kind":"Field","name":{"kind":"Name","value":"diff"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"queueJobEvents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"jobId"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"attemptsMade"}},{"kind":"Field","name":{"kind":"Name","value":"failedReason"}},{"kind":"Field","name":{"kind":"Name","value":"progress"}},{"kind":"Field","name":{"kind":"Name","value":"enqueuedAt"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"finishedAt"}}]}}]}}]}}]} as unknown as DocumentNode<OnEventSubscriptionSubscription, OnEventSubscriptionSubscriptionVariables>;
export const DeleteUserAccountDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteUserAccount"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<DeleteUserAccountMutation, DeleteUserAccountMutationVariables>;
export const DeleteUserWorkspaceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteUserWorkspace"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceMemberIdToDelete"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteUserFromWorkspace"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceMemberIdToDelete"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceMemberIdToDelete"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<DeleteUserWorkspaceMutation, DeleteUserWorkspaceMutationVariables>;
-export const GetCurrentUserDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCurrentUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"UserQueryFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"colorScheme"}},{"kind":"Field","name":{"kind":"Name","value":"uiScale"}},{"kind":"Field","name":{"kind":"Name","value":"openRecordIn"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"locale"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","name":{"kind":"Name","value":"dateFormat"}},{"kind":"Field","name":{"kind":"Name","value":"timeFormat"}},{"kind":"Field","name":{"kind":"Name","value":"calendarStartDay"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PartialWorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"DeletedWorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"DeletedWorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ObjectPermissionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ObjectPermission"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"canReadObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"restrictedFields"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RowLevelPermissionPredicateFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RowLevelPermissionPredicate"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"operand"}},{"kind":"Field","name":{"kind":"Name","value":"subFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberSubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicateGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"positionInRowLevelPermissionPredicateGroup"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroupFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroup"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"parentRowLevelPermissionPredicateGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"logicalOperator"}},{"kind":"Field","name":{"kind":"Name","value":"positionInRowLevelPermissionPredicateGroup"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceUrlsFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceUrls"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"price"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhase"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"start_date"}},{"kind":"Field","name":{"kind":"Name","value":"end_date"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"collectionMethod"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptionItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasReachedCurrentPeriodCap"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"billingProduct"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RoleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Role"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"isEditable"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToUsers"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToAgents"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToApiKeys"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspaceFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspace"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"loginToken"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"personalInviteToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"sso"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspacesFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspaces"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignIn"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignUp"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"User"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"hasPassword"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}},{"kind":"Field","name":{"kind":"Name","value":"supportUserHash"}},{"kind":"Field","name":{"kind":"Name","value":"onboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"previousOnboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"isWorkspaceCreator"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMember"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMembers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PartialWorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"deletedWorkspaceMembers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"DeletedWorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentUserWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"permissionFlags"}},{"kind":"Field","name":{"kind":"Name","value":"isImpersonating"}},{"kind":"Field","name":{"kind":"Name","value":"objectsPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ObjectPermissionFragment"}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RowLevelPermissionPredicateFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicateGroups"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroupFragment"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationMethodSummary"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationMethodId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"strategy"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"isPublicInviteLinkEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isCampaignClickTrackingEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isCampaignOpenTrackingEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceDiscoverability"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"subdomain"}},{"kind":"Field","name":{"kind":"Name","value":"customDomain"}},{"kind":"Field","name":{"kind":"Name","value":"hasValidSignedEnterpriseKey"}},{"kind":"Field","name":{"kind":"Name","value":"hasValidEnterpriseValidityToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCustomApplication"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}},{"kind":"Field","name":{"kind":"Name","value":"installedApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"isCustomDomainEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceUrlsFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentBillingSubscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingCustomer"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasPaymentMethod"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingEntitlements"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMembersCount"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRole"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RoleFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"aiChatModelTier"}},{"kind":"Field","name":{"kind":"Name","value":"aiAgentModelTier"}},{"kind":"Field","name":{"kind":"Name","value":"isAutoModelSelectionEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"aiModelIdByTier"}},{"kind":"Field","name":{"kind":"Name","value":"aiAdditionalInstructions"}},{"kind":"Field","name":{"kind":"Name","value":"isTwoFactorAuthenticationEnforced"}},{"kind":"Field","name":{"kind":"Name","value":"trashRetentionDays"}},{"kind":"Field","name":{"kind":"Name","value":"eventLogRetentionDays"}},{"kind":"Field","name":{"kind":"Name","value":"editableProfileFields"}},{"kind":"Field","name":{"kind":"Name","value":"isInternalMessagesImportEnabled"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspacesFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"userVars"}}]}}]} as unknown as DocumentNode<GetCurrentUserQuery, GetCurrentUserQueryVariables>;
+export const GetCurrentUserDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCurrentUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"UserQueryFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"colorScheme"}},{"kind":"Field","name":{"kind":"Name","value":"uiScale"}},{"kind":"Field","name":{"kind":"Name","value":"openRecordIn"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"locale"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","name":{"kind":"Name","value":"dateFormat"}},{"kind":"Field","name":{"kind":"Name","value":"timeFormat"}},{"kind":"Field","name":{"kind":"Name","value":"calendarStartDay"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PartialWorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"DeletedWorkspaceMemberQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"DeletedWorkspaceMember"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ObjectPermissionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ObjectPermission"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"canReadObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"restrictedFields"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RowLevelPermissionPredicateFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RowLevelPermissionPredicate"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"operand"}},{"kind":"Field","name":{"kind":"Name","value":"subFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberSubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicateGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"positionInRowLevelPermissionPredicateGroup"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroupFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroup"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"parentRowLevelPermissionPredicateGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"logicalOperator"}},{"kind":"Field","name":{"kind":"Name","value":"positionInRowLevelPermissionPredicateGroup"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceUrlsFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceUrls"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"price"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhase"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"start_date"}},{"kind":"Field","name":{"kind":"Name","value":"end_date"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"collectionMethod"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptionItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasReachedCurrentPeriodCap"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"billingProduct"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RoleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Role"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"isEditable"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToUsers"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToAgents"}},{"kind":"Field","name":{"kind":"Name","value":"canBeAssignedToApiKeys"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspaceFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspace"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"loginToken"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"personalInviteToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"sso"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspacesFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspaces"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignIn"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignUp"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserQueryFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"User"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"hasPassword"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}},{"kind":"Field","name":{"kind":"Name","value":"supportUserHash"}},{"kind":"Field","name":{"kind":"Name","value":"onboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"previousOnboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"isWorkspaceCreator"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMember"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMembers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PartialWorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"deletedWorkspaceMembers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"DeletedWorkspaceMemberQueryFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentUserWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"permissionFlags"}},{"kind":"Field","name":{"kind":"Name","value":"isImpersonating"}},{"kind":"Field","name":{"kind":"Name","value":"objectsPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ObjectPermissionFragment"}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RowLevelPermissionPredicateFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"rowLevelPermissionPredicateGroups"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RowLevelPermissionPredicateGroupFragment"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationMethodSummary"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationMethodId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"strategy"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentWorkspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"isPublicInviteLinkEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isCampaignClickTrackingEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isCampaignOpenTrackingEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceDiscoverability"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isGoogleAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isMicrosoftAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"isPasswordAuthBypassEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"subdomain"}},{"kind":"Field","name":{"kind":"Name","value":"customDomain"}},{"kind":"Field","name":{"kind":"Name","value":"hasValidSignedEnterpriseKey"}},{"kind":"Field","name":{"kind":"Name","value":"hasValidEnterpriseValidityToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCustomApplication"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}},{"kind":"Field","name":{"kind":"Name","value":"installedApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"isCustomDomainEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceUrlsFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentBillingSubscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingCustomer"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasPaymentMethod"}},{"kind":"Field","name":{"kind":"Name","value":"userCreditsFallback"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingEntitlements"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMembersCount"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRole"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RoleFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"aiChatModelTier"}},{"kind":"Field","name":{"kind":"Name","value":"aiAgentModelTier"}},{"kind":"Field","name":{"kind":"Name","value":"isAutoModelSelectionEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"aiModelIdByTier"}},{"kind":"Field","name":{"kind":"Name","value":"aiAdditionalInstructions"}},{"kind":"Field","name":{"kind":"Name","value":"isTwoFactorAuthenticationEnforced"}},{"kind":"Field","name":{"kind":"Name","value":"trashRetentionDays"}},{"kind":"Field","name":{"kind":"Name","value":"eventLogRetentionDays"}},{"kind":"Field","name":{"kind":"Name","value":"editableProfileFields"}},{"kind":"Field","name":{"kind":"Name","value":"isInternalMessagesImportEnabled"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspacesFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"userVars"}}]}}]} as unknown as DocumentNode<GetCurrentUserQuery, GetCurrentUserQueryVariables>;
export const CreateValidationRuleDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateValidationRule"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateValidationRuleInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createValidationRule"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ValidationRuleFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ValidationRuleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ValidationRule"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"errorFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"expression"}},{"kind":"Field","name":{"kind":"Name","value":"message"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]} as unknown as DocumentNode<CreateValidationRuleMutation, CreateValidationRuleMutationVariables>;
export const DeleteValidationRuleDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteValidationRule"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteValidationRule"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ValidationRuleFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ValidationRuleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ValidationRule"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"errorFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"expression"}},{"kind":"Field","name":{"kind":"Name","value":"message"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]} as unknown as DocumentNode<DeleteValidationRuleMutation, DeleteValidationRuleMutationVariables>;
export const UpdateValidationRuleDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateValidationRule"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateValidationRuleInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateValidationRule"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ValidationRuleFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ValidationRuleFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ValidationRule"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"errorFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"expression"}},{"kind":"Field","name":{"kind":"Name","value":"message"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]} as unknown as DocumentNode<UpdateValidationRuleMutation, UpdateValidationRuleMutationVariables>;
diff --git a/packages/twenty-front/src/modules/ai/components/internal/__stories__/AiChatContextUsageButton.stories.tsx b/packages/twenty-front/src/modules/ai/components/internal/__stories__/AiChatContextUsageButton.stories.tsx
index 4a5f88240a5..6c6555d1b00 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/__stories__/AiChatContextUsageButton.stories.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/__stories__/AiChatContextUsageButton.stories.tsx
@@ -74,7 +74,7 @@ const UsageStory = ({
limitValue: limit,
consumedValue: consumed,
periodEnd: null,
- kind: 'allowance',
+ kind: 'workspaceAllowance',
},
},
},
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatQuotaExhaustedKind.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatQuotaExhaustedKind.test.ts
index a12e63e24ec..751d2cfa612 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatQuotaExhaustedKind.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatQuotaExhaustedKind.test.ts
@@ -12,9 +12,12 @@ describe('getAiChatQuotaExhaustedKind', () => {
it('tells a spent allowance apart from a configured limit', () => {
expect(
getAiChatQuotaExhaustedKind(
- buildError({ code: 'QUOTA_EXHAUSTED', exhaustedKind: 'allowance' }),
+ buildError({
+ code: 'QUOTA_EXHAUSTED',
+ exhaustedKind: 'workspaceAllowance',
+ }),
),
- ).toBe('allowance');
+ ).toBe('workspaceAllowance');
expect(
getAiChatQuotaExhaustedKind(
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatCreditsExhaustedError.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatCreditsExhaustedError.test.ts
index eb25431e9da..2448539805c 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatCreditsExhaustedError.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatCreditsExhaustedError.test.ts
@@ -20,7 +20,10 @@ describe('isAiChatCreditsExhaustedError', () => {
expect(
isAiChatCreditsExhaustedError(
- buildError({ code: 'QUOTA_EXHAUSTED', exhaustedKind: 'allowance' }),
+ buildError({
+ code: 'QUOTA_EXHAUSTED',
+ exhaustedKind: 'workspaceAllowance',
+ }),
),
).toBe(true);
});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatUsageLimitReached.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatUsageLimitReached.test.ts
index 0f6c8006bdd..c62ad031f1f 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatUsageLimitReached.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatUsageLimitReached.test.ts
@@ -37,7 +37,7 @@ describe('isAiChatUsageLimitReached', () => {
it('ignores the plan allowance, which the credits banner owns', () => {
expect(
isAiChatUsageLimitReached(
- buildUsage({ consumedValue: 1000, kind: 'allowance' }),
+ buildUsage({ consumedValue: 1000, kind: 'workspaceAllowance' }),
),
).toBe(false);
});
diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatQuotaExhaustedKind.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatQuotaExhaustedKind.ts
index 36b66da31aa..3b253c814ee 100644
--- a/packages/twenty-front/src/modules/ai/utils/getAiChatQuotaExhaustedKind.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatQuotaExhaustedKind.ts
@@ -2,16 +2,16 @@ import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
import { getGraphqlErrorExtensionsFromError } from '~/utils/get-graphql-error-extensions-from-error.util';
import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
-// An unreadable refusal is reported as a limit: guessing 'allowance' would flip the workspace into the upgrade banner
+// An unreadable refusal is reported as a limit: guessing 'workspaceAllowance' would flip the workspace into the upgrade banner
export const getAiChatQuotaExhaustedKind = (
error: unknown,
-): 'limit' | 'allowance' | null => {
+): 'limit' | 'workspaceAllowance' | null => {
if (!isGraphqlErrorOfType(error, AiChatErrorCode.QUOTA_EXHAUSTED)) {
return null;
}
return getGraphqlErrorExtensionsFromError(error)?.exhaustedKind ===
- 'allowance'
- ? 'allowance'
+ 'workspaceAllowance'
+ ? 'workspaceAllowance'
: 'limit';
};
diff --git a/packages/twenty-front/src/modules/ai/utils/isAiChatCreditsExhaustedError.ts b/packages/twenty-front/src/modules/ai/utils/isAiChatCreditsExhaustedError.ts
index e113beef470..74d8fc46479 100644
--- a/packages/twenty-front/src/modules/ai/utils/isAiChatCreditsExhaustedError.ts
+++ b/packages/twenty-front/src/modules/ai/utils/isAiChatCreditsExhaustedError.ts
@@ -4,4 +4,4 @@ import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
export const isAiChatCreditsExhaustedError = (error: unknown): boolean =>
isGraphqlErrorOfType(error, AiChatErrorCode.CREDITS_EXHAUSTED) ||
- getAiChatQuotaExhaustedKind(error) === 'allowance';
+ getAiChatQuotaExhaustedKind(error) === 'workspaceAllowance';
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceBillingContent.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceBillingContent.tsx
index 4ea32e9b2bd..50a6f13fe50 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceBillingContent.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceBillingContent.tsx
@@ -207,23 +207,23 @@ export const SettingsAdminWorkspaceBillingContent = ({
{
Icon: IconChartBar,
label: t`Credits used`,
- value: `${formatCredits(usage.usedCredits)} / ${formatCredits(usage.totalGrantedCredits)}`,
+ value: `${formatCredits(usage.workspaceCreditsUsed)} / ${formatCredits(usage.workspaceCreditsTotalGranted)}`,
},
...(!isTrialing
? [
{
Icon: IconCoins,
label: t`Base credits`,
- value: formatCredits(usage.grantedCredits),
+ value: formatCredits(usage.workspaceCreditsGranted),
},
]
: []),
- ...(usage.rolloverCredits > 0
+ ...(usage.workspaceCreditsExtraGranted > 0
? [
{
Icon: IconCoins,
label: t`Granted credits`,
- value: formatCredits(usage.rolloverCredits),
+ value: formatCredits(usage.workspaceCreditsExtraGranted),
},
]
: []),
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel.ts b/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel.ts
index 7cc85f03e67..1e7ee64ef65 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel.ts
@@ -20,11 +20,11 @@ export const GET_WORKSPACE_BILLING_ADMIN_PANEL = gql`
usage {
periodStart
periodEnd
- usedCredits
- grantedCredits
- rolloverCredits
- totalGrantedCredits
- remainingCredits
+ workspaceCreditsUsed
+ workspaceCreditsGranted
+ workspaceCreditsExtraGranted
+ workspaceCreditsTotalGranted
+ workspaceCreditsRemaining
}
subscription {
stripeSubscriptionId
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx
index 284dd659c70..bf79535aa98 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx
@@ -160,13 +160,17 @@ export const SettingsBillingCreditsSection = ({
const { getResourceCreditUsage } = useGetResourceCreditUsage();
- const { usedCredits, grantedCredits, totalGrantedCredits, rolloverCredits } =
- getResourceCreditUsage();
+ const {
+ workspaceCreditsUsed,
+ workspaceCreditsGranted,
+ workspaceCreditsTotalGranted,
+ workspaceCreditsExtraGranted,
+ } = getResourceCreditUsage();
const intervalLabel = getIntervalLabel(isMonthlyPlan);
const packageCredits = currentResourceCreditBillingPrice?.creditAmount;
const nextCreditsByPeriod = nextResourceCreditPrice?.creditAmount;
- const displayedGrantedCredits = packageCredits ?? grantedCredits;
+ const displayedGrantedCredits = packageCredits ?? workspaceCreditsGranted;
const canCancelCreditPackSwitch =
!isCancellationScheduled &&
!shouldUpdatePayment &&
@@ -174,26 +178,31 @@ export const SettingsBillingCreditsSection = ({
packageCredits !== nextCreditsByPeriod;
const remainingCreditsPercentage =
- totalGrantedCredits > 0
- ? ((totalGrantedCredits - usedCredits) / totalGrantedCredits) * 100
+ workspaceCreditsTotalGranted > 0
+ ? ((workspaceCreditsTotalGranted - workspaceCreditsUsed) /
+ workspaceCreditsTotalGranted) *
+ 100
: 0;
const clampedRemainingCreditsPercentage = Math.min(
100,
Math.max(0, remainingCreditsPercentage),
);
- // rolloverCredits sums every active grant, not just the rolled-over ones
- const extraCredits = rolloverCredits;
- const hasExtraCredits = extraCredits > 0;
+ const hasExtraCredits = workspaceCreditsExtraGranted > 0;
- const usedCreditsDisplay = formatNumber(usedCredits, { decimals: 2 });
- const grantedCreditsDisplay = formatNumber(displayedGrantedCredits, {
+ const workspaceCreditsUsedDisplay = formatNumber(workspaceCreditsUsed, {
decimals: 2,
});
- const totalGrantedCreditsDisplay = formatNumber(totalGrantedCredits, {
+ const grantedCreditsDisplay = formatNumber(displayedGrantedCredits, {
decimals: 2,
});
- const extraCreditsDisplay = formatNumber(extraCredits, {
+ const workspaceCreditsTotalGrantedDisplay = formatNumber(
+ workspaceCreditsTotalGranted,
+ {
+ decimals: 2,
+ },
+ );
+ const extraCreditsDisplay = formatNumber(workspaceCreditsExtraGranted, {
decimals: 2,
});
const rolloverCapDisplay = formatNumber(displayedGrantedCredits * 2, {
@@ -263,14 +272,14 @@ export const SettingsBillingCreditsSection = ({
{isTrialing ? (
<StyledRolloverText>
<StyledMetricValue>
- {totalGrantedCreditsDisplay}
+ {workspaceCreditsTotalGrantedDisplay}
</StyledMetricValue>
{t`credits available during the trial period`}
</StyledRolloverText>
) : hasExtraCredits ? (
<StyledRolloverText>
<StyledMetricValue>
- {totalGrantedCreditsDisplay}
+ {workspaceCreditsTotalGrantedDisplay}
</StyledMetricValue>
{t`credits available (including ${extraCreditsDisplay} on top of your plan)`}
</StyledRolloverText>
@@ -282,7 +291,9 @@ export const SettingsBillingCreditsSection = ({
)}
<StyledUsageMetrics>
<span>
- <StyledMetricValue>{usedCreditsDisplay}</StyledMetricValue>{' '}
+ <StyledMetricValue>
+ {workspaceCreditsUsedDisplay}
+ </StyledMetricValue>{' '}
{t`credits used`}
</span>
<span>·</span>
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitInvocationUnitLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitInvocationUnitLabels.ts
index 402a1e13bd9..bfe1907c2f7 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitInvocationUnitLabels.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitInvocationUnitLabels.ts
@@ -15,6 +15,10 @@ export const USAGE_LIMIT_INVOCATION_UNIT_LABELS: Partial<
name: msg`Searches`,
suffix: msg`searches`,
},
+ [UsageOperationType.AI_WORKFLOW_WEB_SEARCH]: {
+ name: msg`Searches`,
+ suffix: msg`searches`,
+ },
[UsageOperationType.EMAIL_SEND]: { name: msg`Emails`, suffix: msg`emails` },
[UsageOperationType.MESSAGE_CAMPAIGN_SEND]: {
name: msg`Emails`,
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
index 645a083c01b..45e2d62ebe0 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitOperationTypeIcons.ts
@@ -28,6 +28,7 @@ export const USAGE_LIMIT_OPERATION_TYPE_ICONS: Record<
[UsageOperationType.WORKFLOW_EXECUTION]: IconSettingsAutomation,
[UsageOperationType.CODE_EXECUTION]: IconCode,
[UsageOperationType.WEB_SEARCH]: IconSearch,
+ [UsageOperationType.AI_WORKFLOW_WEB_SEARCH]: IconSearch,
[UsageOperationType.CALL_RECORDING]: IconPhone,
[UsageOperationType.EMAIL_SEND]: IconMail,
[UsageOperationType.MESSAGE_CAMPAIGN_SEND]: IconSend,
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitIcons.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitIcons.ts
index e1090b59ef3..be979cf895b 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitIcons.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitIcons.ts
@@ -13,6 +13,7 @@ import { UsageUnit } from '~/generated-metadata/graphql';
export const USAGE_LIMIT_UNIT_ICONS: Record<UsageUnit, IconComponent> = {
[UsageUnit.CREDIT]: IconCoins,
+ [UsageUnit.USER_CREDIT]: IconCoins,
[UsageUnit.TOKEN]: IconNumber123,
[UsageUnit.INVOCATION]: IconNumber123,
[UsageUnit.MINUTE]: IconClock,
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitLabels.ts
index 756605b06f8..c0065565a9b 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitLabels.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitLabels.ts
@@ -5,6 +5,7 @@ import { UsageUnit } from '~/generated-metadata/graphql';
export const USAGE_LIMIT_UNIT_LABELS: Record<UsageUnit, UsageLimitUnitLabel> = {
[UsageUnit.CREDIT]: { name: msg`Credits`, suffix: msg`credits` },
+ [UsageUnit.USER_CREDIT]: { name: msg`User credits`, suffix: msg`credits` },
[UsageUnit.TOKEN]: { name: msg`Tokens`, suffix: msg`tokens` },
[UsageUnit.INVOCATION]: { name: msg`Operations`, suffix: msg`operations` },
[UsageUnit.MINUTE]: { name: msg`Minutes`, suffix: msg`min` },
diff --git a/packages/twenty-front/src/modules/settings/billing/graphql/queries/getResourceCreditUsage.ts b/packages/twenty-front/src/modules/settings/billing/graphql/queries/getResourceCreditUsage.ts
index 62f73c6b077..dcc3959e462 100644
--- a/packages/twenty-front/src/modules/settings/billing/graphql/queries/getResourceCreditUsage.ts
+++ b/packages/twenty-front/src/modules/settings/billing/graphql/queries/getResourceCreditUsage.ts
@@ -4,10 +4,10 @@ export const GET_RESOURCE_CREDIT_USAGE = gql`
query GetResourceCreditUsage {
getResourceCreditUsage {
productKey
- usedCredits
- grantedCredits
- rolloverCredits
- totalGrantedCredits
+ workspaceCreditsUsed
+ workspaceCreditsGranted
+ workspaceCreditsExtraGranted
+ workspaceCreditsTotalGranted
unitPriceCents
}
}
diff --git a/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx b/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
index 06a86913477..f28f67c23f9 100644
--- a/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
+++ b/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
@@ -65,7 +65,10 @@ export const UsageBreakdownPieSection = ({
return null;
}
- const total = breakdownData.reduce((sum, item) => sum + item.creditsUsed, 0);
+ const total = breakdownData.reduce(
+ (sum, item) => sum + item.workspaceCreditsUsed,
+ 0,
+ );
// Operation types are a fixed vocabulary translated here; other breakdowns name workspace data only the server resolves
const formatLabel = ({
@@ -86,7 +89,7 @@ export const UsageBreakdownPieSection = ({
const pieData = breakdownData.map((item, index) => ({
id: formatLabel(item),
- value: item.creditsUsed,
+ value: item.workspaceCreditsUsed,
color: getColorSchemeByIndex(colorRegistry, index).solid,
}));
diff --git a/packages/twenty-front/src/modules/settings/usage/components/UsageByUserTableSection.tsx b/packages/twenty-front/src/modules/settings/usage/components/UsageByUserTableSection.tsx
index 61650889aa4..f112ddcf54b 100644
--- a/packages/twenty-front/src/modules/settings/usage/components/UsageByUserTableSection.tsx
+++ b/packages/twenty-front/src/modules/settings/usage/components/UsageByUserTableSection.tsx
@@ -125,7 +125,7 @@ export const UsageByUserTableSection = ({
{item.label ?? item.key}
</TableCell>
<TableCell align="right">
- {formatUsageValue(item.creditsUsed)}
+ {formatUsageValue(item.workspaceCreditsUsed)}
</TableCell>
<TableCell align="center">
<StyledIconChevronRightContainer>
diff --git a/packages/twenty-front/src/modules/settings/usage/components/UsageDailyChartSection.tsx b/packages/twenty-front/src/modules/settings/usage/components/UsageDailyChartSection.tsx
index a1e1de4806f..6ba13ba9d56 100644
--- a/packages/twenty-front/src/modules/settings/usage/components/UsageDailyChartSection.tsx
+++ b/packages/twenty-front/src/modules/settings/usage/components/UsageDailyChartSection.tsx
@@ -66,7 +66,7 @@ export const UsageDailyChartSection = ({
label: chartLabel,
data: timeSeries.map((point) => ({
x: formatDate(point.date, 'MMM d'),
- y: point.creditsUsed,
+ y: point.workspaceCreditsUsed,
})),
},
];
diff --git a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
index f79e1ef8664..9ee35dae622 100644
--- a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
+++ b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
@@ -13,6 +13,7 @@ export const USAGE_OPERATION_TYPE_LABELS: Record<
[UsageOperationType.WORKFLOW_EXECUTION]: msg`Workflow Execution`,
[UsageOperationType.CODE_EXECUTION]: msg`Code Execution`,
[UsageOperationType.WEB_SEARCH]: msg`Web Search`,
+ [UsageOperationType.AI_WORKFLOW_WEB_SEARCH]: msg`Agent Web Search`,
[UsageOperationType.CALL_RECORDING]: msg`Call Recording`,
[UsageOperationType.EMAIL_SEND]: msg`Email Send`,
[UsageOperationType.MESSAGE_CAMPAIGN_SEND]: msg`Campaign Email Send`,
diff --git a/packages/twenty-front/src/modules/settings/usage/graphql/queries/getUsageAnalytics.ts b/packages/twenty-front/src/modules/settings/usage/graphql/queries/getUsageAnalytics.ts
index 060a043a340..7cd652b7f7d 100644
--- a/packages/twenty-front/src/modules/settings/usage/graphql/queries/getUsageAnalytics.ts
+++ b/packages/twenty-front/src/modules/settings/usage/graphql/queries/getUsageAnalytics.ts
@@ -6,24 +6,24 @@ export const GET_USAGE_ANALYTICS = gql`
usageByUser {
key
label
- creditsUsed
+ workspaceCreditsUsed
}
usageByOperationType {
key
- creditsUsed
+ workspaceCreditsUsed
}
usageByApplication {
key
label
- creditsUsed
+ workspaceCreditsUsed
}
usageByModel {
key
- creditsUsed
+ workspaceCreditsUsed
}
timeSeries {
date
- creditsUsed
+ workspaceCreditsUsed
}
periodStart
periodEnd
@@ -31,7 +31,7 @@ export const GET_USAGE_ANALYTICS = gql`
userWorkspaceId
dailyUsage {
date
- creditsUsed
+ workspaceCreditsUsed
}
}
}
diff --git a/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts b/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
index 35d853f1fbd..be90e598cfe 100644
--- a/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
+++ b/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
@@ -100,6 +100,7 @@ export const USER_QUERY_FRAGMENT = gql`
billingCustomer {
id
hasPaymentMethod
+ userCreditsFallback
}
billingSubscriptions {
...BillingSubscriptionFragment
diff --git a/packages/twenty-front/src/pages/settings/billing/SettingsUsageUserDetail.tsx b/packages/twenty-front/src/pages/settings/billing/SettingsUsageUserDetail.tsx
index 101aeab20c8..19ab75885bd 100644
--- a/packages/twenty-front/src/pages/settings/billing/SettingsUsageUserDetail.tsx
+++ b/packages/twenty-front/src/pages/settings/billing/SettingsUsageUserDetail.tsx
@@ -58,7 +58,7 @@ export const SettingsUsageUserDetail = () => {
const totalCredits = analytics
? analytics.usageByOperationType.reduce(
- (sum, item) => sum + item.creditsUsed,
+ (sum, item) => sum + item.workspaceCreditsUsed,
0,
)
: 0;
diff --git a/packages/twenty-front/src/testing/graphqlMocks.ts b/packages/twenty-front/src/testing/graphqlMocks.ts
index 9c383672533..13f91660606 100644
--- a/packages/twenty-front/src/testing/graphqlMocks.ts
+++ b/packages/twenty-front/src/testing/graphqlMocks.ts
@@ -552,10 +552,10 @@ export const graphqlMocks = {
{
__typename: 'BillingResourceCreditUsage',
productKey: 'RESOURCE_CREDIT',
- usedCredits: 1000,
- grantedCredits: 500000,
- rolloverCredits: 0,
- totalGrantedCredits: 500000,
+ workspaceCreditsUsed: 1000,
+ workspaceCreditsGranted: 500000,
+ workspaceCreditsExtraGranted: 0,
+ workspaceCreditsTotalGranted: 500000,
unitPriceCents: 1,
},
],
diff --git a/packages/twenty-server/src/database/clickhouse/migrations/014-add-user-credits-used-micro-to-usage-event.sql b/packages/twenty-server/src/database/clickhouse/migrations/014-add-user-credits-used-micro-to-usage-event.sql
new file mode 100644
index 00000000000..82a3e69fd14
--- /dev/null
+++ b/packages/twenty-server/src/database/clickhouse/migrations/014-add-user-credits-used-micro-to-usage-event.sql
@@ -0,0 +1,35 @@
+ALTER TABLE usageEvent ADD COLUMN IF NOT EXISTS userCreditsUsedMicro Int64 DEFAULT 0;
+
+ALTER TABLE usageEvent DROP PROJECTION IF EXISTS consumption_by_scope;
+
+ALTER TABLE usageEvent ADD PROJECTION IF NOT EXISTS consumption_by_scope (
+ SELECT
+ workspaceId,
+ resourceType,
+ toStartOfDay(timestamp, 'UTC'),
+ operationType,
+ unit,
+ userWorkspaceId,
+ apiKeyId,
+ applicationId,
+ agentId,
+ workflowId,
+ logicFunctionId,
+ sum(creditsUsedMicro) AS creditsUsedMicro,
+ sum(userCreditsUsedMicro) AS userCreditsUsedMicro,
+ sum(quantity) AS quantity
+ GROUP BY
+ workspaceId, resourceType, toStartOfDay(timestamp, 'UTC'), operationType, unit, userWorkspaceId, apiKeyId, applicationId, agentId, workflowId, logicFunctionId
+);
+
+ALTER TABLE usageEvent DROP PROJECTION IF EXISTS billing_by_workspace_period;
+
+ALTER TABLE usageEvent ADD PROJECTION IF NOT EXISTS billing_by_workspace_period (
+ SELECT
+ workspaceId,
+ periodStart,
+ sum(creditsUsedMicro) AS totalCreditsUsedMicro,
+ sum(userCreditsUsedMicro) AS userCreditsUsedMicro
+ GROUP BY
+ workspaceId, periodStart
+);
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-instance-command-fast-1792154197828-add-user-credits-fallback-to-billing-customer.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-instance-command-fast-1792154197828-add-user-credits-fallback-to-billing-customer.ts
new file mode 100644
index 00000000000..2b5f20bcb54
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-instance-command-fast-1792154197828-add-user-credits-fallback-to-billing-customer.ts
@@ -0,0 +1,37 @@
+import { type QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { type FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.49.0', 1792154197828)
+export class AddUserCreditsFallbackToBillingCustomerFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ if (!(await this.hasBillingCustomerTable(queryRunner))) {
+ return;
+ }
+
+ await queryRunner.query(
+ `ALTER TABLE "core"."billingCustomer" ADD COLUMN IF NOT EXISTS "userCreditsFallback" character varying NOT NULL DEFAULT 'WORKSPACE_CREDITS'`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ if (!(await this.hasBillingCustomerTable(queryRunner))) {
+ return;
+ }
+
+ await queryRunner.query(
+ `ALTER TABLE "core"."billingCustomer" DROP COLUMN IF EXISTS "userCreditsFallback"`,
+ );
+ }
+
+ private async hasBillingCustomerTable(
+ queryRunner: QueryRunner,
+ ): Promise<boolean> {
+ const rows = await queryRunner.query(
+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'billingCustomer'`,
+ );
+
+ return rows.length > 0;
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 0bd0057ee0e..2b113fee973 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -244,6 +244,7 @@ import { AddWidgetAvailabilityToFrontComponentFastInstanceCommand } from 'src/da
import { AddIdentifyAccountLogicFunctionAndExternalAccountIdFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-48/2-48-instance-command-fast-1791975194413-add-identify-account-logic-function-and-external-account-id';
import { AddApplicationRegistrationVersionsFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-48/2-48-instance-command-fast-1792077317736-add-application-registration-versions';
import { BackfillApplicationRegistrationVersionsSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-48/2-48-instance-command-slow-1792077361238-backfill-application-registration-versions';
+import { AddUserCreditsFallbackToBillingCustomerFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-49/2-49-instance-command-fast-1792154197828-add-user-credits-fallback-to-billing-customer';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -490,4 +491,5 @@ export const INSTANCE_COMMANDS = [
AddIdentifyAccountLogicFunctionAndExternalAccountIdFastInstanceCommand,
AddApplicationRegistrationVersionsFastInstanceCommand,
BackfillApplicationRegistrationVersionsSlowInstanceCommand,
+ AddUserCreditsFallbackToBillingCustomerFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage.dto.ts
index 5e167792b9b..fb81509d2f9 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage.dto.ts
@@ -9,17 +9,20 @@ export class AdminPanelWorkspaceUsageDTO {
periodEnd: Date;
@Field(() => Float)
- usedCredits: number;
+ workspaceCreditsUsed: number;
@Field(() => Float)
- grantedCredits: number;
+ workspaceCreditsGranted: number;
@Field(() => Float)
- rolloverCredits: number;
+ workspaceCreditsExtraGranted: number;
@Field(() => Float)
- totalGrantedCredits: number;
+ workspaceCreditsTotalGranted: number;
@Field(() => Float)
- remainingCredits: number;
+ workspaceCreditsRemaining: number;
+
+ @Field(() => Float)
+ userCreditsUsed: number;
}
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
index d5c4bb903ce..4d6c259555f 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
@@ -274,19 +274,27 @@ export class AdminPanelBillingService {
return null;
}
- const usedCredits = toDisplayCredits(usage.usedCredits);
- const grantedCredits = toDisplayCredits(usage.grantedCredits);
- const rolloverCredits = toDisplayCredits(usage.rolloverCredits);
- const totalGrantedCredits = toDisplayCredits(usage.totalGrantedCredits);
+ const workspaceCreditsUsed = toDisplayCredits(usage.workspaceCreditsUsed);
+ const workspaceCreditsGranted = toDisplayCredits(
+ usage.workspaceCreditsGranted,
+ );
+ const workspaceCreditsExtraGranted = toDisplayCredits(
+ usage.workspaceCreditsExtraGranted,
+ );
+ const workspaceCreditsTotalGranted = toDisplayCredits(
+ usage.workspaceCreditsTotalGranted,
+ );
return {
periodStart: usage.periodStart,
periodEnd: usage.periodEnd,
- usedCredits,
- grantedCredits,
- rolloverCredits,
- totalGrantedCredits,
- remainingCredits: totalGrantedCredits - usedCredits,
+ workspaceCreditsUsed,
+ workspaceCreditsGranted,
+ workspaceCreditsExtraGranted,
+ workspaceCreditsTotalGranted,
+ workspaceCreditsRemaining:
+ workspaceCreditsTotalGranted - workspaceCreditsUsed,
+ userCreditsUsed: toDisplayCredits(usage.userCreditsUsed),
};
} catch (error) {
this.logger.warn(
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service.ts
index 25e47d84208..f3356b7e285 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service.ts
@@ -43,7 +43,10 @@ export class AdminPanelUsageLimitService {
const overridingUsageLimit = usageLimits.find((usageLimit) =>
doesUsageLimitRowSuppressDefault({
scope: buildUsageLimitScope(usageLimit),
- usageLimitDefault,
+ usageLimitDefault: {
+ ...usageLimitDefault,
+ operationTypes: [usageLimitDefault.operationType],
+ },
}),
);
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
index 53432780333..ad08c118551 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
@@ -22,7 +22,9 @@ import { BillingUpdateDTO } from 'src/engine/core-modules/billing/dtos/billing-u
import { BillingCheckoutSessionInput } from 'src/engine/core-modules/billing/dtos/inputs/billing-checkout-session.input';
import { BillingSessionInput } from 'src/engine/core-modules/billing/dtos/inputs/billing-session.input';
import { BillingSwitchPlanInput } from 'src/engine/core-modules/billing/dtos/inputs/billing-switch-plan.input';
+import { BillingUpdateUserCreditsFallbackInput } from 'src/engine/core-modules/billing/dtos/inputs/billing-update-user-credits-fallback.input';
import { BillingUpdateSubscriptionItemPriceInput } from 'src/engine/core-modules/billing/dtos/inputs/billing-update-subscription-item-price.input';
+import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
import { BillingPlanService } from 'src/engine/core-modules/billing/services/billing-plan.service';
import { BillingPortalWorkspaceService } from 'src/engine/core-modules/billing/services/billing-portal.workspace-service';
import { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';
@@ -408,6 +410,31 @@ export class BillingResolver {
};
}
+ @Mutation(() => BillingCustomerEntity)
+ @UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: true,
+ playground: true,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ SettingsPermissionGuard(PermissionFlagType.BILLING),
+ )
+ async updateUserCreditsFallback(
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @Args() { userCreditsFallback }: BillingUpdateUserCreditsFallbackInput,
+ ): Promise<BillingCustomerEntity> {
+ return this.billingService.updateUserCreditsFallbackOrThrow({
+ workspaceId: workspace.id,
+ userCreditsFallback,
+ });
+ }
+
@Query(() => [BillingPlanDTO])
@UseGuards(
AuthPrincipalGuard({
@@ -502,10 +529,15 @@ export class BillingResolver {
return usageData.map((item) => ({
...item,
- usedCredits: toDisplayCredits(item.usedCredits),
- grantedCredits: toDisplayCredits(item.grantedCredits),
- rolloverCredits: toDisplayCredits(item.rolloverCredits),
- totalGrantedCredits: toDisplayCredits(item.totalGrantedCredits),
+ workspaceCreditsUsed: toDisplayCredits(item.workspaceCreditsUsed),
+ userCreditsUsed: toDisplayCredits(item.userCreditsUsed),
+ workspaceCreditsGranted: toDisplayCredits(item.workspaceCreditsGranted),
+ workspaceCreditsExtraGranted: toDisplayCredits(
+ item.workspaceCreditsExtraGranted,
+ ),
+ workspaceCreditsTotalGranted: toDisplayCredits(
+ item.workspaceCreditsTotalGranted,
+ ),
unitPriceCents: item.unitPriceCents * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
}));
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto.ts b/packages/twenty-server/src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto.ts
index 0e16fda3e05..e1ffbf67ef8 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto.ts
@@ -14,16 +14,19 @@ export class BillingResourceCreditUsageDTO {
periodEnd: Date;
@Field(() => Float)
- usedCredits: number;
+ workspaceCreditsUsed: number;
@Field(() => Float)
- grantedCredits: number;
+ userCreditsUsed: number;
@Field(() => Float)
- rolloverCredits: number;
+ workspaceCreditsGranted: number;
@Field(() => Float)
- totalGrantedCredits: number;
+ workspaceCreditsExtraGranted: number;
+
+ @Field(() => Float)
+ workspaceCreditsTotalGranted: number;
@Field(() => Float)
unitPriceCents: number;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/dtos/inputs/billing-update-user-credits-fallback.input.ts b/packages/twenty-server/src/engine/core-modules/billing/dtos/inputs/billing-update-user-credits-fallback.input.ts
new file mode 100644
index 00000000000..cc2b7457a41
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/dtos/inputs/billing-update-user-credits-fallback.input.ts
@@ -0,0 +1,14 @@
+/* @license Enterprise */
+
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { IsEnum } from 'class-validator';
+
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
+
+@ArgsType()
+export class BillingUpdateUserCreditsFallbackInput {
+ @Field(() => UserCreditsFallback)
+ @IsEnum(UserCreditsFallback)
+ userCreditsFallback: UserCreditsFallback;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-customer.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-customer.entity.ts
index cad6e6a7370..ece66c430cf 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-customer.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-customer.entity.ts
@@ -15,6 +15,8 @@ import {
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { BillingEntitlementEntity } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';
import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
+import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity.type';
@Entity({ name: 'billingCustomer', schema: 'core' })
@@ -44,6 +46,18 @@ export class BillingCustomerEntity extends WorkspaceRelatedEntity {
@Column({ nullable: true, type: 'boolean' })
hasPaymentMethod: boolean | null;
+ @Field(() => UserCreditsFallback)
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.49.0_AddUserCreditsFallbackToBillingCustomerFastInstanceCommand_1792154197828',
+ })
+ @Column({
+ type: 'varchar',
+ nullable: false,
+ default: UserCreditsFallback.WORKSPACE_CREDITS,
+ })
+ userCreditsFallback: UserCreditsFallback;
+
@OneToMany(
() => BillingSubscriptionEntity,
(billingSubscription) => billingSubscription.billingCustomer,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum.ts b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum.ts
new file mode 100644
index 00000000000..51cf7b6e4c9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum.ts
@@ -0,0 +1,12 @@
+/* @license Enterprise */
+
+import { registerEnumType } from '@nestjs/graphql';
+
+export enum UserCreditsFallback {
+ WORKSPACE_CREDITS = 'WORKSPACE_CREDITS',
+ STOP = 'STOP',
+}
+
+registerEnumType(UserCreditsFallback, {
+ name: 'UserCreditsFallback',
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance.service.ts
index cb01645aae1..e5419ea083a 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance.service.ts
@@ -5,6 +5,7 @@ import { Injectable } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
import { type FlatBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { type CreditAllowance } from 'src/engine/core-modules/usage-limit/types/credit-allowance.type';
@@ -63,6 +64,16 @@ export class BillingCreditAllowanceService {
return subscription?.planKey ?? null;
}
+ async getUserCreditsFallback(
+ workspaceId: string,
+ ): Promise<UserCreditsFallback> {
+ const subscription = await this.findCurrentBillingSubscription(workspaceId);
+
+ return (
+ subscription?.userCreditsFallback ?? UserCreditsFallback.WORKSPACE_CREDITS
+ );
+ }
+
private async findCurrentBillingSubscription(
workspaceId: string,
): Promise<FlatBillingSubscription | null> {
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.ts
index a8520355334..e331c799c49 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
@@ -51,7 +51,7 @@ export class BillingCreditRolloverService {
// Outside the lock: no credit write changes ClickHouse usage, and its latency would stall grants
const usageMicro =
- await this.billingUsageService.getCreditsUsedBetweenOrNull({
+ await this.billingUsageService.getWorkspaceCreditsUsedMicroBetweenOrNull({
workspaceId,
from: closingPeriodStart,
to: closingPeriodEnd,
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.ts
index 6e2f36349d9..ea38206e493 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
@@ -122,7 +122,7 @@ export class BillingUsageService {
periodStart: Date,
periodEnd: Date,
): Promise<BillingResourceCreditUsageDTO> {
- const [usedCredits, rolloverCredits] = await Promise.all([
+ const [creditsUsed, workspaceCreditsExtraGranted] = await Promise.all([
// Fails open: an unreadable usage total must never block a paying workspace
this.usageAnalyticsService
.getCreditsUsedMicroForBillingPeriod({ workspaceId, periodStart })
@@ -132,12 +132,12 @@ export class BillingUsageService {
error,
);
- return 0;
+ return { workspaceCreditsUsedMicro: 0, userCreditsUsedMicro: 0 };
}),
this.billingCreditGrantService.getActiveCreditsMicro(workspaceId),
]);
- const grantedCredits =
+ const workspaceCreditsGranted =
subscription.status === SubscriptionStatus.Trialing
? item.freeTrialQuantity
: item.creditAmount;
@@ -146,10 +146,12 @@ export class BillingUsageService {
productKey: item.productKey,
periodStart,
periodEnd,
- usedCredits,
- grantedCredits,
- rolloverCredits,
- totalGrantedCredits: grantedCredits + rolloverCredits,
+ workspaceCreditsUsed: creditsUsed.workspaceCreditsUsedMicro,
+ userCreditsUsed: creditsUsed.userCreditsUsedMicro,
+ workspaceCreditsGranted,
+ workspaceCreditsExtraGranted,
+ workspaceCreditsTotalGranted:
+ workspaceCreditsGranted + workspaceCreditsExtraGranted,
unitPriceCents: item.unitPriceCents,
};
}
@@ -187,7 +189,7 @@ export class BillingUsageService {
// By event timestamp: at a transition currentPeriodStart has moved on, so periodStart would read the new period
// Null on a failed read: select swallows errors into [], while sum() always yields one row
- async getCreditsUsedBetweenOrNull({
+ async getWorkspaceCreditsUsedMicroBetweenOrNull({
workspaceId,
from,
to,
@@ -197,7 +199,7 @@ export class BillingUsageService {
to: Date;
}): Promise<number | null> {
const rows = await this.clickHouseService.select<UsageSumRow>(
- `SELECT sum(creditsUsedMicro) AS total
+ `SELECT sum(creditsUsedMicro) - sum(userCreditsUsedMicro) AS total
FROM usageEvent
WHERE workspaceId = {workspaceId:String}
AND timestamp >= {from:DateTime64(3)} AND timestamp < {to:DateTime64(3)}`,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts
index 609ed686281..045a32a51de 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts
@@ -4,10 +4,15 @@ import { Injectable, Logger } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
+import {
+ BillingException,
+ BillingExceptionCode,
+} from 'src/engine/core-modules/billing/billing.exception';
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
import { type BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';
+import { type UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
import { BillingProductService } from 'src/engine/core-modules/billing/services/billing-product.service';
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
@@ -61,6 +66,35 @@ export class BillingService {
});
}
+ async updateUserCreditsFallbackOrThrow({
+ workspaceId,
+ userCreditsFallback,
+ }: {
+ workspaceId: string;
+ userCreditsFallback: UserCreditsFallback;
+ }): Promise<BillingCustomerEntity> {
+ const { affected } = await this.billingCustomerRepository.update(
+ workspaceId,
+ {},
+ { userCreditsFallback },
+ );
+
+ if (affected === 0) {
+ throw new BillingException(
+ `No billing customer found for workspace ${workspaceId}`,
+ BillingExceptionCode.BILLING_CUSTOMER_NOT_FOUND,
+ );
+ }
+
+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
+ 'currentBillingSubscription',
+ ]);
+
+ return this.billingCustomerRepository.findOneOrFail(workspaceId, {
+ where: {},
+ });
+ }
+
async hasWorkspaceAnySubscription(workspaceId: string) {
const isBillingEnabled = this.isBillingEnabled();
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service.ts
index f721dcd1bd2..4dba6c3c67f 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service.ts
@@ -9,6 +9,7 @@ import { BillingSubscriptionService } from 'src/engine/core-modules/billing/serv
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';
import { isBaseProductSubscriptionItem } from 'src/engine/core-modules/billing/utils/is-base-product-subscription-item.util';
import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
@@ -38,8 +39,10 @@ export class WorkspaceCurrentBillingSubscriptionCacheService extends WorkspaceCa
return NO_BILLING_SUBSCRIPTION;
}
- const unexpiredGrants =
- await this.billingCreditGrantService.findUnexpiredGrants(workspaceId);
+ const [unexpiredGrants, billingCustomer] = await Promise.all([
+ this.billingCreditGrantService.findUnexpiredGrants(workspaceId),
+ this.billingSubscriptionService.getBillingCustomer(workspaceId),
+ ]);
return {
id: subscription.id,
@@ -64,6 +67,9 @@ export class WorkspaceCurrentBillingSubscriptionCacheService extends WorkspaceCa
subscription.billingSubscriptionItems.find(
isBaseProductSubscriptionItem,
)?.billingProduct?.metadata.planKey ?? null,
+ userCreditsFallback:
+ billingCustomer?.userCreditsFallback ??
+ UserCreditsFallback.WORKSPACE_CREDITS,
creditGrants: unexpiredGrants.map(
({ amountMicro, effectiveAt, expiresAt }) => ({
amountMicro,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/flat-billing-subscription.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/flat-billing-subscription.type.ts
index 3389479512b..9e0679badd2 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/types/flat-billing-subscription.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/types/flat-billing-subscription.type.ts
@@ -1,6 +1,7 @@
/* @license Enterprise */
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
+import { type UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
import { type BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';
import { type BillingSubscriptionCollectionMethod } from 'src/engine/core-modules/billing/enums/billing-subscription-collection-method.enum';
import { type SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
@@ -26,6 +27,7 @@ export type FlatBillingSubscription = {
collectionMethod: BillingSubscriptionCollectionMethod;
planAllowanceMicro: number | null;
planKey: BillingPlanKey | null;
+ userCreditsFallback: UserCreditsFallback;
creditGrants: CreditAllowanceGrant[];
};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-usage-refusal-exception.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-usage-refusal-exception.util.spec.ts
index 04bbd3e94fe..1169942602c 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-usage-refusal-exception.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-usage-refusal-exception.util.spec.ts
@@ -35,7 +35,10 @@ const buildExhaustedScope = (
const EXHAUSTED_SCOPE_BY_EXHAUSTED_KIND: Record<ExhaustedKind, ExhaustedScope> =
{
limit: buildExhaustedScope({ exhaustedKind: 'limit' }),
- allowance: buildExhaustedScope({ exhaustedKind: 'allowance' }),
+ workspaceAllowance: buildExhaustedScope({
+ exhaustedKind: 'workspaceAllowance',
+ }),
+ userAllowance: buildExhaustedScope({ exhaustedKind: 'userAllowance' }),
};
const USAGE_REFUSALS_BY_KIND: Record<UsageRefusal['kind'], UsageRefusal[]> = {
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index 286e5f60f93..60ed0502b54 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -1009,6 +1009,16 @@ export class ConfigVariables {
@ValidateIf((env) => env.IS_BILLING_ENABLED === true)
BILLING_FREE_WORKFLOW_CREDITS_FOR_TRIAL_PERIOD_WITH_CREDIT_CARD = 2_500_000;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.BILLING_CONFIG,
+ description:
+ 'User credits each user can spend on AI chat and web search per period of the AI user credit limit default, before workspace credits (in microCredits). No user credits when unset. USAGE_LIMIT_DEFAULTS_BY_PLAN can set it per billing plan',
+ type: ConfigVariableType.NUMBER,
+ })
+ @CastToPositiveNumber()
+ @IsOptional()
+ AI_USER_CREDITS_LIMIT?: number;
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.BILLING_CONFIG,
description:
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
index 2f02a350ec2..72541cf6546 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
@@ -83,6 +83,10 @@ export const USAGE_LIMIT_DEFINITIONS = {
operationType: UsageOperationType.WEB_SEARCH,
allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
},
+ {
+ operationType: UsageOperationType.AI_WORKFLOW_WEB_SEARCH,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
],
allowedSpenderTypes: [
'workspace',
@@ -90,7 +94,24 @@ export const USAGE_LIMIT_DEFINITIONS = {
'apiKey',
'application',
],
- defaults: [],
+ defaults: [
+ {
+ resourceType: UsageResourceType.AI,
+ operationTypes: [
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ],
+ limitKind: 'quota',
+ spenderType: 'userWorkspace',
+ spenderId: '',
+ isPerSpender: true,
+ unit: UsageUnit.USER_CREDIT,
+ periodUnit: 'week',
+ periodCount: 1,
+ limitValueConfigVariable: 'AI_USER_CREDITS_LIMIT',
+ isOverridable: false,
+ },
+ ],
},
},
[UsageResourceType.WORKFLOW]: {
@@ -229,10 +250,11 @@ export const USAGE_LIMIT_DEFINITIONS = {
defaults: [
{
resourceType: UsageResourceType.EMAIL,
- operationType: UsageOperationType.EMAIL_SEND,
+ operationTypes: [UsageOperationType.EMAIL_SEND],
limitKind: 'quota',
spenderType: 'workspace',
spenderId: '',
+ isPerSpender: false,
unit: UsageUnit.INVOCATION,
periodUnit: 'day',
periodCount: 1,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/warm-and-consume-counters-script.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/warm-and-consume-counters-script.constant.ts
index 83abaf9d8d6..5a6cda08df0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/warm-and-consume-counters-script.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/warm-and-consume-counters-script.constant.ts
@@ -6,15 +6,50 @@ export const WARM_AND_CONSUME_COUNTERS_SCRIPT: CacheScript = {
local amounts = cjson.decode(ARGV[1])
local warmValues = cjson.decode(ARGV[2])
local warmTtls = cjson.decode(ARGV[3])
+local splits = cjson.decode(ARGV[4] or '[]')
+local userLimits = cjson.decode(ARGV[5] or '[]')
+local isUserCreditsFallbackEnabled = ARGV[6] == 'true'
local result = {}
+local isSplitCold = false
+local userShare = false
for i = 1, #KEYS do
if warmValues[i] then
redis.call('SET', KEYS[i], warmValues[i], 'NX', 'PX', warmTtls[i])
end
- if redis.call('EXISTS', KEYS[i]) == 1 then
- result[i] = redis.call('INCRBY', KEYS[i], amounts[i])
+ if splits[i] then
+ local consumed = redis.call('GET', KEYS[i])
+
+ if not consumed then
+ isSplitCold = true
+ elseif splits[i] == 'userCredits' then
+ local share = amounts[i]
+
+ if isUserCreditsFallbackEnabled then
+ share = math.max(0, math.min(share, userLimits[i] - tonumber(consumed)))
+ end
+
+ userShare = math.min(userShare or share, share)
+ end
+ end
+end
+
+if isSplitCold then
+ userShare = false
+end
+
+for i = 1, #KEYS do
+ local amount = amounts[i]
+
+ if splits[i] == 'userCredits' then
+ amount = userShare
+ elseif splits[i] == 'workspaceCredits' then
+ amount = math.max(0, amounts[i] - (userShare or 0))
+ end
+
+ if not (splits[i] and isSplitCold) and redis.call('EXISTS', KEYS[i]) == 1 then
+ result[i] = redis.call('INCRBY', KEYS[i], amount)
if result[i] < 0 then
redis.call('SET', KEYS[i], 0, 'KEEPTTL')
@@ -25,6 +60,10 @@ for i = 1, #KEYS do
end
end
+if userShare then
+ result[#KEYS + 1] = userShare
+end
+
return result
`,
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
index 6bceffccef8..b63308dc38f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
@@ -3,6 +3,7 @@ import { Injectable, Logger } from '@nestjs/common';
import uniqBy from 'lodash.uniqby';
import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
import { BillingCreditAllowanceService } from 'src/engine/core-modules/billing/services/billing-credit-allowance.service';
import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
@@ -15,7 +16,7 @@ import { UsageLimitException } from 'src/engine/core-modules/usage-limit/excepti
import { UsageLimitDefaultValueService } from 'src/engine/core-modules/usage-limit/services/usage-limit-default-value.service';
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
-import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type WorkspaceAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/workspace-allowance-quota-counter.type';
import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';
import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/flat-quota-limit.type';
@@ -24,8 +25,11 @@ import { type LimitConsumption } from 'src/engine/core-modules/usage-limit/types
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';
import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
+import { type QuotaDebit } from 'src/engine/core-modules/usage-limit/types/quota-debit.type';
+import { type QuotaDebitResult } from 'src/engine/core-modules/usage-limit/types/quota-debit-result.type';
import { type QuotaLimitDefault } from 'src/engine/core-modules/usage-limit/types/quota-limit-default.type';
-import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
+import { type UserAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type';
+import { buildWorkspaceAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-workspace-allowance-counter-key.util';
import { buildConsumeScriptArguments } from 'src/engine/core-modules/usage-limit/utils/build-consume-script-arguments.util';
import { buildIntraWorkspaceLimitCounterKeys } from 'src/engine/core-modules/usage-limit/utils/build-intra-workspace-limit-counter-keys.util';
import { buildLimitQuotaCounter } from 'src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util';
@@ -36,11 +40,14 @@ import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/ut
import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';
import { computeCreditAllowanceMicro } from 'src/engine/core-modules/usage-limit/utils/compute-credit-allowance-micro.util';
import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
+import { findBlockingCounters } from 'src/engine/core-modules/usage-limit/utils/find-blocking-counters.util';
import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';
import { findLimitsForResource } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-resource.util';
import { findSuppressedUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util';
+import { findUnmeteredUserCreditsShare } from 'src/engine/core-modules/usage-limit/utils/find-unmetered-user-credits-share.util';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
import { isQuotaLimit } from 'src/engine/core-modules/usage-limit/utils/is-quota-limit.util';
+import { splitUserCreditsAcrossEvents } from 'src/engine/core-modules/usage-limit/utils/split-user-credits-across-events.util';
import { getPeriodAnchor } from 'src/engine/core-modules/usage-limit/utils/get-period-anchor.util';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
@@ -93,14 +100,10 @@ export class UsageLimitQuotaService {
async findExhaustedScope(
args: QuotaConsumeArgs & { cost?: QuotaCost },
): Promise<ExhaustedScope | null> {
- const exhaustedScopes =
+ const [exhaustedScope] =
await this.findExhaustedScopesAdmittingOnFailure(args);
- return (
- exhaustedScopes.find((scope) => scope.exhaustedKind === 'allowance') ??
- exhaustedScopes[0] ??
- null
- );
+ return exhaustedScope ?? null;
}
async charge({
@@ -114,12 +117,16 @@ export class UsageLimitQuotaService {
return { exhaustedKind: null };
}
- const exhaustedKind = await this.debitCountersAdmittingOnFailure({
- workspaceId,
- events,
- });
+ const { exhaustedKind, userCreditsUsedMicro } =
+ await this.debitCountersAdmittingOnFailure({
+ workspaceId,
+ events,
+ });
- await this.usageRecorderService.record(workspaceId, events);
+ await this.usageRecorderService.record(
+ workspaceId,
+ splitUserCreditsAcrossEvents({ events, userCreditsUsedMicro }),
+ );
return { exhaustedKind };
}
@@ -130,13 +137,11 @@ export class UsageLimitQuotaService {
}: {
workspaceId: string;
event: RecordUsageInput;
- }): Promise<{ exhaustedKind: ExhaustedKind | null }> {
- return {
- exhaustedKind: await this.debitCountersAdmittingOnFailure({
- workspaceId,
- events: [event],
- }),
- };
+ }): Promise<QuotaDebitResult> {
+ return this.debitCountersAdmittingOnFailure({
+ workspaceId,
+ events: [event],
+ });
}
async dropIntraWorkspaceLimitCounters(workspaceId: string): Promise<void> {
@@ -190,44 +195,36 @@ export class UsageLimitQuotaService {
);
}
- async getAllowanceUsage(workspaceId: string): Promise<{
+ async getWorkspaceAllowanceUsage(workspaceId: string): Promise<{
limitValue: number;
consumedValue: number | null;
periodEnd: Date;
} | null> {
- const counter = await this.buildAllowanceCounter(workspaceId);
+ const counter = await this.buildWorkspaceAllowanceCounter(workspaceId);
if (!isDefined(counter)) {
return null;
}
- let consumedValue: number | null = null;
-
- try {
- const [storedValue] = await this.cacheStorage.mget<number>([counter.key]);
-
- consumedValue =
- storedValue ??
- (await this.usageAnalyticsService.getCreditsUsedMicroForBillingPeriod({
- workspaceId,
- periodStart: counter.periodStart,
- }));
- } catch (error) {
- this.admitOnFailure({ error, workspaceId, admitted: null });
- }
+ const {
+ consumedValues: [consumedValue],
+ } = await this.readCountersAdmittingOnFailure({
+ workspaceId,
+ counters: [counter],
+ });
return {
limitValue: counter.limitValue,
- consumedValue,
+ consumedValue: consumedValue ?? null,
periodEnd: counter.periodEnd,
};
}
- async getAllowanceRemainingMicro(
+ async getWorkspaceAllowanceRemainingMicro(
workspaceId: string,
): Promise<number | null> {
try {
- const counter = await this.buildAllowanceCounter(workspaceId);
+ const counter = await this.buildWorkspaceAllowanceCounter(workspaceId);
if (!isDefined(counter)) {
return null;
@@ -281,7 +278,7 @@ export class UsageLimitQuotaService {
return new Map();
}
- const consumedValues = await this.readConsumedValuesAdmittingOnFailure({
+ const { consumedValues } = await this.readCountersAdmittingOnFailure({
workspaceId,
counters: entries.map(({ counter }) => counter),
});
@@ -326,15 +323,23 @@ export class UsageLimitQuotaService {
};
try {
- const [limitCounters, { allowanceCounter, isAllowanceSkipped }] =
- await Promise.all([
- this.buildLimitCounters(args),
- this.buildAllowanceCounterAdmittingOnFailure(args.workspaceId),
- ]);
+ const [
+ quotaCounters,
+ {
+ workspaceAllowanceCounter,
+ userCreditsFallback,
+ isWorkspaceAllowanceSkipped,
+ },
+ ] = await Promise.all([
+ this.buildQuotaCountersForScope(args),
+ this.buildWorkspaceAllowanceCounterAdmittingOnFailure(args.workspaceId),
+ ]);
const counters: QuotaCounter[] = [
- ...limitCounters,
- ...(isDefined(allowanceCounter) ? [allowanceCounter] : []),
+ ...quotaCounters,
+ ...(isDefined(workspaceAllowanceCounter)
+ ? [workspaceAllowanceCounter]
+ : []),
];
const { consumedValues, isDegraded } = await this.consumeCounters({
@@ -343,16 +348,25 @@ export class UsageLimitQuotaService {
amounts: counters.map(() => 0),
});
- if (isDegraded || isAllowanceSkipped) {
+ if (isDegraded || isWorkspaceAllowanceSkipped) {
this.countAdmitOnFailure(enforcement);
}
- return findExhaustedCounters({ counters, consumedValues, cost }).map(
- (counter) =>
- buildQuotaExhaustedScope({
- resourceType: args.resourceType,
- counter,
- }),
+ return findBlockingCounters({
+ counters,
+ consumedValues,
+ exhaustedCounters: findExhaustedCounters({
+ counters,
+ consumedValues,
+ cost,
+ }),
+ userCreditsFallback,
+ }).map((counter) =>
+ buildQuotaExhaustedScope({
+ resourceType: args.resourceType,
+ operationType: args.operationType,
+ counter,
+ }),
);
} catch (error) {
return this.admitOnFailure({
@@ -370,38 +384,99 @@ export class UsageLimitQuotaService {
}: {
workspaceId: string;
events: RecordUsageInput[];
- }): Promise<ExhaustedKind | null> {
+ }): Promise<QuotaDebitResult> {
try {
- const [limitCounters, { allowanceCounter, isAllowanceSkipped }] =
- await Promise.all([
- this.buildLimitCountersForEvents({ workspaceId, events }),
- this.buildAllowanceCounterAdmittingOnFailure(workspaceId),
- ]);
+ const { debits, userCreditsFallback, isWorkspaceAllowanceSkipped } =
+ await this.buildQuotaDebitsForEvents({ workspaceId, events });
- const debits = buildQuotaDebits({
- counters: [
- ...limitCounters,
- ...(isDefined(allowanceCounter) ? [allowanceCounter] : []),
- ],
+ return await this.consumeQuotaDebitsAdmittingOnFailure({
+ workspaceId,
+ events,
+ debits,
+ userCreditsFallback,
+ isWorkspaceAllowanceSkipped,
+ });
+ } catch (error) {
+ return this.admitDebitOnFailure({
+ error,
+ workspaceId,
events,
+ userCreditsUsedMicro: 0,
});
+ }
+ }
+
+ private async buildQuotaDebitsForEvents({
+ workspaceId,
+ events,
+ }: {
+ workspaceId: string;
+ events: RecordUsageInput[];
+ }): Promise<{
+ debits: QuotaDebit[];
+ userCreditsFallback: UserCreditsFallback;
+ isWorkspaceAllowanceSkipped: boolean;
+ }> {
+ const [
+ quotaCounters,
+ {
+ workspaceAllowanceCounter,
+ userCreditsFallback,
+ isWorkspaceAllowanceSkipped,
+ },
+ ] = await Promise.all([
+ this.buildQuotaCountersForEvents({ workspaceId, events }),
+ this.buildWorkspaceAllowanceCounterAdmittingOnFailure(workspaceId),
+ ]);
+ return {
+ debits: buildQuotaDebits({
+ counters: [
+ ...quotaCounters,
+ ...(isDefined(workspaceAllowanceCounter)
+ ? [workspaceAllowanceCounter]
+ : []),
+ ].filter((counter) => counter.periodEnd.getTime() > Date.now()),
+ events,
+ }),
+ userCreditsFallback,
+ isWorkspaceAllowanceSkipped,
+ };
+ }
+
+ private async consumeQuotaDebitsAdmittingOnFailure({
+ workspaceId,
+ events,
+ debits,
+ userCreditsFallback,
+ isWorkspaceAllowanceSkipped,
+ }: {
+ workspaceId: string;
+ events: RecordUsageInput[];
+ debits: QuotaDebit[];
+ userCreditsFallback: UserCreditsFallback;
+ isWorkspaceAllowanceSkipped: boolean;
+ }): Promise<QuotaDebitResult> {
+ try {
const counters = debits.map((debit) => debit.counter);
- const { consumedValues, isDegraded } = await this.consumeCounters({
- workspaceId,
- counters,
- amounts: debits.map((debit) => debit.amount),
- });
+ const { consumedValues, userCreditsUsedMicro, isDegraded } =
+ await this.consumeCounters({
+ workspaceId,
+ counters,
+ amounts: debits.map((debit) => debit.amount),
+ splits: debits.map((debit) => debit.split),
+ userCreditsFallback,
+ });
- if (isDegraded || isAllowanceSkipped) {
+ if (isDegraded || isWorkspaceAllowanceSkipped) {
this.countConsumeAdmittedOnFailure({
events,
- isAllowanceUnmetered:
- isAllowanceSkipped ||
+ isWorkspaceAllowanceUnmetered:
+ isWorkspaceAllowanceSkipped ||
counters.some(
(counter, index) =>
- counter.kind === 'allowance' &&
+ counter.kind === 'workspaceAllowance' &&
!isDefined(consumedValues[index]) &&
counter.periodEnd.getTime() > Date.now(),
),
@@ -413,31 +488,68 @@ export class UsageLimitQuotaService {
consumedValues,
});
- if (exhaustedCounters.some((counter) => counter.kind === 'allowance')) {
- return 'allowance';
- }
+ const [blockingCounter] = findBlockingCounters({
+ counters,
+ consumedValues,
+ exhaustedCounters,
+ userCreditsFallback,
+ });
- return exhaustedCounters.length > 0 ? 'limit' : null;
+ return {
+ exhaustedKind: blockingCounter?.kind ?? null,
+ userCreditsUsedMicro,
+ userAllowanceExhaustedUntil: exhaustedCounters.reduce<Date | null>(
+ (latestPeriodEnd, counter) =>
+ counter.kind === 'userAllowance' &&
+ (!isDefined(latestPeriodEnd) || counter.periodEnd > latestPeriodEnd)
+ ? counter.periodEnd
+ : latestPeriodEnd,
+ null,
+ ),
+ };
} catch (error) {
- this.logger.error(
- `Usage quota debit degraded for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,
- );
- this.countConsumeAdmittedOnFailure({
+ return this.admitDebitOnFailure({
+ error,
+ workspaceId,
events,
- isAllowanceUnmetered: true,
+ userCreditsUsedMicro: findUnmeteredUserCreditsShare(debits),
});
-
- return null;
}
}
- private async buildLimitCountersForEvents({
+ private admitDebitOnFailure({
+ error,
workspaceId,
events,
+ userCreditsUsedMicro,
}: {
+ error: unknown;
workspaceId: string;
events: RecordUsageInput[];
- }): Promise<LimitQuotaCounter[]> {
+ userCreditsUsedMicro: number;
+ }): QuotaDebitResult {
+ this.logger.error(
+ `Usage quota debit degraded for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,
+ );
+ this.countConsumeAdmittedOnFailure({
+ events,
+ isWorkspaceAllowanceUnmetered: true,
+ });
+
+ return {
+ exhaustedKind: null,
+ userCreditsUsedMicro,
+ userAllowanceExhaustedUntil: null,
+ };
+ }
+
+ private async buildQuotaCountersForEvents({
+ workspaceId,
+ events,
+ }: {
+ workspaceId: string;
+ events: RecordUsageInput[];
+ }): Promise<(LimitQuotaCounter | UserAllowanceQuotaCounter)[]> {
const scopeEvents = uniqBy(events, (event) =>
JSON.stringify([
event.resourceType,
@@ -448,7 +560,7 @@ export class UsageLimitQuotaService {
const counters = await Promise.all(
scopeEvents.map(({ resourceType, operationType, spenders }) =>
- this.buildLimitCounters({
+ this.buildQuotaCountersForScope({
workspaceId,
resourceType,
operationType,
@@ -462,10 +574,10 @@ export class UsageLimitQuotaService {
private countConsumeAdmittedOnFailure({
events,
- isAllowanceUnmetered,
+ isWorkspaceAllowanceUnmetered,
}: {
events: RecordUsageInput[];
- isAllowanceUnmetered: boolean;
+ isWorkspaceAllowanceUnmetered: boolean;
}): void {
for (const resourceType of new Set(
events.map((event) => event.resourceType),
@@ -473,7 +585,7 @@ export class UsageLimitQuotaService {
this.countAdmitOnFailure({
operation: 'consume',
resourceType,
- creditsUsedMicro: isAllowanceUnmetered
+ creditsUsedMicro: isWorkspaceAllowanceUnmetered
? events
.filter((event) => event.resourceType === resourceType)
.reduce(
@@ -541,12 +653,14 @@ export class UsageLimitQuotaService {
}
}
- private async buildLimitCounters({
+ private async buildQuotaCountersForScope({
workspaceId,
resourceType,
operationType,
spenders,
- }: QuotaConsumeArgs): Promise<LimitQuotaCounter[]> {
+ }: QuotaConsumeArgs): Promise<
+ (LimitQuotaCounter | UserAllowanceQuotaCounter)[]
+ > {
const quotaLimitDefaults = await this.buildQuotaLimitDefaults({
workspaceId,
resourceType,
@@ -617,16 +731,26 @@ export class UsageLimitQuotaService {
return quotaLimitDefaults.flat();
}
- private async buildAllowanceCounterAdmittingOnFailure(
+ private async buildWorkspaceAllowanceCounterAdmittingOnFailure(
workspaceId: string,
): Promise<{
- allowanceCounter: AllowanceQuotaCounter | null;
- isAllowanceSkipped: boolean;
+ workspaceAllowanceCounter: WorkspaceAllowanceQuotaCounter | null;
+ userCreditsFallback: UserCreditsFallback;
+ isWorkspaceAllowanceSkipped: boolean;
}> {
try {
+ const [workspaceAllowanceCounter, userCreditsFallback] =
+ await Promise.all([
+ this.buildWorkspaceAllowanceCounter(workspaceId),
+ this.billingCreditAllowanceService.getUserCreditsFallback(
+ workspaceId,
+ ),
+ ]);
+
return {
- allowanceCounter: await this.buildAllowanceCounter(workspaceId),
- isAllowanceSkipped: false,
+ workspaceAllowanceCounter,
+ userCreditsFallback,
+ isWorkspaceAllowanceSkipped: false,
};
} catch (error) {
if (error instanceof WorkspaceCacheException) {
@@ -637,13 +761,17 @@ export class UsageLimitQuotaService {
`Usage quota allowance skipped for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,
);
- return { allowanceCounter: null, isAllowanceSkipped: true };
+ return {
+ workspaceAllowanceCounter: null,
+ userCreditsFallback: UserCreditsFallback.WORKSPACE_CREDITS,
+ isWorkspaceAllowanceSkipped: true,
+ };
}
}
- private async buildAllowanceCounter(
+ private async buildWorkspaceAllowanceCounter(
workspaceId: string,
- ): Promise<AllowanceQuotaCounter | null> {
+ ): Promise<WorkspaceAllowanceQuotaCounter | null> {
if (
!(await this.billingCreditAllowanceService.isCreditAllowanceEnabled())
) {
@@ -658,8 +786,8 @@ export class UsageLimitQuotaService {
}
return {
- kind: 'allowance',
- key: buildAllowanceCounterKey({
+ kind: 'workspaceAllowance',
+ key: buildWorkspaceAllowanceCounterKey({
workspaceId,
periodStart: allowance.periodStart,
}),
@@ -697,66 +825,52 @@ export class UsageLimitQuotaService {
});
}
- private async readConsumedValuesAdmittingOnFailure({
+ private async readCountersAdmittingOnFailure({
workspaceId,
counters,
}: {
workspaceId: string;
- counters: LimitQuotaCounter[];
- }): Promise<(number | null)[]> {
+ counters: QuotaCounter[];
+ }): Promise<QuotaConsumeResult> {
try {
- return await this.readConsumedValues({ workspaceId, counters });
+ return await this.consumeCounters({
+ workspaceId,
+ counters,
+ amounts: counters.map(() => 0),
+ });
} catch (error) {
- return this.admitOnFailure<(number | null)[]>({
+ return this.admitOnFailure({
error,
workspaceId,
- admitted: [],
+ admitted: {
+ consumedValues: counters.map(() => null),
+ isDegraded: true,
+ },
});
}
}
- private async readConsumedValues({
- workspaceId,
- counters,
- }: {
- workspaceId: string;
- counters: LimitQuotaCounter[];
- }): Promise<(number | null)[]> {
- const storedValues = await this.cacheStorage.mget<number>(
- counters.map((counter) => counter.key),
- );
-
- const coldCounters = counters.filter(
- (_, index) => !isDefined(storedValues[index]),
- );
-
- const warmValues = await this.fetchWarmValues({
- workspaceId,
- counters: coldCounters,
- });
-
- const warmedValueByKey = new Map(
- coldCounters.map((counter, index) => [counter.key, warmValues[index]]),
- );
-
- return counters.map(
- (counter, index) =>
- storedValues[index] ?? warmedValueByKey.get(counter.key) ?? null,
- );
- }
-
private async consumeCounters({
workspaceId,
counters,
amounts,
+ splits = counters.map(() => null),
+ userCreditsFallback = UserCreditsFallback.WORKSPACE_CREDITS,
}: {
workspaceId: string;
counters: QuotaCounter[];
amounts: number[];
- }): Promise<QuotaConsumeResult> {
- const consumedValues = await this.runWarmAndConsumeScript({
+ splits?: QuotaDebit['split'][];
+ userCreditsFallback?: UserCreditsFallback;
+ }): Promise<QuotaConsumeResult & { userCreditsUsedMicro: number }> {
+ const { consumedValues, userShare } = await this.runWarmAndConsumeScript({
counters,
- entries: amounts.map((amount) => ({ amount, warm: null })),
+ entries: amounts.map((amount, index) => ({
+ amount,
+ warm: null,
+ split: splits[index],
+ })),
+ userCreditsFallback,
});
const now = Date.now();
@@ -768,7 +882,11 @@ export class UsageLimitQuotaService {
);
if (coldIndexes.length === 0) {
- return { consumedValues, isDegraded: false };
+ return {
+ consumedValues,
+ userCreditsUsedMicro: userShare ?? 0,
+ isDegraded: false,
+ };
}
try {
@@ -785,51 +903,109 @@ export class UsageLimitQuotaService {
: [],
);
- const warmedValues = await this.runWarmAndConsumeScript({
- counters: warmedEntries.map(({ index }) => counters[index]),
- entries: warmedEntries.map(({ index, warmValue }) => ({
- amount: amounts[index],
- warm: {
- value: warmValue,
- ttl: counters[index].periodEnd.getTime() - warmedAt,
- },
- })),
- });
+ const { consumedValues: warmedValues, userShare: warmedUserShare } =
+ await this.runWarmAndConsumeScript({
+ counters: warmedEntries.map(({ index }) => counters[index]),
+ entries: warmedEntries.map(({ index, warmValue }) => ({
+ amount: amounts[index],
+ warm: {
+ value: warmValue,
+ ttl: counters[index].periodEnd.getTime() - warmedAt,
+ },
+ split: splits[index],
+ })),
+ userCreditsFallback,
+ });
warmedEntries.forEach(({ index }, position) => {
consumedValues[index] = warmedValues[position];
});
- return { consumedValues, isDegraded: false };
+ return {
+ consumedValues,
+ userCreditsUsedMicro: userShare ?? warmedUserShare ?? 0,
+ isDegraded: false,
+ };
} catch (error) {
this.logger.error(
`Usage quota warm degraded for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,
);
- return { consumedValues, isDegraded: true };
+ const heldBackIndexes = consumedValues.flatMap((consumedValue, index) =>
+ !isDefined(consumedValue) && isDefined(splits[index]) ? [index] : [],
+ );
+
+ if (!isNonEmptyArray(heldBackIndexes)) {
+ return {
+ consumedValues,
+ userCreditsUsedMicro: userShare ?? 0,
+ isDegraded: true,
+ };
+ }
+
+ const unmeteredUserCreditsShare = findUnmeteredUserCreditsShare(
+ heldBackIndexes.map((index) => ({
+ amount: amounts[index],
+ split: splits[index],
+ })),
+ );
+
+ const { consumedValues: heldBackValues } =
+ await this.runWarmAndConsumeScript({
+ counters: heldBackIndexes.map((index) => counters[index]),
+ entries: heldBackIndexes.map((index) => ({
+ amount:
+ splits[index]?.kind === 'userCredits'
+ ? unmeteredUserCreditsShare
+ : Math.max(0, amounts[index] - unmeteredUserCreditsShare),
+ warm: null,
+ })),
+ userCreditsFallback,
+ });
+
+ heldBackIndexes.forEach((index, position) => {
+ consumedValues[index] = heldBackValues[position];
+ });
+
+ return {
+ consumedValues,
+ userCreditsUsedMicro: unmeteredUserCreditsShare,
+ isDegraded: true,
+ };
}
}
private async runWarmAndConsumeScript({
counters,
entries,
+ userCreditsFallback,
}: {
counters: QuotaCounter[];
- entries: Parameters<typeof buildConsumeScriptArguments>[0];
- }): Promise<(number | null)[]> {
+ entries: Parameters<typeof buildConsumeScriptArguments>[0]['entries'];
+ userCreditsFallback: UserCreditsFallback;
+ }): Promise<{ consumedValues: (number | null)[]; userShare: number | null }> {
if (counters.length === 0) {
- return [];
+ return { consumedValues: [], userShare: null };
}
const results = await this.cacheStorage.runScript<unknown[]>({
script: WARM_AND_CONSUME_COUNTERS_SCRIPT,
keys: counters.map((counter) => counter.key),
- args: buildConsumeScriptArguments(entries),
+ args: buildConsumeScriptArguments({
+ entries,
+ isUserCreditsFallbackEnabled:
+ userCreditsFallback === UserCreditsFallback.WORKSPACE_CREDITS,
+ }),
});
- return results.map((result) =>
+ const values = results.map((result) =>
typeof result === 'number' ? result : null,
);
+
+ return {
+ consumedValues: values.slice(0, counters.length),
+ userShare: values[counters.length] ?? null,
+ };
}
private async fetchWarmValues({
@@ -846,10 +1022,13 @@ export class UsageLimitQuotaService {
return Promise.all(
counters.map(async (counter) => {
- if (counter.kind === 'allowance') {
- return this.usageAnalyticsService.getCreditsUsedMicroForBillingPeriod(
- { workspaceId, periodStart: counter.periodStart },
- );
+ if (counter.kind === 'workspaceAllowance') {
+ const { workspaceCreditsUsedMicro } =
+ await this.usageAnalyticsService.getCreditsUsedMicroForBillingPeriod(
+ { workspaceId, periodStart: counter.periodStart },
+ );
+
+ return workspaceCreditsUsedMicro;
}
const periodGroupKey = buildPeriodGroupKey(counter);
@@ -870,7 +1049,7 @@ export class UsageLimitQuotaService {
counter,
}: {
workspaceId: string;
- counter: LimitQuotaCounter;
+ counter: LimitQuotaCounter | UserAllowanceQuotaCounter;
}): Promise<UsageConsumptionRow[]> {
return this.usageAnalyticsService.getConsumptionRowsForAllScopes({
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
index 418c5ff7d36..7289ea3ada8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
@@ -119,9 +119,9 @@ export class UsageLimitStockService {
...args,
cost,
buildArguments: (amounts) =>
- buildConsumeScriptArguments(
- amounts.map((amount) => ({ amount, warm: null })),
- ),
+ buildConsumeScriptArguments({
+ entries: amounts.map((amount) => ({ amount, warm: null })),
+ }),
});
}
@@ -326,14 +326,14 @@ export class UsageLimitStockService {
const warmedValues = await this.runWarmAndConsumeScript({
counters: coldCounters,
- args: buildConsumeScriptArguments(
- warmValues.map((warmValue) => ({
+ args: buildConsumeScriptArguments({
+ entries: warmValues.map((warmValue) => ({
amount: 0,
warm: isDefined(warmValue)
? { value: warmValue, ttl: STOCK_COUNTER_TTL_MS }
: null,
})),
- ),
+ }),
});
const warmedValueByKey = new Map(
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-admission.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-admission.service.ts
index 0d999aa4b5a..351223a4a9a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-admission.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-admission.service.ts
@@ -77,7 +77,9 @@ export class UsageQuotaAdmissionService {
}
const remainingMicro =
- await this.usageLimitQuotaService.getAllowanceRemainingMicro(workspaceId);
+ await this.usageLimitQuotaService.getWorkspaceAllowanceRemainingMicro(
+ workspaceId,
+ );
if (isDefined(remainingMicro) && remainingMicro <= 0) {
return { hasAvailableCredits: false, reason: 'NO_CREDITS' };
@@ -85,11 +87,4 @@ export class UsageQuotaAdmissionService {
return { hasAvailableCredits: true };
}
-
- async hasAvailableCredits(workspaceId: string): Promise<boolean> {
- const { hasAvailableCredits } =
- await this.getCreditAvailability(workspaceId);
-
- return hasAvailableCredits;
- }
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts
index d7e91ec8e07..04be48d523d 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts
@@ -15,6 +15,7 @@ import { type UsageQuotaScopeConsumption } from 'src/engine/core-modules/usage-l
import { type UsageQuotaWithConsumption } from 'src/engine/core-modules/usage-limit/types/usage-quota-with-consumption.type';
import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
import { buildCustomQuota } from 'src/engine/core-modules/usage-limit/utils/build-custom-quota.util';
+import { computeRowConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-row-consumed.util';
import { getPeriodAnchor } from 'src/engine/core-modules/usage-limit/utils/get-period-anchor.util';
import { isAnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util';
import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
@@ -94,9 +95,10 @@ export class UsageQuotaConsumptionService {
});
return {
- consumedValue: Number(
- isCreditLimit ? totals.creditsUsedMicro : totals.quantity,
- ),
+ consumedValue: computeRowConsumed({
+ row: { ...totals, unit: scope.unit },
+ scope,
+ }),
periodStart: period.periodStart,
periodEnd: period.periodEnd,
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-kind.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-kind.type.ts
index 7d89d9be716..e3885d1a564 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-kind.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-kind.type.ts
@@ -1 +1 @@
-export type ExhaustedKind = 'limit' | 'allowance';
+export type ExhaustedKind = 'limit' | 'workspaceAllowance' | 'userAllowance';
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
index 5970b5180df..ae9b73e7805 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
@@ -1,8 +1,8 @@
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
-import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type QuotaOperationTypes } from 'src/engine/core-modules/usage-limit/types/quota-operation-types.type';
export type LimitQuotaCounter = {
kind: 'limit';
@@ -16,5 +16,5 @@ export type LimitQuotaCounter = {
periodEnd: Date;
spenderType: SpenderType;
spenderId: string | null;
- operationType: UsageOperationType;
+ operationTypes: QuotaOperationTypes;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-counter.type.ts
index 5a2db6706cf..70ddbe75982 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-counter.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-counter.type.ts
@@ -1,4 +1,8 @@
-import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type WorkspaceAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/workspace-allowance-quota-counter.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type UserAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type';
-export type QuotaCounter = LimitQuotaCounter | AllowanceQuotaCounter;
+export type QuotaCounter =
+ | LimitQuotaCounter
+ | WorkspaceAllowanceQuotaCounter
+ | UserAllowanceQuotaCounter;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit-result.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit-result.type.ts
new file mode 100644
index 00000000000..6d9b04aafd4
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit-result.type.ts
@@ -0,0 +1,7 @@
+import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';
+
+export type QuotaDebitResult = {
+ exhaustedKind: ExhaustedKind | null;
+ userCreditsUsedMicro: number;
+ userAllowanceExhaustedUntil: Date | null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit.type.ts
index 98850bd5550..e12e6718dd9 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit.type.ts
@@ -3,4 +3,8 @@ import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quo
export type QuotaDebit = {
counter: QuotaCounter;
amount: number;
+ split:
+ | { kind: 'userCredits'; limitValue: number }
+ | { kind: 'workspaceCredits' }
+ | null;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type.ts
index 69f9cad064f..21fc21a0cd8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type.ts
@@ -1,21 +1,22 @@
-import { type NumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type';
+import { type OptionalNumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/optional-numeric-config-variable-key.type';
import { type AnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/types/anchored-period-unit.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
-import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type QuotaOperationTypes } from 'src/engine/core-modules/usage-limit/types/quota-operation-types.type';
export type QuotaLimitDefaultDefinition<
TResourceType extends UsageResourceType = UsageResourceType,
> = {
resourceType: TResourceType;
- operationType: UsageOperationType;
+ operationTypes: QuotaOperationTypes;
limitKind: 'quota';
spenderType: SpenderType;
spenderId: '';
+ isPerSpender: boolean;
unit: UsageUnit;
periodUnit: AnchoredPeriodUnit;
periodCount: 1;
- limitValueConfigVariable: NumericConfigVariableKey;
- isOverridable: true;
+ limitValueConfigVariable: OptionalNumericConfigVariableKey;
+ isOverridable: boolean;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-operation-types.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-operation-types.type.ts
new file mode 100644
index 00000000000..4e149e3ded4
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-operation-types.type.ts
@@ -0,0 +1,3 @@
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+export type QuotaOperationTypes = [UsageOperationType, ...UsageOperationType[]];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type.ts
new file mode 100644
index 00000000000..47fe83cd950
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type.ts
@@ -0,0 +1,5 @@
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+
+export type UserAllowanceQuotaCounter = Omit<LimitQuotaCounter, 'kind'> & {
+ kind: 'userAllowance';
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/workspace-allowance-quota-counter.type.ts
similarity index 71%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts
rename to packages/twenty-server/src/engine/core-modules/usage-limit/types/workspace-allowance-quota-counter.type.ts
index 4de1bcf0b8c..f9757688009 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/workspace-allowance-quota-counter.type.ts
@@ -1,7 +1,7 @@
import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-export type AllowanceQuotaCounter = {
- kind: 'allowance';
+export type WorkspaceAllowanceQuotaCounter = {
+ kind: 'workspaceAllowance';
key: string;
limitValue: number;
unit: UsageUnit.CREDIT;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-consume-script-arguments.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-consume-script-arguments.util.spec.ts
index 2fb97e620cf..6f90dee880e 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-consume-script-arguments.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-consume-script-arguments.util.spec.ts
@@ -5,7 +5,7 @@ describe('buildConsumeScriptArguments', () => {
'refuses the amount %s',
(amount) => {
expect(() =>
- buildConsumeScriptArguments([{ amount, warm: null }]),
+ buildConsumeScriptArguments({ entries: [{ amount, warm: null }] }),
).toThrow(/^Counter amount .* is not a non-negative safe integer$/);
},
);
@@ -17,8 +17,51 @@ describe('buildConsumeScriptArguments', () => {
{ value: 10, ttl: -1 },
{ value: 10, ttl: 1.5 },
])('refuses the warm value $value with TTL $ttl', (warm) => {
- expect(() => buildConsumeScriptArguments([{ amount: 1, warm }])).toThrow(
+ expect(() =>
+ buildConsumeScriptArguments({ entries: [{ amount: 1, warm }] }),
+ ).toThrow(
/^Counter warm value .* is not a non-negative safe integer with a positive safe TTL$/,
);
});
+
+ it.each([-1, 1.5, Number.NaN])(
+ 'refuses the user credits limit %s',
+ (limitValue) => {
+ expect(() =>
+ buildConsumeScriptArguments({
+ entries: [
+ {
+ amount: 1,
+ warm: null,
+ split: { kind: 'userCredits', limitValue },
+ },
+ ],
+ }),
+ ).toThrow(/^User credits limit .* is not a non-negative safe integer$/);
+ },
+ );
+
+ it('passes the split of each key, the user limits and the fallback', () => {
+ expect(
+ buildConsumeScriptArguments({
+ entries: [
+ { amount: 5, warm: null },
+ {
+ amount: 300,
+ warm: { value: 900, ttl: 60_000 },
+ split: { kind: 'userCredits', limitValue: 1_000 },
+ },
+ { amount: 300, warm: null, split: { kind: 'workspaceCredits' } },
+ ],
+ isUserCreditsFallbackEnabled: true,
+ }),
+ ).toEqual([
+ '[5,300,300]',
+ '[false,900,false]',
+ '[false,60000,false]',
+ '[false,"userCredits","workspaceCredits"]',
+ '[false,1000,false]',
+ 'true',
+ ]);
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counter-key.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counter-key.util.spec.ts
index b6166a03fa8..dfefba37122 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counter-key.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counter-key.util.spec.ts
@@ -13,7 +13,7 @@ const buildKey = (overrides: Partial<CounterIdentity> = {}) =>
workspaceId: WORKSPACE_ID,
counter: {
resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
spenderType: 'workspace',
spenderId: null,
unit: UsageUnit.CREDIT,
@@ -30,8 +30,8 @@ describe('buildQuotaCounterKey', () => {
);
});
- it.each([
- ['operationType', { operationType: UsageOperationType.WEB_SEARCH }],
+ it.each<[string, Partial<CounterIdentity>]>([
+ ['operationTypes', { operationTypes: [UsageOperationType.WEB_SEARCH] }],
['unit', { unit: UsageUnit.TOKEN }],
['spenderId', { spenderId: 'user-1' }],
['periodUnit', { periodUnit: 'week' as const }],
@@ -39,4 +39,17 @@ describe('buildQuotaCounterKey', () => {
])('gives two counters differing only by %s their own key', (_, differs) => {
expect(buildKey(differs)).not.toBe(buildKey());
});
+
+ it('keys a counter over several operations by their sorted list', () => {
+ expect(
+ buildKey({
+ operationTypes: [
+ UsageOperationType.WEB_SEARCH,
+ UsageOperationType.AI_CHAT_TOKEN,
+ ],
+ }),
+ ).toBe(
+ `{${WORKSPACE_ID}}:quota-consumed:AI:AI_CHAT_TOKEN+WEB_SEARCH:workspace:-:CREDIT:month:${PERIOD_START.getTime()}`,
+ );
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
index 6e56c7b2808..c9b3cbe8230 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
@@ -35,10 +35,11 @@ const buildDefault = (
overrides: Partial<QuotaLimitDefault> = {},
): QuotaLimitDefault => ({
resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
limitKind: 'quota',
spenderType: 'workspace',
spenderId: '',
+ isPerSpender: false,
unit: UsageUnit.CREDIT,
periodUnit: 'month',
periodCount: 1,
@@ -50,16 +51,18 @@ const buildDefault = (
const buildCounters = ({
limits = [],
quotaLimitDefaults = [],
+ operationType = UsageOperationType.AI_CHAT_TOKEN,
}: {
limits?: FlatQuotaLimit[];
quotaLimitDefaults?: QuotaLimitDefault[];
+ operationType?: UsageOperationType;
}) =>
buildQuotaCounters({
limits,
quotaLimitDefaults,
usageSpenders: { userWorkspaceId: 'user-1' },
workspaceId: 'workspace-1',
- operationType: UsageOperationType.AI_CHAT_TOKEN,
+ operationType,
periodByUnit: { month: MONTH_PERIOD, week: WEEK_PERIOD },
});
@@ -82,7 +85,7 @@ describe('buildQuotaCounters', () => {
periodEnd: MONTH_PERIOD.periodEnd,
spenderType: 'workspace',
spenderId: null,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
},
]);
});
@@ -117,9 +120,9 @@ describe('buildQuotaCounters', () => {
],
});
- expect(counters.map((counter) => counter.operationType)).toEqual([
- UsageOperationType.AI_CHAT_TOKEN,
- UsageOperationType.ALL,
+ expect(counters.map((counter) => counter.operationTypes)).toEqual([
+ [UsageOperationType.AI_CHAT_TOKEN],
+ [UsageOperationType.ALL],
]);
});
@@ -152,14 +155,14 @@ describe('buildQuotaCounters', () => {
});
expect(
- counters.map(({ resourceType, operationType }) => [
+ counters.map(({ resourceType, operationTypes }) => [
resourceType,
- operationType,
+ operationTypes,
]),
).toEqual([
- [UsageResourceType.AI, UsageOperationType.AI_CHAT_TOKEN],
- [UsageResourceType.AI, UsageOperationType.ALL],
- [UsageResourceType.ALL, UsageOperationType.ALL],
+ [UsageResourceType.AI, [UsageOperationType.AI_CHAT_TOKEN]],
+ [UsageResourceType.AI, [UsageOperationType.ALL]],
+ [UsageResourceType.ALL, [UsageOperationType.ALL]],
]);
expect(counters[2].key).toContain(
':quota-consumed:ALL:ALL:application:app-1:',
@@ -220,7 +223,7 @@ describe('buildQuotaCounters', () => {
periodEnd: MONTH_PERIOD.periodEnd,
spenderType: 'workspace',
spenderId: null,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
},
]);
});
@@ -266,7 +269,7 @@ describe('buildQuotaCounters', () => {
it('ignores a default declared on another operation', () => {
const counters = buildCounters({
quotaLimitDefaults: [
- buildDefault({ operationType: UsageOperationType.WEB_SEARCH }),
+ buildDefault({ operationTypes: [UsageOperationType.WEB_SEARCH] }),
],
});
@@ -285,4 +288,131 @@ describe('buildQuotaCounters', () => {
]);
expect(new Set(counters.map((counter) => counter.key)).size).toBe(2);
});
+
+ it('gives each spender its own counter for a per-spender default', () => {
+ const counters = buildCounters({
+ quotaLimitDefaults: [
+ buildDefault({ spenderType: 'userWorkspace', isPerSpender: true }),
+ ],
+ });
+
+ expect(counters).toEqual([
+ expect.objectContaining({
+ isDefault: true,
+ spenderType: 'userWorkspace',
+ spenderId: 'user-1',
+ key: `{workspace-1}:quota-consumed:AI:AI_CHAT_TOKEN:userWorkspace:user-1:CREDIT:month:${MONTH_PERIOD.periodStart.getTime()}`,
+ }),
+ ]);
+ });
+
+ it('builds a user allowance counter from a user credit default', () => {
+ const counters = buildCounters({
+ quotaLimitDefaults: [
+ buildDefault({
+ spenderType: 'userWorkspace',
+ isPerSpender: true,
+ unit: UsageUnit.USER_CREDIT,
+ }),
+ ],
+ });
+
+ expect(counters).toEqual([
+ expect.objectContaining({
+ kind: 'userAllowance',
+ spenderId: 'user-1',
+ unit: UsageUnit.USER_CREDIT,
+ }),
+ ]);
+ });
+
+ it('builds no user allowance counter when user credits are 0', () => {
+ const counters = buildCounters({
+ quotaLimitDefaults: [
+ buildDefault({
+ spenderType: 'userWorkspace',
+ isPerSpender: true,
+ unit: UsageUnit.USER_CREDIT,
+ limitValue: 0,
+ }),
+ buildDefault({ limitValue: 0 }),
+ ],
+ });
+
+ expect(counters).toEqual([
+ expect.objectContaining({ kind: 'limit', limitValue: 0 }),
+ ]);
+ });
+
+ it('shares one counter across spenders for a default that is not per spender', () => {
+ const counters = buildCounters({
+ quotaLimitDefaults: [buildDefault({ spenderType: 'userWorkspace' })],
+ });
+
+ expect(counters).toEqual([
+ expect.objectContaining({
+ spenderType: 'userWorkspace',
+ spenderId: null,
+ key: `{workspace-1}:quota-consumed:AI:AI_CHAT_TOKEN:userWorkspace:-:CREDIT:month:${MONTH_PERIOD.periodStart.getTime()}`,
+ }),
+ ]);
+ });
+
+ it('shares one counter across the operations a default lists', () => {
+ const quotaLimitDefaults = [
+ buildDefault({
+ operationTypes: [
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ],
+ isOverridable: false,
+ }),
+ ];
+
+ const [chatCounter] = buildCounters({ quotaLimitDefaults });
+ const [webSearchCounter] = buildCounters({
+ quotaLimitDefaults,
+ operationType: UsageOperationType.WEB_SEARCH,
+ });
+
+ expect(chatCounter.key).toBe(webSearchCounter.key);
+ });
+
+ it('ignores a default listing other operations', () => {
+ const counters = buildCounters({
+ quotaLimitDefaults: [
+ buildDefault({
+ operationTypes: [
+ UsageOperationType.WEB_SEARCH,
+ UsageOperationType.AI_WORKFLOW_TOKEN,
+ ],
+ isOverridable: false,
+ }),
+ ],
+ });
+
+ expect(counters).toEqual([]);
+ });
+
+ it('ranks a single operation before a list, and a list before every operation', () => {
+ const counters = buildCounters({
+ quotaLimitDefaults: [
+ buildDefault({ operationTypes: [UsageOperationType.ALL] }),
+ buildDefault({
+ operationTypes: [
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ],
+ isOverridable: false,
+ }),
+ buildDefault(),
+ ],
+ });
+
+ expect(counters.map((counter) => counter.operationTypes)).toEqual([
+ [UsageOperationType.AI_CHAT_TOKEN],
+ [UsageOperationType.AI_CHAT_TOKEN, UsageOperationType.WEB_SEARCH],
+ [UsageOperationType.ALL],
+ ]);
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
index 7099af958f4..b9fde676104 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
@@ -1,5 +1,6 @@
-import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type WorkspaceAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/workspace-allowance-quota-counter.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type UserAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type';
import { buildQuotaDebits } from 'src/engine/core-modules/usage-limit/utils/build-quota-debits.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
@@ -9,15 +10,30 @@ import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/recor
const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
const PERIOD_END = new Date('2026-09-01T00:00:00.000Z');
-const allowanceCounter: AllowanceQuotaCounter = {
- kind: 'allowance',
- key: 'allowance',
+const workspaceAllowanceCounter: WorkspaceAllowanceQuotaCounter = {
+ kind: 'workspaceAllowance',
+ key: 'workspaceAllowance',
limitValue: 1_000_000,
unit: UsageUnit.CREDIT,
periodStart: PERIOD_START,
periodEnd: PERIOD_END,
};
+const userAllowanceCounter: UserAllowanceQuotaCounter = {
+ kind: 'userAllowance',
+ key: 'user-allowance',
+ limitValue: 1_000,
+ unit: UsageUnit.USER_CREDIT,
+ resourceType: UsageResourceType.AI,
+ operationTypes: [UsageOperationType.ALL],
+ periodUnit: 'week',
+ isDefault: true,
+ spenderType: 'userWorkspace',
+ spenderId: 'user-workspace-1',
+ periodStart: PERIOD_START,
+ periodEnd: PERIOD_END,
+};
+
const buildLimitCounter = (unit: UsageUnit): LimitQuotaCounter => ({
kind: 'limit',
isDefault: false,
@@ -25,7 +41,7 @@ const buildLimitCounter = (unit: UsageUnit): LimitQuotaCounter => ({
limitValue: 1_000_000,
unit,
resourceType: UsageResourceType.LOGIC_FUNCTION,
- operationType: UsageOperationType.ALL,
+ operationTypes: [UsageOperationType.ALL],
periodUnit: 'month',
periodStart: PERIOD_START,
periodEnd: PERIOD_END,
@@ -41,6 +57,15 @@ const logicFunctionEvent: RecordUsageInput = {
unit: UsageUnit.INVOCATION,
};
+const aiChatEvent: RecordUsageInput = {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ creditsUsedMicro: 500,
+ quantity: 1_200,
+ unit: UsageUnit.TOKEN,
+ spenders: { userWorkspaceId: 'user-workspace-1' },
+};
+
const workflowEvent: RecordUsageInput = {
resourceType: UsageResourceType.WORKFLOW,
operationType: UsageOperationType.WORKFLOW_EXECUTION,
@@ -58,7 +83,7 @@ describe('buildQuotaDebits', () => {
counters: [creditCounter],
events: [logicFunctionEvent, workflowEvent],
}),
- ).toEqual([{ counter: creditCounter, amount: 100 }]);
+ ).toEqual([{ counter: creditCounter, amount: 100, split: null }]);
});
it('debits an every-resource counter with its spender events from all resources', () => {
@@ -90,22 +115,77 @@ describe('buildQuotaDebits', () => {
},
],
}),
- ).toEqual([{ counter: allResourcesCounter, amount: 5_400 }]);
+ ).toEqual([{ counter: allResourcesCounter, amount: 5_400, split: null }]);
});
it('debits the allowance with the credits of every event', () => {
expect(
buildQuotaDebits({
- counters: [allowanceCounter],
+ counters: [workspaceAllowanceCounter],
events: [logicFunctionEvent, workflowEvent],
}),
- ).toEqual([{ counter: allowanceCounter, amount: 400 }]);
+ ).toEqual([
+ { counter: workspaceAllowanceCounter, amount: 400, split: null },
+ ]);
+ });
+
+ it('splits the credits between the user allowance and workspace credit counters', () => {
+ const workspaceCreditLimitCounter = {
+ ...buildLimitCounter(UsageUnit.CREDIT),
+ resourceType: UsageResourceType.AI,
+ };
+ const userCreditLimitCounter: LimitQuotaCounter = {
+ ...workspaceCreditLimitCounter,
+ key: 'user-credit-limit',
+ spenderType: 'userWorkspace',
+ spenderId: 'user-workspace-1',
+ };
+
+ expect(
+ buildQuotaDebits({
+ counters: [
+ userAllowanceCounter,
+ workspaceCreditLimitCounter,
+ userCreditLimitCounter,
+ workspaceAllowanceCounter,
+ ],
+ events: [aiChatEvent],
+ }),
+ ).toEqual([
+ {
+ counter: userAllowanceCounter,
+ amount: 500,
+ split: { kind: 'userCredits', limitValue: 1_000 },
+ },
+ {
+ counter: workspaceCreditLimitCounter,
+ amount: 500,
+ split: { kind: 'workspaceCredits' },
+ },
+ { counter: userCreditLimitCounter, amount: 500, split: null },
+ {
+ counter: workspaceAllowanceCounter,
+ amount: 500,
+ split: { kind: 'workspaceCredits' },
+ },
+ ]);
+ });
+
+ it('splits nothing when the user allowance has nothing to pay', () => {
+ expect(
+ buildQuotaDebits({
+ counters: [userAllowanceCounter, workspaceAllowanceCounter],
+ events: [logicFunctionEvent],
+ }),
+ ).toEqual([
+ { counter: workspaceAllowanceCounter, amount: 100, split: null },
+ ]);
});
it('drops a counter the events consume nothing of', () => {
expect(
buildQuotaDebits({
- counters: [allowanceCounter],
+ counters: [workspaceAllowanceCounter],
events: [{ ...logicFunctionEvent, creditsUsedMicro: 0 }],
}),
).toEqual([]);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
index 9946134ee13..7399d6bdfe7 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
@@ -51,6 +51,10 @@ describe('buildQuotaDefinitions', () => {
operationType: UsageOperationType.WEB_SEARCH,
allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
},
+ {
+ operationType: UsageOperationType.AI_WORKFLOW_WEB_SEARCH,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
]);
});
@@ -68,6 +72,12 @@ describe('buildQuotaDefinitions', () => {
});
it('lists no operator-only scope for a resource without quota defaults', () => {
+ expect(
+ findQuotaDefinition(UsageResourceType.LOGIC_FUNCTION)?.operatorOnlyScopes,
+ ).toEqual([]);
+ });
+
+ it('lists no operator-only scope for a default over several operations, since no usage limit can override it', () => {
expect(
findQuotaDefinition(UsageResourceType.AI)?.operatorOnlyScopes,
).toEqual([]);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-exception.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-exception.util.spec.ts
index 73617063f80..ba914ba291f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-exception.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-exception.util.spec.ts
@@ -30,18 +30,40 @@ describe('buildQuotaExhaustedException', () => {
});
it('overrides the generic user friendly message when the credit allowance is exhausted', () => {
- const allowanceException = buildQuotaExhaustedException(
- buildExhaustedScope({ exhaustedKind: 'allowance' }),
+ const workspaceAllowanceException = buildQuotaExhaustedException(
+ buildExhaustedScope({ exhaustedKind: 'workspaceAllowance' }),
);
- expect(allowanceException.message).toBe(
+ expect(workspaceAllowanceException.message).toBe(
'Credit allowance exhausted for this billing period',
);
- expect(allowanceException.userFriendlyMessage).not.toEqual(
+ expect(workspaceAllowanceException.userFriendlyMessage).not.toEqual(
buildQuotaExhaustedException(buildExhaustedScope()).userFriendlyMessage,
);
});
+ it('tells the member their own AI credits are used up when the user allowance is exhausted', () => {
+ const userAllowanceException = buildQuotaExhaustedException(
+ buildExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ exhaustedKind: 'userAllowance',
+ operationType: UsageOperationType.ALL,
+ periodCount: null,
+ periodUnit: null,
+ }),
+ );
+
+ expect(userAllowanceException.message).toBe(
+ 'User credits allowance exhausted for this period',
+ );
+ expect(userAllowanceException.code).toBe(
+ UsageLimitExceptionCode.QUOTA_EXHAUSTED,
+ );
+ expect(userAllowanceException.userFriendlyMessage.message).toBe(
+ 'Your AI credits for this period are used up.',
+ );
+ });
+
it('carries the exhausted scope so the api filters can build a response', () => {
const exhaustedScope = buildExhaustedScope();
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
index f7dd1f89a1c..9f59be0dbfc 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
@@ -1,5 +1,6 @@
-import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type WorkspaceAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/workspace-allowance-quota-counter.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type UserAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type';
import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
@@ -23,12 +24,12 @@ const buildLimitCounter = (
periodEnd: PERIOD_END,
spenderType: 'userWorkspace',
spenderId: 'user-1',
- operationType: UsageOperationType.AI_CHAT_TOKEN,
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
...overrides,
});
-const allowanceCounter: AllowanceQuotaCounter = {
- kind: 'allowance',
+const workspaceAllowanceCounter: WorkspaceAllowanceQuotaCounter = {
+ kind: 'workspaceAllowance',
key: 'allowance-key',
limitValue: 2_000_000,
unit: UsageUnit.CREDIT,
@@ -36,6 +37,23 @@ const allowanceCounter: AllowanceQuotaCounter = {
periodEnd: PERIOD_END,
};
+const USER_ALLOWANCE_PERIOD_END = new Date('2026-08-25T00:00:00.000Z');
+
+const userAllowanceCounter: UserAllowanceQuotaCounter = {
+ kind: 'userAllowance',
+ key: 'user-allowance-key',
+ limitValue: 3_000_000,
+ unit: UsageUnit.USER_CREDIT,
+ resourceType: UsageResourceType.AI,
+ operationTypes: [UsageOperationType.ALL],
+ periodUnit: 'week',
+ isDefault: true,
+ spenderType: 'userWorkspace',
+ spenderId: 'user-workspace-1',
+ periodStart: new Date('2026-07-25T00:00:00.000Z'),
+ periodEnd: USER_ALLOWANCE_PERIOD_END,
+};
+
describe('buildQuotaExhaustedScope', () => {
beforeAll(() => {
jest.useFakeTimers().setSystemTime(NOW);
@@ -49,6 +67,7 @@ describe('buildQuotaExhaustedScope', () => {
expect(
buildQuotaExhaustedScope({
resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
counter: buildLimitCounter(),
}),
).toEqual({
@@ -72,9 +91,10 @@ describe('buildQuotaExhaustedScope', () => {
expect(
buildQuotaExhaustedScope({
resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
counter: buildLimitCounter({
resourceType: UsageResourceType.ALL,
- operationType: UsageOperationType.ALL,
+ operationTypes: [UsageOperationType.ALL],
spenderType: 'application',
spenderId: 'application-1',
}),
@@ -89,6 +109,7 @@ describe('buildQuotaExhaustedScope', () => {
expect(
buildQuotaExhaustedScope({
resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
counter: buildLimitCounter({ isDefault: true }),
}),
).toMatchObject({ exhaustedKind: 'limit', isDefault: true });
@@ -98,12 +119,13 @@ describe('buildQuotaExhaustedScope', () => {
expect(
buildQuotaExhaustedScope({
resourceType: UsageResourceType.AI,
- counter: allowanceCounter,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ counter: workspaceAllowanceCounter,
}),
).toEqual({
resourceType: UsageResourceType.AI,
limitKind: 'quota',
- exhaustedKind: 'allowance',
+ exhaustedKind: 'workspaceAllowance',
spenderType: 'workspace',
spenderId: null,
operationType: UsageOperationType.ALL,
@@ -116,14 +138,54 @@ describe('buildQuotaExhaustedScope', () => {
});
});
+ it('scopes an exhausted user allowance counter to the member until the week ends', () => {
+ expect(
+ buildQuotaExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ counter: userAllowanceCounter,
+ }),
+ ).toEqual({
+ resourceType: UsageResourceType.AI,
+ limitKind: 'quota',
+ exhaustedKind: 'userAllowance',
+ spenderType: 'userWorkspace',
+ spenderId: 'user-workspace-1',
+ operationType: UsageOperationType.ALL,
+ unit: UsageUnit.USER_CREDIT,
+ limitValue: 3_000_000,
+ remaining: 0,
+ periodCount: 1,
+ periodUnit: 'week',
+ retryAfterMs: USER_ALLOWANCE_PERIOD_END.getTime() - NOW.getTime(),
+ isDefault: true,
+ });
+ });
+
it('clamps the retry delay to zero once the period has ended', () => {
expect(
buildQuotaExhaustedScope({
resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
counter: buildLimitCounter({
periodEnd: new Date('2026-08-10T00:00:00.000Z'),
}),
}),
).toMatchObject({ retryAfterMs: 0 });
});
+
+ it('reports the charge operation for a counter over several operations', () => {
+ expect(
+ buildQuotaExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.WEB_SEARCH,
+ counter: buildLimitCounter({
+ operationTypes: [
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ],
+ }),
+ }),
+ ).toMatchObject({ operationType: UsageOperationType.WEB_SEARCH });
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts
index c1cc285d773..a6b4bf97d3b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts
@@ -7,19 +7,28 @@ import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const buildRow = (
overrides: Partial<UsageConsumptionRow>,
-): UsageConsumptionRow => ({
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- unit: UsageUnit.TOKEN,
- userWorkspaceId: 'user-1',
- apiKeyId: '',
- applicationId: '',
- agentId: '',
- workflowId: '',
- logicFunctionId: '',
- creditsUsedMicro: '100',
- quantity: '10',
- ...overrides,
-});
+): UsageConsumptionRow => {
+ const creditsUsedMicro = overrides.creditsUsedMicro ?? '100';
+ const userCreditsUsedMicro = overrides.userCreditsUsedMicro ?? '0';
+
+ return {
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ unit: UsageUnit.TOKEN,
+ userWorkspaceId: 'user-1',
+ apiKeyId: '',
+ applicationId: '',
+ agentId: '',
+ workflowId: '',
+ logicFunctionId: '',
+ creditsUsedMicro,
+ userCreditsUsedMicro,
+ workspaceCreditsUsedMicro: String(
+ Number(creditsUsedMicro) - Number(userCreditsUsedMicro),
+ ),
+ quantity: '10',
+ ...overrides,
+ };
+};
const buildCounter = (
overrides: Partial<LimitQuotaCounter>,
@@ -35,7 +44,7 @@ const buildCounter = (
periodEnd: new Date('2026-09-01T00:00:00.000Z'),
spenderType: 'workspace',
spenderId: null,
- operationType: UsageOperationType.ALL,
+ operationTypes: [UsageOperationType.ALL],
...overrides,
});
@@ -65,7 +74,7 @@ describe('computeQuotaConsumed', () => {
computeQuotaConsumed({
rows,
scope: buildCounter({
- operationType: UsageOperationType.AI_CHAT_TOKEN,
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
}),
}),
).toBe(140);
@@ -172,7 +181,7 @@ describe('computeQuotaConsumed', () => {
];
const logicFunctionScope = buildCounter({
- operationType: UsageOperationType.CODE_EXECUTION,
+ operationTypes: [UsageOperationType.CODE_EXECUTION],
spenderType: 'logicFunction',
spenderId: 'logic-function-1',
});
@@ -213,4 +222,63 @@ describe('computeQuotaConsumed', () => {
}),
).toBe(20_000_000);
});
+
+ it('sums only the listed operations for a scope over several operations', () => {
+ expect(
+ computeQuotaConsumed({
+ rows,
+ scope: buildCounter({
+ operationTypes: [
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ],
+ }),
+ }),
+ ).toBe(140);
+ });
+
+ describe('when user credits paid part of the credits', () => {
+ const rowsWithUserCredits = [
+ buildRow({ creditsUsedMicro: '100', userCreditsUsedMicro: '60' }),
+ buildRow({
+ userWorkspaceId: 'user-2',
+ creditsUsedMicro: '40',
+ userCreditsUsedMicro: '40',
+ }),
+ ];
+
+ it('counts only the workspace credits on a workspace-wide credit counter', () => {
+ expect(
+ computeQuotaConsumed({
+ rows: rowsWithUserCredits,
+ scope: buildCounter({}),
+ }),
+ ).toBe(40);
+ });
+
+ it('counts every credit on a credit counter of one user', () => {
+ expect(
+ computeQuotaConsumed({
+ rows: rowsWithUserCredits,
+ scope: buildCounter({
+ spenderType: 'userWorkspace',
+ spenderId: 'user-1',
+ }),
+ }),
+ ).toBe(100);
+ });
+
+ it('counts only the user credits on a user credit counter', () => {
+ expect(
+ computeQuotaConsumed({
+ rows: rowsWithUserCredits,
+ scope: buildCounter({
+ unit: UsageUnit.USER_CREDIT,
+ spenderType: 'userWorkspace',
+ spenderId: 'user-1',
+ }),
+ }),
+ ).toBe(60);
+ });
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts
index 2bfa9b5d987..7c006400a15 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts
@@ -1,4 +1,3 @@
-import { type StockLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type';
import {
buildUsageLimitScope,
type UsageLimitScope,
@@ -8,18 +7,20 @@ import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-op
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+type SuppressibleDefault = Parameters<
+ typeof doesUsageLimitRowSuppressDefault
+>[0]['usageLimitDefault'];
+
const buildDefault = (
- overrides: Partial<StockLimitDefaultDefinition> = {},
-): StockLimitDefaultDefinition => ({
+ overrides: Partial<SuppressibleDefault> = {},
+): SuppressibleDefault => ({
resourceType: UsageResourceType.STORAGE,
- operationType: UsageOperationType.STORAGE_FILE,
+ operationTypes: [UsageOperationType.STORAGE_FILE],
limitKind: 'stock',
spenderType: 'workspace',
spenderId: '',
unit: UsageUnit.BYTE,
periodUnit: 'lifetime',
- periodCount: 1,
- limitValueConfigVariable: 'WORKSPACE_STORAGE_LIMIT_BYTES',
isOverridable: true,
...overrides,
});
@@ -103,7 +104,7 @@ describe('doesUsageLimitRowSuppressDefault', () => {
expect(
doesUsageLimitRowSuppressDefault({
scope: buildScope({ periodCount: 60 }),
- usageLimitDefault: buildDefault({ periodCount: 1 }),
+ usageLimitDefault: buildDefault(),
}),
).toBe(true);
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-blocking-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-blocking-counters.util.spec.ts
new file mode 100644
index 00000000000..e09f5187807
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-blocking-counters.util.spec.ts
@@ -0,0 +1,148 @@
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
+import { type UserAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type';
+import { findBlockingCounters } from 'src/engine/core-modules/usage-limit/utils/find-blocking-counters.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
+const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
+
+const workspaceCreditLimit: LimitQuotaCounter = {
+ kind: 'limit',
+ isDefault: false,
+ key: 'workspace-credit-limit',
+ limitValue: 1_000,
+ unit: UsageUnit.CREDIT,
+ resourceType: UsageResourceType.AI,
+ periodUnit: 'month',
+ periodStart: PERIOD_START,
+ periodEnd: new Date('2026-09-01T00:00:00.000Z'),
+ spenderType: 'workspace',
+ spenderId: null,
+ operationTypes: [UsageOperationType.ALL],
+};
+
+const userCreditLimit: LimitQuotaCounter = {
+ ...workspaceCreditLimit,
+ key: 'user-credit-limit',
+ spenderType: 'userWorkspace',
+ spenderId: 'user-workspace-1',
+};
+
+const weekUserAllowance: UserAllowanceQuotaCounter = {
+ ...userCreditLimit,
+ kind: 'userAllowance',
+ key: 'week-user-allowance',
+ unit: UsageUnit.USER_CREDIT,
+ periodUnit: 'week',
+ periodEnd: new Date('2026-08-08T00:00:00.000Z'),
+};
+
+const dayUserAllowance: UserAllowanceQuotaCounter = {
+ ...weekUserAllowance,
+ key: 'day-user-allowance',
+ periodUnit: 'day',
+ periodEnd: new Date('2026-08-02T00:00:00.000Z'),
+};
+
+const workspaceAllowance: QuotaCounter = {
+ kind: 'workspaceAllowance',
+ key: 'workspace-allowance',
+ limitValue: 5_000,
+ unit: UsageUnit.CREDIT,
+ periodStart: PERIOD_START,
+ periodEnd: new Date('2026-09-01T00:00:00.000Z'),
+};
+
+const { STOP, WORKSPACE_CREDITS } = UserCreditsFallback;
+
+const allExhausted = [
+ userCreditLimit,
+ workspaceCreditLimit,
+ workspaceAllowance,
+];
+
+describe('findBlockingCounters', () => {
+ it.each<{
+ title: string;
+ userAllowanceConsumedValues: (number | null)[];
+ userCreditsFallback: UserCreditsFallback;
+ exhaustedCounters: QuotaCounter[];
+ expected: QuotaCounter[];
+ }>([
+ {
+ title: 'without a user window',
+ userAllowanceConsumedValues: [],
+ userCreditsFallback: WORKSPACE_CREDITS,
+ exhaustedCounters: allExhausted,
+ expected: [workspaceAllowance, userCreditLimit, workspaceCreditLimit],
+ },
+ {
+ title: 'while spending user credits in spill mode',
+ userAllowanceConsumedValues: [0, 0],
+ userCreditsFallback: WORKSPACE_CREDITS,
+ exhaustedCounters: allExhausted,
+ expected: [userCreditLimit],
+ },
+ {
+ title: 'once a user window is used up in spill mode',
+ userAllowanceConsumedValues: [0, 1_000],
+ userCreditsFallback: WORKSPACE_CREDITS,
+ exhaustedCounters: [...allExhausted, dayUserAllowance],
+ expected: [workspaceAllowance, userCreditLimit, workspaceCreditLimit],
+ },
+ {
+ title: 'while spending user credits in STOP mode',
+ userAllowanceConsumedValues: [0, 0],
+ userCreditsFallback: STOP,
+ exhaustedCounters: allExhausted,
+ expected: [userCreditLimit],
+ },
+ {
+ title: 'once a user window is used up in STOP mode',
+ userAllowanceConsumedValues: [0, 1_000],
+ userCreditsFallback: STOP,
+ exhaustedCounters: [...allExhausted, dayUserAllowance],
+ expected: [dayUserAllowance, userCreditLimit],
+ },
+ {
+ title: 'when a user window was not read',
+ userAllowanceConsumedValues: [0, null],
+ userCreditsFallback: STOP,
+ exhaustedCounters: allExhausted,
+ expected: [workspaceAllowance, userCreditLimit, workspaceCreditLimit],
+ },
+ {
+ title: 'with the user window that ends last first',
+ userAllowanceConsumedValues: [1_000, 1_000],
+ userCreditsFallback: STOP,
+ exhaustedCounters: [dayUserAllowance, weekUserAllowance],
+ expected: [weekUserAllowance, dayUserAllowance],
+ },
+ ])(
+ 'keeps the counters that block $title',
+ ({
+ userAllowanceConsumedValues,
+ userCreditsFallback,
+ exhaustedCounters,
+ expected,
+ }) => {
+ expect(
+ findBlockingCounters({
+ counters: [
+ ...allExhausted,
+ ...[weekUserAllowance, dayUserAllowance].slice(
+ 0,
+ userAllowanceConsumedValues.length,
+ ),
+ ],
+ consumedValues: [1_000, 1_000, 5_000, ...userAllowanceConsumedValues],
+ exhaustedCounters,
+ userCreditsFallback,
+ }),
+ ).toEqual(expected);
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts
index d82389729ca..ae4011eacf8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts
@@ -1,4 +1,4 @@
-import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type WorkspaceAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/workspace-allowance-quota-counter.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
@@ -8,8 +8,10 @@ import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
const PERIOD_END = new Date('2026-09-01T00:00:00.000Z');
-const buildAllowanceCounter = (key: string): AllowanceQuotaCounter => ({
- kind: 'allowance',
+const buildWorkspaceAllowanceCounter = (
+ key: string,
+): WorkspaceAllowanceQuotaCounter => ({
+ kind: 'workspaceAllowance',
key,
limitValue: 5_000,
unit: UsageUnit.CREDIT,
@@ -27,7 +29,7 @@ const buildLimitCounter = (
limitValue: 1_000,
unit: UsageUnit.CREDIT,
resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
periodUnit: 'month',
periodStart: PERIOD_START,
periodEnd: PERIOD_END,
@@ -43,7 +45,7 @@ describe('findExhaustedCounters', () => {
counters: [
buildLimitCounter('under'),
buildLimitCounter('at'),
- buildAllowanceCounter('past'),
+ buildWorkspaceAllowanceCounter('past'),
],
consumedValues: [999, 1_000, 6_000],
}),
@@ -53,7 +55,10 @@ describe('findExhaustedCounters', () => {
it('skips cold counters', () => {
expect(
findExhaustedCounters({
- counters: [buildLimitCounter('cold'), buildAllowanceCounter('cold')],
+ counters: [
+ buildLimitCounter('cold'),
+ buildWorkspaceAllowanceCounter('cold'),
+ ],
consumedValues: [null, null],
}),
).toEqual([]);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-single-operation-type.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-single-operation-type.util.spec.ts
new file mode 100644
index 00000000000..570c44f460a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-single-operation-type.util.spec.ts
@@ -0,0 +1,19 @@
+import { findSingleOperationType } from 'src/engine/core-modules/usage-limit/utils/find-single-operation-type.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+describe('findSingleOperationType', () => {
+ it('returns the operation type of a one-item list', () => {
+ expect(findSingleOperationType([UsageOperationType.EMAIL_SEND])).toBe(
+ UsageOperationType.EMAIL_SEND,
+ );
+ });
+
+ it('returns null for several operation types', () => {
+ expect(
+ findSingleOperationType([
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ]),
+ ).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts
index e52ed2011c3..ad8d38f1ed0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts
@@ -5,6 +5,7 @@ import {
} from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';
import { doesUsageLimitRowSuppressDefault } from 'src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util';
import { findSuppressedUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util';
+import { getUsageLimitDefaultOperationTypes } from 'src/engine/core-modules/usage-limit/utils/get-usage-limit-default-operation-types.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
@@ -57,7 +58,21 @@ describe('findSuppressedUsageLimitDefaults', () => {
it('declares at most one overridable default per suppressible scope', () => {
const overridableDefaults = Object.values(UsageResourceType)
.flatMap((resourceType) => findUsageLimitDefaults({ resourceType }))
- .filter((usageLimitDefault) => usageLimitDefault.isOverridable);
+ .filter((usageLimitDefault) => usageLimitDefault.isOverridable)
+ .flatMap((usageLimitDefault) => {
+ const operationTypes =
+ getUsageLimitDefaultOperationTypes(usageLimitDefault);
+
+ return operationTypes.length === 1
+ ? [
+ {
+ ...usageLimitDefault,
+ operationType: operationTypes[0],
+ operationTypes,
+ },
+ ]
+ : [];
+ });
const defaultsSharingAScope = overridableDefaults.filter(
(usageLimitDefault) =>
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-unmetered-user-credits-share.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-unmetered-user-credits-share.util.spec.ts
new file mode 100644
index 00000000000..f49808ff967
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-unmetered-user-credits-share.util.spec.ts
@@ -0,0 +1,22 @@
+import { findUnmeteredUserCreditsShare } from 'src/engine/core-modules/usage-limit/utils/find-unmetered-user-credits-share.util';
+
+describe('findUnmeteredUserCreditsShare', () => {
+ it('charges the user the smallest amount across their windows', () => {
+ expect(
+ findUnmeteredUserCreditsShare([
+ { amount: 600, split: { kind: 'userCredits', limitValue: 1_000 } },
+ { amount: 400, split: { kind: 'userCredits', limitValue: 5_000 } },
+ { amount: 600, split: { kind: 'workspaceCredits' } },
+ ]),
+ ).toBe(400);
+ });
+
+ it('charges the user nothing when no user window applies', () => {
+ expect(
+ findUnmeteredUserCreditsShare([
+ { amount: 600, split: { kind: 'workspaceCredits' } },
+ { amount: 600, split: null },
+ ]),
+ ).toBe(0);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-usage-limit-default-operation-types.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-usage-limit-default-operation-types.util.spec.ts
new file mode 100644
index 00000000000..fda174711af
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-usage-limit-default-operation-types.util.spec.ts
@@ -0,0 +1,54 @@
+import { findUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-defaults.util';
+import { getUsageLimitDefaultOperationTypes } from 'src/engine/core-modules/usage-limit/utils/get-usage-limit-default-operation-types.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const findFirstDefault = (resourceType: UsageResourceType) => {
+ const [usageLimitDefault] = findUsageLimitDefaults({ resourceType });
+
+ return usageLimitDefault;
+};
+
+describe('getUsageLimitDefaultOperationTypes', () => {
+ it('wraps the single operation of a speed default', () => {
+ expect(
+ getUsageLimitDefaultOperationTypes(
+ findFirstDefault(UsageResourceType.API),
+ ),
+ ).toEqual([UsageOperationType.API_REQUEST]);
+ });
+
+ it('wraps the single operation of a stock default', () => {
+ expect(
+ getUsageLimitDefaultOperationTypes(
+ findFirstDefault(UsageResourceType.STORAGE),
+ ),
+ ).toEqual([UsageOperationType.STORAGE_FILE]);
+ });
+
+ it('returns the operations a quota default lists', () => {
+ expect(
+ getUsageLimitDefaultOperationTypes(
+ findFirstDefault(UsageResourceType.AI),
+ ),
+ ).toEqual([
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ]);
+ });
+
+ it('declares distinct operations on every default, with ALL only on its own', () => {
+ const operationTypesByDefault = Object.values(UsageResourceType)
+ .flatMap((resourceType) => findUsageLimitDefaults({ resourceType }))
+ .map(getUsageLimitDefaultOperationTypes);
+
+ expect(
+ operationTypesByDefault.filter(
+ (operationTypes) =>
+ new Set(operationTypes).size !== operationTypes.length ||
+ (operationTypes.includes(UsageOperationType.ALL) &&
+ operationTypes.length > 1),
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/is-operation-in-scope.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/is-operation-in-scope.util.spec.ts
new file mode 100644
index 00000000000..0a74705d826
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/is-operation-in-scope.util.spec.ts
@@ -0,0 +1,48 @@
+import { isOperationInScope } from 'src/engine/core-modules/usage-limit/utils/is-operation-in-scope.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+describe('isOperationInScope', () => {
+ it('covers every operation for ALL', () => {
+ expect(
+ isOperationInScope({
+ operationTypes: [UsageOperationType.ALL],
+ operationType: UsageOperationType.WEB_SEARCH,
+ }),
+ ).toBe(true);
+ });
+
+ it('covers only the named operation', () => {
+ expect(
+ isOperationInScope({
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ }),
+ ).toBe(true);
+ expect(
+ isOperationInScope({
+ operationTypes: [UsageOperationType.AI_CHAT_TOKEN],
+ operationType: UsageOperationType.WEB_SEARCH,
+ }),
+ ).toBe(false);
+ });
+
+ it('covers the listed operations only', () => {
+ const operationTypes = [
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.WEB_SEARCH,
+ ];
+
+ expect(
+ isOperationInScope({
+ operationTypes,
+ operationType: UsageOperationType.WEB_SEARCH,
+ }),
+ ).toBe(true);
+ expect(
+ isOperationInScope({
+ operationTypes,
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/split-user-credits-across-events.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/split-user-credits-across-events.util.spec.ts
new file mode 100644
index 00000000000..e034007e33a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/split-user-credits-across-events.util.spec.ts
@@ -0,0 +1,53 @@
+import { splitUserCreditsAcrossEvents } from 'src/engine/core-modules/usage-limit/utils/split-user-credits-across-events.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
+
+const buildEvent = (creditsUsedMicro?: number): RecordUsageInput => ({
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ creditsUsedMicro,
+ quantity: 1_200,
+ unit: UsageUnit.TOKEN,
+ spenders: { userWorkspaceId: 'user-workspace-1' },
+});
+
+const findShares = (events: RecordUsageInput[], userCreditsUsedMicro: number) =>
+ splitUserCreditsAcrossEvents({ events, userCreditsUsedMicro }).map(
+ (event) => event.userCreditsUsedMicro,
+ );
+
+describe('splitUserCreditsAcrossEvents', () => {
+ it('stamps the share on a single event and keeps the event as it was', () => {
+ const event = buildEvent(300);
+
+ expect(
+ splitUserCreditsAcrossEvents({
+ events: [event],
+ userCreditsUsedMicro: 100,
+ }),
+ ).toEqual([{ ...event, userCreditsUsedMicro: 100 }]);
+ });
+
+ it('fills the events in order, each up to its own credits', () => {
+ expect(
+ findShares([buildEvent(100), buildEvent(300), buildEvent(200)], 250),
+ ).toEqual([100, 150, 0]);
+ });
+
+ it('drops the part of a share above the credits of the events', () => {
+ expect(findShares([buildEvent(100), buildEvent(200)], 1_000)).toEqual([
+ 100, 200,
+ ]);
+ });
+
+ it('gives no share to an event whose credits are missing or not a whole number', () => {
+ expect(
+ findShares(
+ [buildEvent(undefined), buildEvent(100.5), buildEvent(300)],
+ 250,
+ ),
+ ).toEqual([0, 0, 250]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-rest-api-exception-handler.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-rest-api-exception-handler.util.spec.ts
index d9f73b75729..894fdc2c738 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-rest-api-exception-handler.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/usage-limit-to-rest-api-exception-handler.util.spec.ts
@@ -148,7 +148,7 @@ describe('usageLimitToRestApiExceptionHandler', () => {
buildExhaustedScope({
resourceType: UsageResourceType.AI,
limitKind: 'quota',
- exhaustedKind: 'allowance',
+ exhaustedKind: 'workspaceAllowance',
spenderType: 'workspace',
spenderId: null,
operationType: UsageOperationType.ALL,
@@ -166,7 +166,7 @@ describe('usageLimitToRestApiExceptionHandler', () => {
expect.objectContaining({
statusCode: HttpStatus.PAYMENT_REQUIRED,
error: 'QUOTA_EXHAUSTED',
- exhaustedKind: 'allowance',
+ exhaustedKind: 'workspaceAllowance',
}),
);
expect(error.getResponseHeaders()).toEqual({});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-consume-script-arguments.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-consume-script-arguments.util.ts
index 9e6da1a4ffe..adcbbc4416e 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-consume-script-arguments.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-consume-script-arguments.util.ts
@@ -1,9 +1,19 @@
import { isDefined } from 'twenty-shared/utils';
-export const buildConsumeScriptArguments = (
- entries: { amount: number; warm: { value: number; ttl: number } | null }[],
-): string[] => {
- for (const { amount, warm } of entries) {
+import { type QuotaDebit } from 'src/engine/core-modules/usage-limit/types/quota-debit.type';
+
+export const buildConsumeScriptArguments = ({
+ entries,
+ isUserCreditsFallbackEnabled = false,
+}: {
+ entries: {
+ amount: number;
+ warm: { value: number; ttl: number } | null;
+ split?: QuotaDebit['split'];
+ }[];
+ isUserCreditsFallbackEnabled?: boolean;
+}): string[] => {
+ for (const { amount, warm, split } of entries) {
if (!(Number.isSafeInteger(amount) && amount >= 0)) {
throw new Error(
`Counter amount ${amount} is not a non-negative safe integer`,
@@ -23,11 +33,27 @@ export const buildConsumeScriptArguments = (
`Counter warm value ${warm.value} with TTL ${warm.ttl} is not a non-negative safe integer with a positive safe TTL`,
);
}
+
+ if (
+ split?.kind === 'userCredits' &&
+ !(Number.isSafeInteger(split.limitValue) && split.limitValue >= 0)
+ ) {
+ throw new Error(
+ `User credits limit ${split.limitValue} is not a non-negative safe integer`,
+ );
+ }
}
return [
JSON.stringify(entries.map(({ amount }) => amount)),
JSON.stringify(entries.map(({ warm }) => warm?.value ?? false)),
JSON.stringify(entries.map(({ warm }) => warm?.ttl ?? false)),
+ JSON.stringify(entries.map(({ split }) => split?.kind ?? false)),
+ JSON.stringify(
+ entries.map(({ split }) =>
+ split?.kind === 'userCredits' ? split.limitValue : false,
+ ),
+ ),
+ String(isUserCreditsFallbackEnabled),
];
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts
index 17eb7e0e49a..281fe3c5523 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts
@@ -13,8 +13,8 @@ export const buildLimitQuotaCounter = ({
limit: Omit<FlatQuotaLimit, 'limitKind' | 'periodCount' | 'burstValue'>;
period: UsagePeriod;
}): LimitQuotaCounter => {
- const counter = {
- kind: 'limit' as const,
+ const counter: Omit<LimitQuotaCounter, 'key'> = {
+ kind: 'limit',
isDefault: false,
limitValue: limit.limitValue,
unit: limit.unit,
@@ -24,7 +24,7 @@ export const buildLimitQuotaCounter = ({
periodEnd: period.periodEnd,
spenderType: limit.spenderType,
spenderId: normalizeSpenderId(limit.spenderId),
- operationType: limit.operationType,
+ operationTypes: [limit.operationType],
};
return { ...counter, key: buildQuotaCounterKey({ workspaceId, counter }) };
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-period-group-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-period-group-key.util.ts
index 39cbeaf4ef7..e8d314f343f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-period-group-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-period-group-key.util.ts
@@ -1,4 +1,7 @@
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type UserAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type';
-export const buildPeriodGroupKey = (counter: LimitQuotaCounter): string =>
+export const buildPeriodGroupKey = (
+ counter: LimitQuotaCounter | UserAllowanceQuotaCounter,
+): string =>
`${counter.resourceType}:${counter.periodUnit}:${counter.periodStart.getTime()}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts
index 88e19f3da8c..bcfca6127dc 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts
@@ -12,7 +12,7 @@ export const buildQuotaCounterKey = ({
counter: Pick<
LimitQuotaCounter,
| 'resourceType'
- | 'operationType'
+ | 'operationTypes'
| 'spenderType'
| 'spenderId'
| 'unit'
@@ -20,4 +20,4 @@ export const buildQuotaCounterKey = ({
| 'periodStart'
>;
}): string =>
- `{${workspaceId}}:quota-consumed:${counter.resourceType}:${counter.operationType}:${counter.spenderType}:${isNonEmptyString(counter.spenderId) ? counter.spenderId : ABSENT}:${counter.unit}:${counter.periodUnit}:${counter.periodStart.getTime()}`;
+ `{${workspaceId}}:quota-consumed:${counter.resourceType}:${[...counter.operationTypes].sort().join('+')}:${counter.spenderType}:${isNonEmptyString(counter.spenderId) ? counter.spenderId : ABSENT}:${counter.unit}:${counter.periodUnit}:${counter.periodStart.getTime()}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
index 5f8de14ca98..4733586f744 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
@@ -5,21 +5,42 @@ import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/f
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
import { type QuotaLimitDefault } from 'src/engine/core-modules/usage-limit/types/quota-limit-default.type';
+import { type UserAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type';
import { buildLimitQuotaCounter } from 'src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util';
import { buildQuotaDefaultCounter } from 'src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util';
import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';
import { doesUsageLimitRowSuppressDefault } from 'src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util';
import { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';
+import { isOperationInScope } from 'src/engine/core-modules/usage-limit/utils/is-operation-in-scope.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
-const counterSpecificity = (counter: LimitQuotaCounter): number =>
+const usageScopeSpecificity = (
+ counter: Pick<LimitQuotaCounter, 'resourceType' | 'operationTypes'>,
+): number => {
+ if (counter.resourceType === UsageResourceType.ALL) {
+ return 3;
+ }
+
+ if (counter.operationTypes.includes(UsageOperationType.ALL)) {
+ return 2;
+ }
+
+ return counter.operationTypes.length > 1 ? 1 : 0;
+};
+
+const counterSpecificity = (
+ counter: Pick<
+ LimitQuotaCounter,
+ 'spenderType' | 'spenderId' | 'resourceType' | 'operationTypes'
+ >,
+): number =>
SPENDER_TYPE_SPECIFICITY[counter.spenderType] * 8 +
(isDefined(counter.spenderId) ? 0 : 4) +
- (counter.resourceType === UsageResourceType.ALL ? 2 : 0) +
- (counter.operationType === UsageOperationType.ALL ? 1 : 0);
+ usageScopeSpecificity(counter);
export const buildQuotaCounters = ({
limits,
@@ -35,7 +56,7 @@ export const buildQuotaCounters = ({
workspaceId: string;
operationType: UsageOperationType;
periodByUnit: Partial<Record<PeriodUnit, UsagePeriod>>;
-}): LimitQuotaCounter[] => {
+}): (LimitQuotaCounter | UserAllowanceQuotaCounter)[] => {
const spenders = buildSpendersFromUsageSpenders(usageSpenders);
const limitCounters = spenders.flatMap((spender) =>
@@ -57,8 +78,15 @@ export const buildQuotaCounters = ({
const defaultCounters = quotaLimitDefaults
.filter(
(quotaLimitDefault) =>
- quotaLimitDefault.operationType === operationType &&
+ isOperationInScope({
+ operationTypes: quotaLimitDefault.operationTypes,
+ operationType,
+ }) &&
spenderTypes.has(quotaLimitDefault.spenderType) &&
+ !(
+ quotaLimitDefault.unit === UsageUnit.USER_CREDIT &&
+ quotaLimitDefault.limitValue === 0
+ ) &&
!limits.some((limit) =>
doesUsageLimitRowSuppressDefault({
scope: limit,
@@ -69,9 +97,27 @@ export const buildQuotaCounters = ({
.flatMap((quotaLimitDefault) => {
const period = periodByUnit[quotaLimitDefault.periodUnit];
- return isDefined(period)
- ? [buildQuotaDefaultCounter({ workspaceId, quotaLimitDefault, period })]
- : [];
+ if (!isDefined(period)) {
+ return [];
+ }
+
+ const spenderIds = quotaLimitDefault.isPerSpender
+ ? spenders
+ .filter(
+ (spender) =>
+ spender.spenderType === quotaLimitDefault.spenderType,
+ )
+ .map((spender) => spender.spenderId)
+ : [quotaLimitDefault.spenderId];
+
+ return spenderIds.map((spenderId) =>
+ buildQuotaDefaultCounter({
+ workspaceId,
+ quotaLimitDefault,
+ spenderId,
+ period,
+ }),
+ );
});
return [...limitCounters, ...defaultCounters].sort(
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
index e61413d44b0..b729927f094 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
@@ -4,6 +4,7 @@ import {
computeQuotaConsumed,
type QuotaConsumptionScope,
} from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
+import { isWorkspaceCreditLimitCounter } from 'src/engine/core-modules/usage-limit/utils/is-workspace-credit-limit-counter.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
@@ -12,23 +13,38 @@ import { fromRecordUsageInputToUsageConsumptionRow } from 'src/engine/core-modul
import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';
const ALLOWANCE_CONSUMPTION_SCOPE: QuotaConsumptionScope = {
- operationType: UsageOperationType.ALL,
+ operationTypes: [UsageOperationType.ALL],
spenderType: 'workspace',
spenderId: null,
unit: UsageUnit.CREDIT,
};
+const findDebitSplit = (counter: QuotaCounter): QuotaDebit['split'] => {
+ if (counter.kind === 'userAllowance') {
+ return { kind: 'userCredits', limitValue: counter.limitValue };
+ }
+
+ return counter.kind === 'workspaceAllowance' ||
+ isWorkspaceCreditLimitCounter(counter)
+ ? { kind: 'workspaceCredits' }
+ : null;
+};
+
export const buildQuotaDebits = ({
counters,
events,
}: {
counters: QuotaCounter[];
events: RecordUsageInput[];
-}): QuotaDebit[] =>
- counters.flatMap((counter) => {
+}): QuotaDebit[] => {
+ const debits = counters.flatMap((counter) => {
const amount =
- counter.kind === 'limit'
+ counter.kind === 'workspaceAllowance'
? computeQuotaConsumed({
+ rows: events.map(fromRecordUsageInputToUsageConsumptionRow),
+ scope: ALLOWANCE_CONSUMPTION_SCOPE,
+ })
+ : computeQuotaConsumed({
rows: events
.filter(
(event) =>
@@ -36,14 +52,23 @@ export const buildQuotaDebits = ({
event.resourceType === counter.resourceType,
)
.map(fromRecordUsageInputToUsageConsumptionRow),
- scope: counter,
- })
- : computeQuotaConsumed({
- rows: events.map(fromRecordUsageInputToUsageConsumptionRow),
- scope: ALLOWANCE_CONSUMPTION_SCOPE,
+ scope:
+ counter.kind === 'userAllowance'
+ ? { ...counter, unit: UsageUnit.CREDIT }
+ : counter,
});
return amount > 0 && isValidCreditAmountMicro(amount)
? [{ counter, amount }]
: [];
});
+
+ const hasUserAllowanceDebit = debits.some(
+ ({ counter }) => counter.kind === 'userAllowance',
+ );
+
+ return debits.map((debit) => ({
+ ...debit,
+ split: hasUserAllowanceDebit ? findDebitSplit(debit.counter) : null,
+ }));
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util.ts
index 03089989af3..cc22ee30e64 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util.ts
@@ -1,19 +1,27 @@
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
import { type QuotaLimitDefault } from 'src/engine/core-modules/usage-limit/types/quota-limit-default.type';
import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+import { type UserAllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/user-allowance-quota-counter.type';
import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export const buildQuotaDefaultCounter = ({
workspaceId,
quotaLimitDefault,
+ spenderId,
period,
}: {
workspaceId: string;
quotaLimitDefault: QuotaLimitDefault;
+ spenderId: string;
period: UsagePeriod;
-}): LimitQuotaCounter => {
+}): LimitQuotaCounter | UserAllowanceQuotaCounter => {
const counter = {
- kind: 'limit' as const,
+ kind:
+ quotaLimitDefault.unit === UsageUnit.USER_CREDIT
+ ? ('userAllowance' as const)
+ : ('limit' as const),
isDefault: true,
limitValue: quotaLimitDefault.limitValue,
unit: quotaLimitDefault.unit,
@@ -22,8 +30,8 @@ export const buildQuotaDefaultCounter = ({
periodStart: period.periodStart,
periodEnd: period.periodEnd,
spenderType: quotaLimitDefault.spenderType,
- spenderId: null,
- operationType: quotaLimitDefault.operationType,
+ spenderId: normalizeSpenderId(spenderId),
+ operationTypes: quotaLimitDefault.operationTypes,
};
return { ...counter, key: buildQuotaCounterKey({ workspaceId, counter }) };
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts
index 0a71dc313d5..cd5a53e7b94 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts
@@ -4,6 +4,7 @@ import { type UsageQuotaDefinitionDTO } from 'src/engine/core-modules/usage-limi
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
import { type UsageLimitOperationDefinition } from 'src/engine/core-modules/usage-limit/types/usage-limit-operation-definition.type';
import { findAllowedUsageLimitUnits } from 'src/engine/core-modules/usage-limit/utils/find-allowed-usage-limit-units.util';
+import { findSingleOperationType } from 'src/engine/core-modules/usage-limit/utils/find-single-operation-type.util';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
@@ -44,14 +45,21 @@ export const buildQuotaDefinitions = (): UsageQuotaDefinitionDTO[] =>
definition,
}),
allowedSpenderTypes: definition.allowedSpenderTypes,
- operatorOnlyScopes: definition.defaults
- .filter(({ isOverridable }) => isOverridable)
- .map(({ operationType, spenderType, unit, periodUnit }) => ({
- operationType,
+ operatorOnlyScopes: definition.defaults.flatMap(
+ ({
+ operationTypes,
+ isOverridable,
spenderType,
unit,
periodUnit,
- })),
+ }) => {
+ const operationType = findSingleOperationType(operationTypes);
+
+ return isOverridable && isDefined(operationType)
+ ? [{ operationType, spenderType, unit, periodUnit }]
+ : [];
+ },
+ ),
},
]
: [];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util.ts
index 154ac4f2963..b2c29b93bf3 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util.ts
@@ -9,7 +9,7 @@ import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/e
export const buildQuotaExhaustedException = (
exhaustedScope: ExhaustedScope,
): UsageLimitException => {
- if (exhaustedScope.exhaustedKind === 'allowance') {
+ if (exhaustedScope.exhaustedKind === 'workspaceAllowance') {
return new UsageLimitException(
'Credit allowance exhausted for this billing period',
UsageLimitExceptionCode.QUOTA_EXHAUSTED,
@@ -20,6 +20,17 @@ export const buildQuotaExhaustedException = (
);
}
+ if (exhaustedScope.exhaustedKind === 'userAllowance') {
+ return new UsageLimitException(
+ 'User credits allowance exhausted for this period',
+ UsageLimitExceptionCode.QUOTA_EXHAUSTED,
+ {
+ userFriendlyMessage: msg`Your AI credits for this period are used up.`,
+ exhaustedScope,
+ },
+ );
+ }
+
return new UsageLimitException(
`Usage limit reached for ${exhaustedScope.spenderType}`,
UsageLimitExceptionCode.QUOTA_EXHAUSTED,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
index 297e0f21ae7..2cb215193e7 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
@@ -1,47 +1,51 @@
import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
+import { findSingleOperationType } from 'src/engine/core-modules/usage-limit/utils/find-single-operation-type.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
export const buildQuotaExhaustedScope = ({
resourceType,
+ operationType,
counter,
}: {
resourceType: UsageResourceType;
+ operationType: UsageOperationType;
counter: QuotaCounter;
}): ExhaustedScope => {
const retryAfterMs = Math.max(counter.periodEnd.getTime() - Date.now(), 0);
- if (counter.kind === 'limit') {
+ if (counter.kind === 'workspaceAllowance') {
return {
- resourceType: counter.resourceType,
+ resourceType,
limitKind: 'quota',
- exhaustedKind: 'limit',
- spenderType: counter.spenderType,
- spenderId: counter.spenderId,
- operationType: counter.operationType,
+ exhaustedKind: 'workspaceAllowance',
+ spenderType: 'workspace',
+ spenderId: null,
+ operationType: UsageOperationType.ALL,
unit: counter.unit,
limitValue: counter.limitValue,
remaining: 0,
- periodCount: 1,
- periodUnit: counter.periodUnit,
+ periodCount: null,
+ periodUnit: null,
retryAfterMs,
- isDefault: counter.isDefault,
};
}
return {
- resourceType,
+ resourceType: counter.resourceType,
limitKind: 'quota',
- exhaustedKind: 'allowance',
- spenderType: 'workspace',
- spenderId: null,
- operationType: UsageOperationType.ALL,
+ exhaustedKind: counter.kind,
+ spenderType: counter.spenderType,
+ spenderId: counter.spenderId,
+ operationType:
+ findSingleOperationType(counter.operationTypes) ?? operationType,
unit: counter.unit,
limitValue: counter.limitValue,
remaining: 0,
- periodCount: null,
- periodUnit: null,
+ periodCount: 1,
+ periodUnit: counter.periodUnit,
retryAfterMs,
+ isDefault: counter.isDefault,
};
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-release-script-arguments.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-release-script-arguments.util.ts
index 1ce271c8ab0..0585f77bfdf 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-release-script-arguments.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-release-script-arguments.util.ts
@@ -1,9 +1,9 @@
import { buildConsumeScriptArguments } from 'src/engine/core-modules/usage-limit/utils/build-consume-script-arguments.util';
export const buildReleaseScriptArguments = (amounts: number[]): string[] => {
- const [, warmValues, warmTtls] = buildConsumeScriptArguments(
- amounts.map((amount) => ({ amount, warm: null })),
- );
+ const [, warmValues, warmTtls] = buildConsumeScriptArguments({
+ entries: amounts.map((amount) => ({ amount, warm: null })),
+ });
return [
JSON.stringify(amounts.map((amount) => -amount)),
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-default-scopes.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-default-scopes.util.ts
index 8c47ea8d090..f3a19a95066 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-default-scopes.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-default-scopes.util.ts
@@ -4,7 +4,9 @@ import { type ConfigVariables } from 'src/engine/core-modules/twenty-config/conf
import { type OptionalNumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/optional-numeric-config-variable-key.type';
import { type UsageLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/usage-limit-default-definition.type';
import { type UsageLimitScope } from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';
+import { findSingleOperationType } from 'src/engine/core-modules/usage-limit/utils/find-single-operation-type.util';
import { findUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-defaults.util';
+import { getUsageLimitDefaultOperationTypes } from 'src/engine/core-modules/usage-limit/utils/get-usage-limit-default-operation-types.util';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
export type UsageLimitDefaultScope = UsageLimitScope & {
@@ -37,12 +39,15 @@ export const buildUsageLimitDefaultScopes = ({
const limitValue = getConfigValue(
usageLimitDefault.limitValueConfigVariable,
);
+ const operationType = findSingleOperationType(
+ getUsageLimitDefaultOperationTypes(usageLimitDefault),
+ );
- return isDefined(limitValue)
+ return isDefined(limitValue) && isDefined(operationType)
? [
{
resourceType: usageLimitDefault.resourceType,
- operationType: usageLimitDefault.operationType,
+ operationType,
spenderType: usageLimitDefault.spenderType,
spenderId: usageLimitDefault.spenderId,
limitKind: usageLimitDefault.limitKind,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-workspace-allowance-counter-key.util.ts
similarity index 76%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util.ts
rename to packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-workspace-allowance-counter-key.util.ts
index 80c27c4dc43..04f21d62978 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-workspace-allowance-counter-key.util.ts
@@ -1,4 +1,4 @@
-export const buildAllowanceCounterKey = ({
+export const buildWorkspaceAllowanceCounterKey = ({
workspaceId,
periodStart,
}: {
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts
index 4150e4fca71..49ab6e8cb52 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts
@@ -1,11 +1,11 @@
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
-import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { USAGE_SPENDER_COLUMN_BY_SPENDER_TYPE } from 'src/engine/core-modules/usage-limit/constants/usage-spender-column-by-spender-type.constant';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { computeRowConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-row-consumed.util';
+import { isOperationInScope } from 'src/engine/core-modules/usage-limit/utils/is-operation-in-scope.util';
import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
const spenderColumnMatches = (
@@ -16,7 +16,7 @@ const spenderColumnMatches = (
export type QuotaConsumptionScope = Pick<
LimitQuotaCounter,
- 'operationType' | 'spenderType' | 'spenderId' | 'unit'
+ 'operationTypes' | 'spenderType' | 'spenderId' | 'unit'
>;
const rowMatchesScope = (
@@ -24,8 +24,10 @@ const rowMatchesScope = (
scope: QuotaConsumptionScope,
): boolean => {
if (
- scope.operationType !== UsageOperationType.ALL &&
- row.operationType !== scope.operationType
+ !isOperationInScope({
+ operationTypes: scope.operationTypes,
+ operationType: row.operationType,
+ })
) {
return false;
}
@@ -40,17 +42,6 @@ const rowMatchesScope = (
);
};
-const computeRowConsumed = (
- row: UsageConsumptionRow,
- unit: UsageUnit,
-): number => {
- if (unit === UsageUnit.CREDIT) {
- return Number(row.creditsUsedMicro);
- }
-
- return row.unit === unit ? Number(row.quantity) : 0;
-};
-
export const computeQuotaConsumed = ({
rows,
scope,
@@ -60,4 +51,4 @@ export const computeQuotaConsumed = ({
}): number =>
rows
.filter((row) => rowMatchesScope(row, scope))
- .reduce((total, row) => total + computeRowConsumed(row, scope.unit), 0);
+ .reduce((total, row) => total + computeRowConsumed({ row, scope }), 0);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-row-consumed.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-row-consumed.util.ts
new file mode 100644
index 00000000000..b5dfd26b9dd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-row-consumed.util.ts
@@ -0,0 +1,33 @@
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { isWorkspaceCreditLimitCounter } from 'src/engine/core-modules/usage-limit/utils/is-workspace-credit-limit-counter.util';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
+
+export const computeRowConsumed = ({
+ row,
+ scope,
+}: {
+ row: Pick<
+ UsageConsumptionRow,
+ | 'unit'
+ | 'creditsUsedMicro'
+ | 'userCreditsUsedMicro'
+ | 'workspaceCreditsUsedMicro'
+ | 'quantity'
+ >;
+ scope: Pick<LimitQuotaCounter, 'spenderType' | 'unit'>;
+}): number => {
+ if (scope.unit === UsageUnit.USER_CREDIT) {
+ return Number(row.userCreditsUsedMicro);
+ }
+
+ if (isWorkspaceCreditLimitCounter(scope)) {
+ return Number(row.workspaceCreditsUsedMicro);
+ }
+
+ if (scope.unit === UsageUnit.CREDIT) {
+ return Number(row.creditsUsedMicro);
+ }
+
+ return row.unit === scope.unit ? Number(row.quantity) : 0;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts
index 386ed5701bd..da2373a5a76 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts
@@ -1,4 +1,6 @@
import { type UsageLimitScope } from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';
+import { findSingleOperationType } from 'src/engine/core-modules/usage-limit/utils/find-single-operation-type.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
type SuppressibleScope = Omit<UsageLimitScope, 'periodCount'>;
@@ -7,11 +9,15 @@ export const doesUsageLimitRowSuppressDefault = ({
usageLimitDefault,
}: {
scope: SuppressibleScope;
- usageLimitDefault: SuppressibleScope & { isOverridable: boolean };
+ usageLimitDefault: Omit<SuppressibleScope, 'operationType'> & {
+ operationTypes: UsageOperationType[];
+ isOverridable: boolean;
+ };
}): boolean =>
usageLimitDefault.isOverridable &&
scope.resourceType === usageLimitDefault.resourceType &&
- scope.operationType === usageLimitDefault.operationType &&
+ scope.operationType ===
+ findSingleOperationType(usageLimitDefault.operationTypes) &&
scope.spenderType === usageLimitDefault.spenderType &&
scope.spenderId === usageLimitDefault.spenderId &&
scope.limitKind === usageLimitDefault.limitKind &&
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-blocking-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-blocking-counters.util.ts
new file mode 100644
index 00000000000..bd20d89640b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-blocking-counters.util.ts
@@ -0,0 +1,53 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
+import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
+import { isWorkspaceCreditLimitCounter } from 'src/engine/core-modules/usage-limit/utils/is-workspace-credit-limit-counter.util';
+
+const PRIORITY_BY_KIND: Record<QuotaCounter['kind'], number> = {
+ workspaceAllowance: 0,
+ userAllowance: 1,
+ limit: 2,
+};
+
+export const findBlockingCounters = ({
+ counters,
+ consumedValues,
+ exhaustedCounters,
+ userCreditsFallback,
+}: {
+ counters: QuotaCounter[];
+ consumedValues: (number | null)[];
+ exhaustedCounters: QuotaCounter[];
+ userCreditsFallback: UserCreditsFallback;
+}): QuotaCounter[] => {
+ const isStopMode = userCreditsFallback === UserCreditsFallback.STOP;
+ const userAllowanceIndexes = counters.flatMap((counter, index) =>
+ counter.kind === 'userAllowance' ? [index] : [],
+ );
+
+ const isSpendingUserCredits =
+ userAllowanceIndexes.length > 0 &&
+ userAllowanceIndexes.every((index) => isDefined(consumedValues[index])) &&
+ (isStopMode ||
+ !exhaustedCounters.some((counter) => counter.kind === 'userAllowance'));
+
+ return exhaustedCounters
+ .filter((counter) => {
+ if (counter.kind === 'userAllowance') {
+ return isStopMode;
+ }
+
+ return counter.kind === 'workspaceAllowance' ||
+ isWorkspaceCreditLimitCounter(counter)
+ ? !isSpendingUserCredits
+ : true;
+ })
+ .sort(
+ (first, second) =>
+ PRIORITY_BY_KIND[first.kind] - PRIORITY_BY_KIND[second.kind] ||
+ (first.kind === 'userAllowance'
+ ? second.periodEnd.getTime() - first.periodEnd.getTime()
+ : 0),
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-single-operation-type.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-single-operation-type.util.ts
new file mode 100644
index 00000000000..b537e2ceda1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-single-operation-type.util.ts
@@ -0,0 +1,6 @@
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+export const findSingleOperationType = (
+ operationTypes: UsageOperationType[],
+): UsageOperationType | null =>
+ operationTypes.length === 1 ? operationTypes[0] : null;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util.ts
index dd44091f004..aa95544c525 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util.ts
@@ -2,11 +2,18 @@ import { type UsageLimitDefaultDefinition } from 'src/engine/core-modules/usage-
import { type UsageLimitScope } from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';
import { doesUsageLimitRowSuppressDefault } from 'src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util';
import { findUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-defaults.util';
+import { getUsageLimitDefaultOperationTypes } from 'src/engine/core-modules/usage-limit/utils/get-usage-limit-default-operation-types.util';
export const findSuppressedUsageLimitDefaults = (
scope: UsageLimitScope,
): UsageLimitDefaultDefinition[] =>
findUsageLimitDefaults({ resourceType: scope.resourceType }).filter(
(usageLimitDefault) =>
- doesUsageLimitRowSuppressDefault({ scope, usageLimitDefault }),
+ doesUsageLimitRowSuppressDefault({
+ scope,
+ usageLimitDefault: {
+ ...usageLimitDefault,
+ operationTypes: getUsageLimitDefaultOperationTypes(usageLimitDefault),
+ },
+ }),
);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-unmetered-user-credits-share.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-unmetered-user-credits-share.util.ts
new file mode 100644
index 00000000000..eff82c5b25c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-unmetered-user-credits-share.util.ts
@@ -0,0 +1,15 @@
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import { type QuotaDebit } from 'src/engine/core-modules/usage-limit/types/quota-debit.type';
+
+export const findUnmeteredUserCreditsShare = (
+ debits: Pick<QuotaDebit, 'amount' | 'split'>[],
+): number => {
+ const userCreditsAmounts = debits.flatMap(({ amount, split }) =>
+ split?.kind === 'userCredits' ? [amount] : [],
+ );
+
+ return isNonEmptyArray(userCreditsAmounts)
+ ? Math.min(...userCreditsAmounts)
+ : 0;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-default-operation-types.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-default-operation-types.util.ts
new file mode 100644
index 00000000000..b2a5e3bd5df
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-usage-limit-default-operation-types.util.ts
@@ -0,0 +1,18 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { type UsageLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/usage-limit-default-definition.type';
+import { type QuotaOperationTypes } from 'src/engine/core-modules/usage-limit/types/quota-operation-types.type';
+
+export const getUsageLimitDefaultOperationTypes = (
+ usageLimitDefault: UsageLimitDefaultDefinition,
+): QuotaOperationTypes => {
+ switch (usageLimitDefault.limitKind) {
+ case 'quota':
+ return usageLimitDefault.operationTypes;
+ case 'speed':
+ case 'stock':
+ return [usageLimitDefault.operationType];
+ default:
+ return assertUnreachable(usageLimitDefault);
+ }
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-operation-in-scope.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-operation-in-scope.util.ts
new file mode 100644
index 00000000000..aa184dc7a8a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-operation-in-scope.util.ts
@@ -0,0 +1,14 @@
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+export const isOperationInScope = ({
+ operationTypes,
+ operationType,
+}: {
+ operationTypes: UsageOperationType[];
+ operationType: string;
+}): boolean =>
+ operationTypes.some(
+ (scopeOperationType) =>
+ scopeOperationType === UsageOperationType.ALL ||
+ scopeOperationType === operationType,
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-workspace-credit-limit-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-workspace-credit-limit-counter.util.ts
new file mode 100644
index 00000000000..fece78d0f7c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-workspace-credit-limit-counter.util.ts
@@ -0,0 +1,7 @@
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
+export const isWorkspaceCreditLimitCounter = (
+ counter: Pick<LimitQuotaCounter, 'spenderType' | 'unit'>,
+): boolean =>
+ counter.spenderType === 'workspace' && counter.unit === UsageUnit.CREDIT;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/split-user-credits-across-events.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/split-user-credits-across-events.util.ts
new file mode 100644
index 00000000000..07c1748bd6d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/split-user-credits-across-events.util.ts
@@ -0,0 +1,23 @@
+import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
+import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';
+
+export const splitUserCreditsAcrossEvents = ({
+ events,
+ userCreditsUsedMicro,
+}: {
+ events: RecordUsageInput[];
+ userCreditsUsedMicro: number;
+}): RecordUsageInput[] => {
+ let remainingMicro = userCreditsUsedMicro;
+
+ return events.map((event) => {
+ const creditsUsedMicro = event.creditsUsedMicro ?? 0;
+ const eventUserCreditsUsedMicro = isValidCreditAmountMicro(creditsUsedMicro)
+ ? Math.min(remainingMicro, creditsUsedMicro)
+ : 0;
+
+ remainingMicro -= eventUserCreditsUsedMicro;
+
+ return { ...event, userCreditsUsedMicro: eventUserCreditsUsedMicro };
+ });
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts
index e2b9c726ead..867f419dca9 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts
@@ -11,7 +11,7 @@ import { getUsageLimitErrorCode } from 'src/engine/core-modules/usage-limit/util
const getStatusCode = (
exhaustedScope: UsageLimitException['exhaustedScope'],
): HttpStatus => {
- if (exhaustedScope?.exhaustedKind === 'allowance') {
+ if (exhaustedScope?.exhaustedKind === 'workspaceAllowance') {
return HttpStatus.PAYMENT_REQUIRED;
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-breakdown-item.dto.ts b/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-breakdown-item.dto.ts
index 6462d0f9da1..8eb04f993ca 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-breakdown-item.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-breakdown-item.dto.ts
@@ -12,4 +12,10 @@ export class UsageBreakdownItemDTO {
@Field(() => Float)
creditsUsed: number;
+
+ @Field(() => Float)
+ userCreditsUsed: number;
+
+ @Field(() => Float)
+ workspaceCreditsUsed: number;
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-time-series.dto.ts b/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-time-series.dto.ts
index 5ef4f3ac842..20a7b751713 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-time-series.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-time-series.dto.ts
@@ -9,4 +9,7 @@ export class UsageTimeSeriesDTO {
@Field(() => Float)
creditsUsed: number;
+
+ @Field(() => Float)
+ workspaceCreditsUsed: number;
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
index 6a8a8f8a53b..208a6c3dc78 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
@@ -9,6 +9,7 @@ export enum UsageOperationType {
WORKFLOW_EXECUTION = 'WORKFLOW_EXECUTION',
CODE_EXECUTION = 'CODE_EXECUTION',
WEB_SEARCH = 'WEB_SEARCH',
+ AI_WORKFLOW_WEB_SEARCH = 'AI_WORKFLOW_WEB_SEARCH',
CALL_RECORDING = 'CALL_RECORDING',
EMAIL_SEND = 'EMAIL_SEND',
MESSAGE_CAMPAIGN_SEND = 'MESSAGE_CAMPAIGN_SEND',
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
index 3da4f96ab49..ba8f1ef2bd0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
@@ -4,6 +4,7 @@ import { registerEnumType } from '@nestjs/graphql';
export enum UsageUnit {
CREDIT = 'CREDIT',
+ USER_CREDIT = 'USER_CREDIT',
TOKEN = 'TOKEN',
INVOCATION = 'INVOCATION',
MINUTE = 'MINUTE',
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
index 90d110c3a79..29236ef8323 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
@@ -15,6 +15,7 @@ import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.e
import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
import { type UsageConsumptionTotals } from 'src/engine/core-modules/usage/types/usage-consumption-totals.type';
import { type UsagePeriodAnchor } from 'src/engine/core-modules/usage/types/usage-period-anchor.type';
+import { type CreditsUsed } from 'src/engine/core-modules/usage/types/credits-used.type';
import { buildRecurringChargeKey } from 'src/engine/core-modules/usage/utils/build-recurring-charge-key.util';
import { buildUsagePeriodClause } from 'src/engine/core-modules/usage/utils/build-usage-period-clause.util';
import { buildUsageResourceTypeFilter } from 'src/engine/core-modules/usage/utils/build-usage-resource-type-filter.util';
@@ -23,30 +24,52 @@ import { fillUsageTimeSeriesGaps } from 'src/engine/core-modules/usage/utils/fil
import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { toDollars } from 'src/engine/core-modules/usage/utils/to-dollars.util';
-export type UsageBreakdownItem = {
+type CreditsUsedAmounts = {
+ creditsUsed: number;
+ userCreditsUsed: number;
+ workspaceCreditsUsed: number;
+};
+
+export type UsageBreakdownItem = CreditsUsedAmounts & {
key: string;
label?: string;
- creditsUsed: number;
};
-export type UsageApplicationBreakdownItem = {
+export type UsageApplicationBreakdownItem = CreditsUsedAmounts & {
applicationId: string;
operation: string;
- creditsUsed: number;
};
export type UsageTimeSeriesPoint = {
date: string;
creditsUsed: number;
+ workspaceCreditsUsed: number;
};
-type BreakdownRowMicro<TColumn extends string> = Record<TColumn, string> & {
- creditsUsedMicro: number;
+type CreditsUsedRowMicro = {
+ creditsUsedMicro: string | number;
+ userCreditsUsedMicro: string | number;
+ workspaceCreditsUsedMicro: string | number;
};
-type TimeSeriesRowMicro = {
+type BreakdownRowMicro<TColumn extends string> = Record<TColumn, string> &
+ CreditsUsedRowMicro;
+
+// ClickHouse binds creditsUsedMicro and userCreditsUsedMicro to these sum aliases anywhere in the query, so sum() over them nests an aggregate and fails
+const CREDITS_USED_SELECT = `sum(creditsUsedMicro) AS creditsUsedMicro,
+ sum(userCreditsUsedMicro) AS userCreditsUsedMicro,
+ creditsUsedMicro - userCreditsUsedMicro AS workspaceCreditsUsedMicro`;
+
+const toCreditsUsedAmounts = (
+ row: CreditsUsedRowMicro,
+): CreditsUsedAmounts => ({
+ creditsUsed: Number(row.creditsUsedMicro),
+ userCreditsUsed: Number(row.userCreditsUsedMicro),
+ workspaceCreditsUsed: Number(row.workspaceCreditsUsedMicro),
+});
+
+type TimeSeriesRowMicro = CreditsUsedRowMicro & {
date: string;
- creditsUsedMicro: number;
};
type PeriodParams = {
@@ -95,7 +118,7 @@ export class UsageAnalyticsService {
return this.clickHouseService.selectOrThrow<UsageConsumptionRow>(
`SELECT operationType, unit, userWorkspaceId, apiKeyId, applicationId,
agentId, workflowId, logicFunctionId,
- sum(creditsUsedMicro) AS creditsUsedMicro,
+ ${CREDITS_USED_SELECT},
sum(quantity) AS quantity
FROM usageEvent
WHERE workspaceId = {workspaceId:String}
@@ -143,7 +166,7 @@ export class UsageAnalyticsService {
const rows =
await this.clickHouseService.selectOrThrow<UsageConsumptionTotals>(
- `SELECT sum(creditsUsedMicro) AS creditsUsedMicro,
+ `SELECT ${CREDITS_USED_SELECT},
sum(quantity) AS quantity
FROM usageEvent
WHERE workspaceId = {workspaceId:String}
@@ -161,6 +184,8 @@ export class UsageAnalyticsService {
return {
creditsUsedMicro: rows[0]?.creditsUsedMicro ?? 0,
+ userCreditsUsedMicro: rows[0]?.userCreditsUsedMicro ?? 0,
+ workspaceCreditsUsedMicro: rows[0]?.workspaceCreditsUsedMicro ?? 0,
quantity: rows[0]?.quantity ?? 0,
};
}
@@ -171,20 +196,24 @@ export class UsageAnalyticsService {
}: {
workspaceId: string;
periodStart: Date;
- }): Promise<number> {
+ }): Promise<CreditsUsed> {
// The grouping only exists to match the billing_by_workspace_period projection; it still returns one row.
- const rows = await this.clickHouseService.selectOrThrow<{
- total: string | number | null;
- }>(
- `SELECT sum(creditsUsedMicro) AS total
- FROM usageEvent
- WHERE workspaceId = {workspaceId:String}
- AND periodStart = {periodStart:DateTime64(3)}
- GROUP BY workspaceId, periodStart`,
- { workspaceId, periodStart: formatDateTimeForClickHouse(periodStart) },
- );
+ const rows =
+ await this.clickHouseService.selectOrThrow<CreditsUsedRowMicro>(
+ `SELECT ${CREDITS_USED_SELECT}
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND periodStart = {periodStart:DateTime64(3)}
+ GROUP BY workspaceId, periodStart`,
+ { workspaceId, periodStart: formatDateTimeForClickHouse(periodStart) },
+ );
- return Number(rows[0]?.total ?? 0);
+ return {
+ workspaceCreditsUsedMicro: Number(
+ rows[0]?.workspaceCreditsUsedMicro ?? 0,
+ ),
+ userCreditsUsedMicro: Number(rows[0]?.userCreditsUsedMicro ?? 0),
+ };
}
async getAdminAiUsageByWorkspace(params: {
@@ -199,7 +228,7 @@ export class UsageAnalyticsService {
const query = `
SELECT
workspaceId AS key,
- sum(creditsUsedMicro) AS creditsUsedMicro
+ ${CREDITS_USED_SELECT}
FROM usageEvent
WHERE timestamp >= {periodStart:String}
AND timestamp < {periodEnd:String}
@@ -220,7 +249,9 @@ export class UsageAnalyticsService {
return rows.map((row) => ({
key: row.key,
- creditsUsed: convert(row.creditsUsedMicro),
+ creditsUsed: convert(Number(row.creditsUsedMicro)),
+ userCreditsUsed: convert(Number(row.userCreditsUsedMicro)),
+ workspaceCreditsUsed: convert(Number(row.workspaceCreditsUsedMicro)),
}));
}
@@ -291,7 +322,7 @@ export class UsageAnalyticsService {
resourceContext,
''
) AS operation,
- sum(creditsUsedMicro) AS creditsUsedMicro
+ ${CREDITS_USED_SELECT}
FROM usageEvent
WHERE workspaceId = {workspaceId:String}
AND timestamp >= {periodStart:String}
@@ -301,7 +332,7 @@ export class UsageAnalyticsService {
${hasOperationTypes ? 'AND operationType IN ({operationTypes:Array(String)})' : ''}
${isNonEmptyString(userWorkspaceId) ? 'AND userWorkspaceId = {userWorkspaceId:String}' : ''}
GROUP BY resourceId, operation
- ORDER BY creditsUsedMicro DESC
+ ORDER BY workspaceCreditsUsedMicro DESC
LIMIT ${BREAKDOWN_QUERY_LIMIT}
`;
@@ -321,7 +352,7 @@ export class UsageAnalyticsService {
return rows.map((row) => ({
applicationId: row.resourceId,
operation: row.operation,
- creditsUsed: row.creditsUsedMicro,
+ ...toCreditsUsedAmounts(row),
}));
}
@@ -407,7 +438,7 @@ export class UsageAnalyticsService {
const query = `
SELECT
${groupByField} AS key,
- sum(creditsUsedMicro) AS creditsUsedMicro
+ ${CREDITS_USED_SELECT}
FROM usageEvent
WHERE workspaceId = {workspaceId:String}
AND timestamp >= {periodStart:String}
@@ -415,7 +446,7 @@ export class UsageAnalyticsService {
${opTypeFilter}
${extraWhere}
GROUP BY ${groupByField}
- ORDER BY creditsUsedMicro DESC
+ ORDER BY workspaceCreditsUsedMicro DESC
LIMIT ${BREAKDOWN_QUERY_LIMIT}
`;
@@ -434,7 +465,7 @@ export class UsageAnalyticsService {
return rows.map((row) => ({
key: row.key,
- creditsUsed: row.creditsUsedMicro,
+ ...toCreditsUsedAmounts(row),
}));
}
@@ -457,7 +488,7 @@ export class UsageAnalyticsService {
const query = `
SELECT
formatDateTime(timestamp, '%Y-%m-%d') AS date,
- sum(creditsUsedMicro) AS creditsUsedMicro
+ ${CREDITS_USED_SELECT}
FROM usageEvent
WHERE workspaceId = {workspaceId:String}
AND timestamp >= {periodStart:String}
@@ -483,7 +514,8 @@ export class UsageAnalyticsService {
const points = rows.map((row) => ({
date: row.date,
- creditsUsed: row.creditsUsedMicro,
+ creditsUsed: Number(row.creditsUsedMicro),
+ workspaceCreditsUsed: Number(row.workspaceCreditsUsedMicro),
}));
return fillUsageTimeSeriesGaps({
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
index ecc9d0efa35..43397fdb0b6 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
@@ -159,7 +159,7 @@ export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {
`Refusing to record ${creditsUsedMicro} creditsUsedMicro on a ${input.operationType} usage event; recording 0 instead`,
);
- return { ...input, creditsUsedMicro: 0 };
+ return { ...input, creditsUsedMicro: 0, userCreditsUsedMicro: 0 };
}
return { ...input, creditsUsedMicro };
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/credits-used.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/credits-used.type.ts
new file mode 100644
index 00000000000..db60919c062
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/credits-used.type.ts
@@ -0,0 +1,4 @@
+export type CreditsUsed = {
+ workspaceCreditsUsedMicro: number;
+ userCreditsUsedMicro: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-row.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-row.type.ts
index 917bdcce496..300ef346587 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-row.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-row.type.ts
@@ -8,5 +8,7 @@ export type UsageConsumptionRow = {
workflowId: string;
logicFunctionId: string;
creditsUsedMicro: string | number;
+ userCreditsUsedMicro: string | number;
+ workspaceCreditsUsedMicro: string | number;
quantity: string | number;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-totals.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-totals.type.ts
index 9545c146e0e..27df1b8c3fc 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-totals.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-totals.type.ts
@@ -2,5 +2,8 @@ import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/us
export type UsageConsumptionTotals = Pick<
UsageConsumptionRow,
- 'creditsUsedMicro' | 'quantity'
+ | 'creditsUsedMicro'
+ | 'userCreditsUsedMicro'
+ | 'workspaceCreditsUsedMicro'
+ | 'quantity'
>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/usage-event.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/usage-event.type.ts
index cd5b72de8d6..45c9c21dc41 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/types/usage-event.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/usage-event.type.ts
@@ -9,6 +9,7 @@ export type UsageEvent = {
resourceType: UsageResourceType;
operationType: UsageOperationType;
creditsUsedMicro: number;
+ userCreditsUsedMicro?: number;
quantity: number;
unit: UsageUnit;
periodStart?: Date;
diff --git a/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts b/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
index fd40b44b758..828368dc8ca 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
@@ -18,6 +18,7 @@ import {
type UsageBreakdownItem,
} from 'src/engine/core-modules/usage/services/usage-analytics.service';
import { consolidateUsageByApplication } from 'src/engine/core-modules/usage/utils/consolidate-usage-by-application.util';
+import { fromUsageBreakdownItemToUsageBreakdownItemDTO } from 'src/engine/core-modules/usage/utils/from-usage-breakdown-item-to-usage-breakdown-item-dto.util';
import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -121,25 +122,22 @@ export class UsageResolver {
});
const result: UsageAnalyticsDTO = {
- usageByUser: resolvedUsageByUser.map((item) => ({
- ...item,
- creditsUsed: toDisplayCredits(item.creditsUsed),
- })),
- usageByOperationType: usageByOperationType.map((item) => ({
- ...item,
- creditsUsed: toDisplayCredits(item.creditsUsed),
- })),
- usageByApplication: resolvedUsageByApplication.map((item) => ({
- ...item,
- creditsUsed: toDisplayCredits(item.creditsUsed),
- })),
- usageByModel: usageByModel.map((item) => ({
- ...item,
- creditsUsed: toDisplayCredits(item.creditsUsed),
- })),
+ usageByUser: resolvedUsageByUser.map(
+ fromUsageBreakdownItemToUsageBreakdownItemDTO,
+ ),
+ usageByOperationType: usageByOperationType.map(
+ fromUsageBreakdownItemToUsageBreakdownItemDTO,
+ ),
+ usageByApplication: resolvedUsageByApplication.map(
+ fromUsageBreakdownItemToUsageBreakdownItemDTO,
+ ),
+ usageByModel: usageByModel.map(
+ fromUsageBreakdownItemToUsageBreakdownItemDTO,
+ ),
timeSeries: timeSeries.map((point) => ({
...point,
creditsUsed: toDisplayCredits(point.creditsUsed),
+ workspaceCreditsUsed: toDisplayCredits(point.workspaceCreditsUsed),
})),
periodStart,
periodEnd,
@@ -163,6 +161,7 @@ export class UsageResolver {
dailyUsage: dailyUsage.map((point) => ({
...point,
creditsUsed: toDisplayCredits(point.creditsUsed),
+ workspaceCreditsUsed: toDisplayCredits(point.workspaceCreditsUsed),
})),
};
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/consolidate-usage-by-application.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/consolidate-usage-by-application.util.spec.ts
index 74772f95689..11860e21ae6 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/consolidate-usage-by-application.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/consolidate-usage-by-application.util.spec.ts
@@ -22,11 +22,15 @@ describe('consolidateUsageByApplication', () => {
applicationId: 'app-1',
operation: 'recordMeeting',
creditsUsed: 500,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 500,
},
{
applicationId: 'app-1',
operation: 'summarizeMeeting',
creditsUsed: 300,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 300,
},
],
flatApplicationMaps: buildFlatApplicationMaps([
@@ -54,11 +58,15 @@ describe('consolidateUsageByApplication', () => {
key: 'Call Recorder · Meeting recording',
label: 'Call Recorder · Meeting recording',
creditsUsed: 500,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 500,
},
{
key: 'Call Recorder · Meeting summary',
label: 'Call Recorder · Meeting summary',
creditsUsed: 300,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 300,
},
]);
});
@@ -66,8 +74,20 @@ describe('consolidateUsageByApplication', () => {
it('should give each declared recurring charge its own slice', () => {
const result = consolidateUsageByApplication({
items: [
- { applicationId: 'app-1', operation: 'seat', creditsUsed: 50 },
- { applicationId: 'app-1', operation: 'platformFee', creditsUsed: 20 },
+ {
+ applicationId: 'app-1',
+ operation: 'seat',
+ creditsUsed: 50,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 50,
+ },
+ {
+ applicationId: 'app-1',
+ operation: 'platformFee',
+ creditsUsed: 20,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 20,
+ },
],
flatApplicationMaps: buildFlatApplicationMaps([
{
@@ -97,11 +117,15 @@ describe('consolidateUsageByApplication', () => {
key: 'Call Recorder · Per member',
label: 'Call Recorder · Per member',
creditsUsed: 50,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 50,
},
{
key: 'Call Recorder · Platform fee',
label: 'Call Recorder · Platform fee',
creditsUsed: 20,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 20,
},
]);
});
@@ -109,9 +133,27 @@ describe('consolidateUsageByApplication', () => {
it('should fold undeclared operations into a single app-level slice', () => {
const result = consolidateUsageByApplication({
items: [
- { applicationId: 'app-1', operation: 'pdl/person', creditsUsed: 100 },
- { applicationId: 'app-1', operation: 'pdl/company', creditsUsed: 70 },
- { applicationId: 'app-1', operation: '', creditsUsed: 40 },
+ {
+ applicationId: 'app-1',
+ operation: 'pdl/person',
+ creditsUsed: 100,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 100,
+ },
+ {
+ applicationId: 'app-1',
+ operation: 'pdl/company',
+ creditsUsed: 70,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 70,
+ },
+ {
+ applicationId: 'app-1',
+ operation: '',
+ creditsUsed: 40,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 40,
+ },
],
flatApplicationMaps: buildFlatApplicationMaps([
{ id: 'app-1', name: 'People Data Labs', billing: {} },
@@ -123,13 +165,23 @@ describe('consolidateUsageByApplication', () => {
key: 'People Data Labs',
label: 'People Data Labs',
creditsUsed: 210,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 210,
},
]);
});
it('should keep an uninstalled application in the breakdown under its name', () => {
const result = consolidateUsageByApplication({
- items: [{ applicationId: 'app-1', operation: '', creditsUsed: 120 }],
+ items: [
+ {
+ applicationId: 'app-1',
+ operation: '',
+ creditsUsed: 120,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 120,
+ },
+ ],
flatApplicationMaps: buildFlatApplicationMaps([
{
id: 'app-1',
@@ -141,26 +193,58 @@ describe('consolidateUsageByApplication', () => {
});
expect(result).toEqual([
- { key: 'Retired App', label: 'Retired App', creditsUsed: 120 },
+ {
+ key: 'Retired App',
+ label: 'Retired App',
+ creditsUsed: 120,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 120,
+ },
]);
});
it('should fall back to the application id when the application is unknown', () => {
const result = consolidateUsageByApplication({
- items: [{ applicationId: 'app-gone', operation: '', creditsUsed: 90 }],
+ items: [
+ {
+ applicationId: 'app-gone',
+ operation: '',
+ creditsUsed: 90,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 90,
+ },
+ ],
flatApplicationMaps: buildFlatApplicationMaps([]),
});
expect(result).toEqual([
- { key: 'app-gone', label: 'app-gone', creditsUsed: 90 },
+ {
+ key: 'app-gone',
+ label: 'app-gone',
+ creditsUsed: 90,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 90,
+ },
]);
});
it('should merge two applications sharing a display name into one slice', () => {
const result = consolidateUsageByApplication({
items: [
- { applicationId: 'app-1', operation: '', creditsUsed: 60 },
- { applicationId: 'app-2', operation: '', creditsUsed: 25 },
+ {
+ applicationId: 'app-1',
+ operation: '',
+ creditsUsed: 60,
+ userCreditsUsed: 20,
+ workspaceCreditsUsed: 40,
+ },
+ {
+ applicationId: 'app-2',
+ operation: '',
+ creditsUsed: 25,
+ userCreditsUsed: 5,
+ workspaceCreditsUsed: 20,
+ },
],
flatApplicationMaps: buildFlatApplicationMaps([
{ id: 'app-1', name: 'Enricher', billing: {} },
@@ -169,16 +253,40 @@ describe('consolidateUsageByApplication', () => {
});
expect(result).toEqual([
- { key: 'Enricher', label: 'Enricher', creditsUsed: 85 },
+ {
+ key: 'Enricher',
+ label: 'Enricher',
+ creditsUsed: 85,
+ userCreditsUsed: 25,
+ workspaceCreditsUsed: 60,
+ },
]);
});
it('should order slices by credits descending after merging', () => {
const result = consolidateUsageByApplication({
items: [
- { applicationId: 'app-1', operation: '', creditsUsed: 10 },
- { applicationId: 'app-2', operation: '', creditsUsed: 400 },
- { applicationId: 'app-1', operation: 'undeclared', creditsUsed: 50 },
+ {
+ applicationId: 'app-1',
+ operation: '',
+ creditsUsed: 10,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 10,
+ },
+ {
+ applicationId: 'app-2',
+ operation: '',
+ creditsUsed: 400,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 400,
+ },
+ {
+ applicationId: 'app-1',
+ operation: 'undeclared',
+ creditsUsed: 50,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 50,
+ },
],
flatApplicationMaps: buildFlatApplicationMaps([
{ id: 'app-1', name: 'Small', billing: {} },
@@ -187,8 +295,50 @@ describe('consolidateUsageByApplication', () => {
});
expect(result).toEqual([
- { key: 'Large', label: 'Large', creditsUsed: 400 },
- { key: 'Small', label: 'Small', creditsUsed: 60 },
+ {
+ key: 'Large',
+ label: 'Large',
+ creditsUsed: 400,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 400,
+ },
+ {
+ key: 'Small',
+ label: 'Small',
+ creditsUsed: 60,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 60,
+ },
+ ]);
+ });
+
+ it('should order slices by workspace credits, not by total credits', () => {
+ const result = consolidateUsageByApplication({
+ items: [
+ {
+ applicationId: 'app-1',
+ operation: '',
+ creditsUsed: 100,
+ userCreditsUsed: 90,
+ workspaceCreditsUsed: 10,
+ },
+ {
+ applicationId: 'app-2',
+ operation: '',
+ creditsUsed: 50,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 50,
+ },
+ ],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ { id: 'app-1', name: 'Mostly user credits', billing: {} },
+ { id: 'app-2', name: 'Workspace credits', billing: {} },
+ ]),
+ });
+
+ expect(result.map((item) => item.key)).toEqual([
+ 'Workspace credits',
+ 'Mostly user credits',
]);
});
@@ -196,7 +346,13 @@ describe('consolidateUsageByApplication', () => {
it('should treat a missing billing column as no declarations', () => {
const result = consolidateUsageByApplication({
items: [
- { applicationId: 'app-1', operation: 'recordMeeting', creditsUsed: 75 },
+ {
+ applicationId: 'app-1',
+ operation: 'recordMeeting',
+ creditsUsed: 75,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 75,
+ },
],
flatApplicationMaps: buildFlatApplicationMaps([
{ id: 'app-1', name: 'Call Recorder' },
@@ -204,7 +360,13 @@ describe('consolidateUsageByApplication', () => {
});
expect(result).toEqual([
- { key: 'Call Recorder', label: 'Call Recorder', creditsUsed: 75 },
+ {
+ key: 'Call Recorder',
+ label: 'Call Recorder',
+ creditsUsed: 75,
+ userCreditsUsed: 0,
+ workspaceCreditsUsed: 75,
+ },
]);
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/fill-usage-time-series-gaps.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/fill-usage-time-series-gaps.util.spec.ts
index 84530d079f9..bfec98e82c5 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/fill-usage-time-series-gaps.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/fill-usage-time-series-gaps.util.spec.ts
@@ -9,71 +9,71 @@ describe('fillUsageTimeSeriesGaps', () => {
});
expect(result).toEqual([
- { date: '2026-04-20', creditsUsed: 0 },
- { date: '2026-04-21', creditsUsed: 0 },
- { date: '2026-04-22', creditsUsed: 0 },
- { date: '2026-04-23', creditsUsed: 0 },
+ { date: '2026-04-20', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-21', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-22', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-23', creditsUsed: 0, workspaceCreditsUsed: 0 },
]);
});
it('should fill internal gaps with zero while preserving real values', () => {
const result = fillUsageTimeSeriesGaps({
rows: [
- { date: '2026-04-20', creditsUsed: 100 },
- { date: '2026-04-22', creditsUsed: 250 },
+ { date: '2026-04-20', creditsUsed: 100, workspaceCreditsUsed: 100 },
+ { date: '2026-04-22', creditsUsed: 250, workspaceCreditsUsed: 250 },
],
periodStart: new Date('2026-04-20T00:00:00.000Z'),
periodEnd: new Date('2026-04-23T23:59:59.999Z'),
});
expect(result).toEqual([
- { date: '2026-04-20', creditsUsed: 100 },
- { date: '2026-04-21', creditsUsed: 0 },
- { date: '2026-04-22', creditsUsed: 250 },
- { date: '2026-04-23', creditsUsed: 0 },
+ { date: '2026-04-20', creditsUsed: 100, workspaceCreditsUsed: 100 },
+ { date: '2026-04-21', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-22', creditsUsed: 250, workspaceCreditsUsed: 250 },
+ { date: '2026-04-23', creditsUsed: 0, workspaceCreditsUsed: 0 },
]);
});
it('should pad trailing dates with zero when data stops before period end (Félix bug)', () => {
const result = fillUsageTimeSeriesGaps({
rows: [
- { date: '2026-04-15', creditsUsed: 50 },
- { date: '2026-04-16', creditsUsed: 75 },
+ { date: '2026-04-15', creditsUsed: 50, workspaceCreditsUsed: 50 },
+ { date: '2026-04-16', creditsUsed: 75, workspaceCreditsUsed: 75 },
],
periodStart: new Date('2026-04-15T00:00:00.000Z'),
periodEnd: new Date('2026-04-20T23:59:59.999Z'),
});
expect(result).toEqual([
- { date: '2026-04-15', creditsUsed: 50 },
- { date: '2026-04-16', creditsUsed: 75 },
- { date: '2026-04-17', creditsUsed: 0 },
- { date: '2026-04-18', creditsUsed: 0 },
- { date: '2026-04-19', creditsUsed: 0 },
- { date: '2026-04-20', creditsUsed: 0 },
+ { date: '2026-04-15', creditsUsed: 50, workspaceCreditsUsed: 50 },
+ { date: '2026-04-16', creditsUsed: 75, workspaceCreditsUsed: 75 },
+ { date: '2026-04-17', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-18', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-19', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-20', creditsUsed: 0, workspaceCreditsUsed: 0 },
]);
});
it('should pad leading dates with zero when data starts after period start', () => {
const result = fillUsageTimeSeriesGaps({
- rows: [{ date: '2026-04-22', creditsUsed: 99 }],
+ rows: [{ date: '2026-04-22', creditsUsed: 99, workspaceCreditsUsed: 99 }],
periodStart: new Date('2026-04-20T00:00:00.000Z'),
periodEnd: new Date('2026-04-23T23:59:59.999Z'),
});
expect(result).toEqual([
- { date: '2026-04-20', creditsUsed: 0 },
- { date: '2026-04-21', creditsUsed: 0 },
- { date: '2026-04-22', creditsUsed: 99 },
- { date: '2026-04-23', creditsUsed: 0 },
+ { date: '2026-04-20', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-21', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-22', creditsUsed: 99, workspaceCreditsUsed: 99 },
+ { date: '2026-04-23', creditsUsed: 0, workspaceCreditsUsed: 0 },
]);
});
it('should return data unchanged when every day in period is already present', () => {
const rows = [
- { date: '2026-04-20', creditsUsed: 1 },
- { date: '2026-04-21', creditsUsed: 2 },
- { date: '2026-04-22', creditsUsed: 3 },
+ { date: '2026-04-20', creditsUsed: 1, workspaceCreditsUsed: 1 },
+ { date: '2026-04-21', creditsUsed: 2, workspaceCreditsUsed: 2 },
+ { date: '2026-04-22', creditsUsed: 3, workspaceCreditsUsed: 3 },
];
const result = fillUsageTimeSeriesGaps({
@@ -87,12 +87,14 @@ describe('fillUsageTimeSeriesGaps', () => {
it('should return a single entry when period spans one day', () => {
const result = fillUsageTimeSeriesGaps({
- rows: [{ date: '2026-04-23', creditsUsed: 42 }],
+ rows: [{ date: '2026-04-23', creditsUsed: 42, workspaceCreditsUsed: 42 }],
periodStart: new Date('2026-04-23T00:00:00.000Z'),
periodEnd: new Date('2026-04-23T23:59:59.999Z'),
});
- expect(result).toEqual([{ date: '2026-04-23', creditsUsed: 42 }]);
+ expect(result).toEqual([
+ { date: '2026-04-23', creditsUsed: 42, workspaceCreditsUsed: 42 },
+ ]);
});
it('should return an empty array when periodStart is after periodEnd', () => {
@@ -107,22 +109,22 @@ describe('fillUsageTimeSeriesGaps', () => {
it('should treat periodEnd as exclusive to match SQL `timestamp < periodEnd` semantics', () => {
const result = fillUsageTimeSeriesGaps({
- rows: [{ date: '2026-04-23', creditsUsed: 10 }],
+ rows: [{ date: '2026-04-23', creditsUsed: 10, workspaceCreditsUsed: 10 }],
periodStart: new Date('2026-04-22T00:00:00.000Z'),
periodEnd: new Date('2026-04-24T00:00:00.000Z'),
});
expect(result).toEqual([
- { date: '2026-04-22', creditsUsed: 0 },
- { date: '2026-04-23', creditsUsed: 10 },
+ { date: '2026-04-22', creditsUsed: 0, workspaceCreditsUsed: 0 },
+ { date: '2026-04-23', creditsUsed: 10, workspaceCreditsUsed: 10 },
]);
});
it('should return dates in ascending order', () => {
const result = fillUsageTimeSeriesGaps({
rows: [
- { date: '2026-04-22', creditsUsed: 5 },
- { date: '2026-04-20', creditsUsed: 1 },
+ { date: '2026-04-22', creditsUsed: 5, workspaceCreditsUsed: 5 },
+ { date: '2026-04-20', creditsUsed: 1, workspaceCreditsUsed: 1 },
],
periodStart: new Date('2026-04-20T00:00:00.000Z'),
periodEnd: new Date('2026-04-23T23:59:59.999Z'),
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/from-record-usage-input-to-usage-consumption-row.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/from-record-usage-input-to-usage-consumption-row.util.spec.ts
index 39c4743723a..0c6e7bce95e 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/from-record-usage-input-to-usage-consumption-row.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/from-record-usage-input-to-usage-consumption-row.util.spec.ts
@@ -32,6 +32,8 @@ describe('fromRecordUsageInputToUsageConsumptionRow', () => {
workflowId: WORKFLOW_ID,
logicFunctionId: '',
creditsUsedMicro: 100,
+ userCreditsUsedMicro: 0,
+ workspaceCreditsUsedMicro: 100,
quantity: 1,
});
});
@@ -44,7 +46,7 @@ describe('fromRecordUsageInputToUsageConsumptionRow', () => {
fromRecordUsageInputToUsageConsumptionRow({
...workflowEvent,
creditsUsedMicro,
- }).creditsUsedMicro,
- ).toBe(0);
+ }),
+ ).toMatchObject({ creditsUsedMicro: 0, workspaceCreditsUsedMicro: 0 });
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.spec.ts
index 36297d0adf6..b0317036cfb 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.spec.ts
@@ -65,4 +65,15 @@ describe('buildUsageEventEnvelopes', () => {
'2026-01-01 00:00:00.000',
);
});
+
+ it('writes a positive user share next to the total cost', () => {
+ const [envelope] = buildUsageEventEnvelopes('ws-1', [
+ usageEvent({ userCreditsUsedMicro: 2500 }),
+ ]);
+
+ expect(envelope.row).toMatchObject({
+ creditsUsedMicro: 7500,
+ userCreditsUsedMicro: 2500,
+ });
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.ts
index a31d9fcac86..432efb5444b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-event-envelopes.ts
@@ -29,6 +29,7 @@ export const buildUsageEventEnvelopes = (
quantity: usageEvent.quantity,
unit: usageEvent.unit,
creditsUsedMicro: usageEvent.creditsUsedMicro,
+ userCreditsUsedMicro: usageEvent.userCreditsUsedMicro ?? 0,
resourceId: usageEvent.resourceId ?? '',
resourceContext: usageEvent.resourceContext ?? '',
metadata: usageEvent.metadata ?? {},
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts
index 926fdd35cd9..56bceb782ff 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts
@@ -17,7 +17,7 @@ export const consolidateUsageByApplication = ({
items,
flatApplicationMaps,
}: ConsolidateUsageByApplicationParams): UsageBreakdownItem[] => {
- const creditsByKey = new Map<string, number>();
+ const itemsByKey = new Map<string, UsageBreakdownItem>();
for (const item of items) {
const application = flatApplicationMaps.byId[item.applicationId];
@@ -33,10 +33,21 @@ export const consolidateUsageByApplication = ({
? `${applicationName} · ${declaredCharge.label}`
: applicationName;
- creditsByKey.set(key, (creditsByKey.get(key) ?? 0) + item.creditsUsed);
+ const consolidatedItem = itemsByKey.get(key);
+
+ itemsByKey.set(key, {
+ key,
+ label: key,
+ creditsUsed: (consolidatedItem?.creditsUsed ?? 0) + item.creditsUsed,
+ userCreditsUsed:
+ (consolidatedItem?.userCreditsUsed ?? 0) + item.userCreditsUsed,
+ workspaceCreditsUsed:
+ (consolidatedItem?.workspaceCreditsUsed ?? 0) +
+ item.workspaceCreditsUsed,
+ });
}
- return [...creditsByKey.entries()]
- .map(([key, creditsUsed]) => ({ key, label: key, creditsUsed }))
- .sort((a, b) => b.creditsUsed - a.creditsUsed);
+ return [...itemsByKey.values()].sort(
+ (a, b) => b.workspaceCreditsUsed - a.workspaceCreditsUsed,
+ );
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/fill-usage-time-series-gaps.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/fill-usage-time-series-gaps.util.ts
index 8b01282345b..be0f9febc0b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/fill-usage-time-series-gaps.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/fill-usage-time-series-gaps.util.ts
@@ -39,7 +39,9 @@ export const fillUsageTimeSeriesGaps = ({
const key = currentDateCursor.toString();
const existing = rowsByDate.get(key);
- filled.push(existing ?? { date: key, creditsUsed: 0 });
+ filled.push(
+ existing ?? { date: key, creditsUsed: 0, workspaceCreditsUsed: 0 },
+ );
currentDateCursor = currentDateCursor.add({ days: 1 });
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util.ts
index ba1338dc286..1ff60936cb3 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util.ts
@@ -10,17 +10,23 @@ export const fromRecordUsageInputToUsageConsumptionRow = ({
spenders,
creditsUsedMicro = 0,
quantity,
-}: RecordUsageInput): UsageConsumptionRow => ({
- operationType,
- unit,
- userWorkspaceId: spenders?.userWorkspaceId ?? '',
- apiKeyId: spenders?.apiKeyId ?? '',
- applicationId: spenders?.applicationId ?? '',
- agentId: spenders?.agentId ?? '',
- workflowId: spenders?.workflowId ?? '',
- logicFunctionId: spenders?.logicFunctionId ?? '',
- creditsUsedMicro: isValidCreditAmountMicro(creditsUsedMicro)
+}: RecordUsageInput): UsageConsumptionRow => {
+ const validCreditsUsedMicro = isValidCreditAmountMicro(creditsUsedMicro)
? creditsUsedMicro
- : 0,
- quantity,
-});
+ : 0;
+
+ return {
+ operationType,
+ unit,
+ userWorkspaceId: spenders?.userWorkspaceId ?? '',
+ apiKeyId: spenders?.apiKeyId ?? '',
+ applicationId: spenders?.applicationId ?? '',
+ agentId: spenders?.agentId ?? '',
+ workflowId: spenders?.workflowId ?? '',
+ logicFunctionId: spenders?.logicFunctionId ?? '',
+ creditsUsedMicro: validCreditsUsedMicro,
+ userCreditsUsedMicro: 0,
+ workspaceCreditsUsedMicro: validCreditsUsedMicro,
+ quantity,
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/from-usage-breakdown-item-to-usage-breakdown-item-dto.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/from-usage-breakdown-item-to-usage-breakdown-item-dto.util.ts
new file mode 100644
index 00000000000..e12bd64d750
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/from-usage-breakdown-item-to-usage-breakdown-item-dto.util.ts
@@ -0,0 +1,19 @@
+/* @license Enterprise */
+
+import { type UsageBreakdownItemDTO } from 'src/engine/core-modules/usage/dtos/usage-breakdown-item.dto';
+import { type UsageBreakdownItem } from 'src/engine/core-modules/usage/services/usage-analytics.service';
+import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
+
+export const fromUsageBreakdownItemToUsageBreakdownItemDTO = ({
+ key,
+ label,
+ creditsUsed,
+ userCreditsUsed,
+ workspaceCreditsUsed,
+}: UsageBreakdownItem): UsageBreakdownItemDTO => ({
+ key,
+ label,
+ creditsUsed: toDisplayCredits(creditsUsed),
+ userCreditsUsed: toDisplayCredits(userCreditsUsed),
+ workspaceCreditsUsed: toDisplayCredits(workspaceCreditsUsed),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
index eceb64ce9d2..698ddc40f1d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
@@ -53,6 +53,7 @@ import { getToolMetricName } from 'src/engine/core-modules/tool-provider/utils/g
import { isToolOutputSuccessful } from 'src/engine/core-modules/tool-provider/utils/is-tool-output-successful.util';
import { OUTPUT_NAVIGATION_TOOL_NAMES } from 'src/engine/core-modules/tool/tools/output-navigation-tool/constants/output-navigation-tool-names.constant';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { OPEN_ENDED_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/open-ended-agent-registry-tool-categories.const';
@@ -497,7 +498,7 @@ export class AgentAsyncExecutorService {
const decrementCreditsForStep = async (
step: Pick<StepResult<ToolSet>, 'usage' | 'providerMetadata'>,
) => {
- const { hasNoMoreAvailableCredits: stepHasNoMoreAvailableCredits } =
+ const { stopReason } =
await this.aiBillingService.decrementAndCheckAvailableCredits({
modelId: registeredModel.modelId,
billingInput: {
@@ -511,7 +512,7 @@ export class AgentAsyncExecutorService {
spenders: usageSpenders,
});
- if (stepHasNoMoreAvailableCredits) {
+ if (isDefined(stopReason)) {
hasNoMoreAvailableCredits = true;
}
};
@@ -761,6 +762,7 @@ export class AgentAsyncExecutorService {
void this.aiBillingService.billNativeWebSearchUsage({
nativeWebSearchCallCount,
workspaceId,
+ operationType: UsageOperationType.AI_WORKFLOW_WEB_SEARCH,
spenders: usageSpenders,
});
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
index 5069a6d63b7..40cfeab7c66 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
@@ -2,6 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';
+import { type QuotaDebitResult } from 'src/engine/core-modules/usage-limit/types/quota-debit-result.type';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
@@ -10,6 +11,7 @@ import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/recor
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { NATIVE_WEB_SEARCH_COST_PER_CALL_DOLLARS } from 'src/engine/metadata-modules/ai/ai-billing/constants/native-web-search-cost-per-call-dollars';
import { type BillingTokenUsage } from 'src/engine/metadata-modules/ai/ai-billing/types/billing-token-usage.type';
+import { type StepDebitResult } from 'src/engine/metadata-modules/ai/ai-billing/types/step-debit-result.type';
import { computeAgentTurnUsageFromSteps } from 'src/engine/metadata-modules/ai/ai-billing/utils/compute-agent-turn-usage-from-steps.util';
import { computeStepCostBreakdown } from 'src/engine/metadata-modules/ai/ai-billing/utils/compute-step-cost-breakdown.util';
import { convertDollarsToCreditsMicro } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-credits-micro.util';
@@ -154,7 +156,7 @@ export class AiBillingService {
workspaceId: string;
operationType: UsageOperationType;
spenders: UsageSpenders;
- }): Promise<{ hasNoMoreAvailableCredits: boolean }> {
+ }): Promise<StepDebitResult> {
const costInDollars = this.calculateCost(modelId, billingInput);
const creditsUsedMicro = convertDollarsToCreditsMicro(costInDollars);
@@ -162,7 +164,7 @@ export class AiBillingService {
(billingInput.usage.inputTokens ?? 0) +
(billingInput.usage.outputTokens ?? 0);
- const { exhaustedKind } =
+ return this.toStepDebitResult(
await this.usageLimitQuotaService.debitAheadOfRecord({
workspaceId,
event: this.buildAiTokenUsageEvent({
@@ -172,22 +174,25 @@ export class AiBillingService {
operationType,
spenders,
}),
- });
-
- return { hasNoMoreAvailableCredits: exhaustedKind === 'allowance' };
+ }),
+ );
}
async billNativeWebSearchUsage({
nativeWebSearchCallCount,
workspaceId,
+ operationType,
spenders,
}: {
nativeWebSearchCallCount: number;
workspaceId: string;
+ operationType:
+ | UsageOperationType.WEB_SEARCH
+ | UsageOperationType.AI_WORKFLOW_WEB_SEARCH;
spenders: UsageSpenders;
- }): Promise<void> {
+ }): Promise<StepDebitResult | null> {
if (nativeWebSearchCallCount <= 0) {
- return;
+ return null;
}
const costInDollars =
@@ -198,19 +203,27 @@ export class AiBillingService {
`Native web search billing: ${nativeWebSearchCallCount} calls, $${costInDollars.toFixed(4)}`,
);
- await this.usageLimitQuotaService.charge({
- workspaceId,
- events: [
- {
- resourceType: UsageResourceType.AI,
- operationType: UsageOperationType.WEB_SEARCH,
- creditsUsedMicro,
- quantity: nativeWebSearchCallCount,
- unit: UsageUnit.INVOCATION,
- spenders,
- },
- ],
- });
+ const event: RecordUsageInput = {
+ resourceType: UsageResourceType.AI,
+ operationType,
+ creditsUsedMicro,
+ quantity: nativeWebSearchCallCount,
+ unit: UsageUnit.INVOCATION,
+ spenders,
+ };
+
+ const webSearchDebit = await this.usageLimitQuotaService.debitAheadOfRecord(
+ {
+ workspaceId,
+ event,
+ },
+ );
+
+ await this.usageRecorderService.record(workspaceId, [
+ { ...event, userCreditsUsedMicro: webSearchDebit.userCreditsUsedMicro },
+ ]);
+
+ return this.toStepDebitResult(webSearchDebit);
}
async emitAiTokenUsageEvent({
@@ -220,6 +233,7 @@ export class AiBillingService {
modelId,
operationType,
spenders,
+ userCreditsUsedMicro = 0,
}: {
workspaceId: string;
creditsUsedMicro: number;
@@ -227,18 +241,32 @@ export class AiBillingService {
modelId: ModelId;
operationType: UsageOperationType;
spenders: UsageSpenders;
+ userCreditsUsedMicro?: number;
}): Promise<void> {
await this.usageRecorderService.record(workspaceId, [
- this.buildAiTokenUsageEvent({
- creditsUsedMicro,
- totalTokens,
- modelId,
- operationType,
- spenders,
- }),
+ {
+ ...this.buildAiTokenUsageEvent({
+ creditsUsedMicro,
+ totalTokens,
+ modelId,
+ operationType,
+ spenders,
+ }),
+ userCreditsUsedMicro,
+ },
]);
}
+ private toStepDebitResult({
+ exhaustedKind,
+ ...userAllowanceDebit
+ }: QuotaDebitResult): StepDebitResult {
+ return {
+ stopReason: exhaustedKind === 'limit' ? null : exhaustedKind,
+ ...userAllowanceDebit,
+ };
+ }
+
private buildAiTokenUsageEvent({
creditsUsedMicro,
totalTokens,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/types/step-debit-result.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/types/step-debit-result.type.ts
new file mode 100644
index 00000000000..8476e5b0078
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/types/step-debit-result.type.ts
@@ -0,0 +1,7 @@
+import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';
+
+export type StepDebitResult = {
+ stopReason: Exclude<ExhaustedKind, 'limit'> | null;
+ userCreditsUsedMicro: number;
+ userAllowanceExhaustedUntil: Date | null;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto.ts
index 6e86b624aff..4ee69356926 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto.ts
@@ -15,5 +15,5 @@ export class AiChatUsageDTO {
periodEnd: Date | null;
@Field(() => String)
- kind: ExhaustedKind;
+ kind: Exclude<ExhaustedKind, 'userAllowance'>;
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
index 3fc6a221abc..c8e18c9e188 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
@@ -275,7 +275,7 @@ describe('StreamAgentChatJob', () => {
: jest.fn().mockResolvedValue({
stream: chatStream,
modelConfig,
- hasNoMoreAvailableCredits: () => false,
+ getStopReason: () => null,
getStreamError: () => chatStream.streamError,
}),
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
index 054661a9ad9..9c66c55d0a7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
@@ -34,6 +34,7 @@ import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service'
import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { type StepDebitResult } from 'src/engine/metadata-modules/ai/ai-billing/types/step-debit-result.type';
import { addStepToAgentTurnUsage } from 'src/engine/metadata-modules/ai/ai-billing/utils/compute-agent-turn-usage-from-steps.util';
import {
AiException,
@@ -392,7 +393,7 @@ export class StreamAgentChatJob {
};
let streamError: unknown;
let streamFinishError: unknown;
- let checkHasNoMoreAvailableCredits: () => boolean = () => false;
+ let getStopReason: () => StepDebitResult['stopReason'] = () => null;
let persistChain: Promise<void> = Promise.resolve();
let lastCheckpointAt = 0;
@@ -452,10 +453,30 @@ export class StreamAgentChatJob {
});
};
+ const onUserCreditsExhausted: ChatExecutionOptions['onUserCreditsExhausted'] =
+ ({ renewsAt, isFallingBackToWorkspaceCredits }) =>
+ this.eventPublisherService
+ .publish({
+ threadId: data.threadId,
+ workspaceId: data.workspaceId,
+ event: {
+ type: 'user-credits-exhausted',
+ workspaceMemberId:
+ authorization.authContext.workspaceMemberId,
+ isFallingBackToWorkspaceCredits,
+ renewsAt: renewsAt.toISOString(),
+ },
+ })
+ .catch((error: unknown) =>
+ this.logger.warn(
+ `Could not publish the user credits notice for stream ${data.streamId}: ${formatErrorWithCause(error)}`,
+ ),
+ );
+
const {
stream,
modelConfig,
- hasNoMoreAvailableCredits,
+ getStopReason: getChatStopReason,
getStreamError,
} = await this.chatExecutionService.streamChat({
workspace,
@@ -472,9 +493,10 @@ export class StreamAgentChatJob {
onCompaction,
abortSignal,
conversationSizeTokens: data.conversationSizeTokens,
+ onUserCreditsExhausted,
});
- checkHasNoMoreAvailableCredits = hasNoMoreAvailableCredits;
+ getStopReason = getChatStopReason;
const titleWritePromise = titlePromise.then((generatedTitle) => {
if (generatedTitle) {
@@ -506,7 +528,7 @@ export class StreamAgentChatJob {
responseMessage,
isAborted,
streamError,
- outOfCredits: checkHasNoMoreAvailableCredits(),
+ stopReason: getStopReason(),
threadId: data.threadId,
workspaceId: data.workspaceId,
workspaceMemberId:
@@ -604,7 +626,7 @@ export class StreamAgentChatJob {
reject(streamError);
} else if (streamFinishError) {
reject(streamFinishError);
- } else if (checkHasNoMoreAvailableCredits()) {
+ } else if (getStopReason() === 'workspaceAllowance') {
await this.eventPublisherService.publish({
threadId: data.threadId,
workspaceId: data.workspaceId,
@@ -689,7 +711,7 @@ export class StreamAgentChatJob {
responseMessage,
isAborted,
streamError,
- outOfCredits,
+ stopReason,
threadId,
workspaceId,
workspaceMemberId,
@@ -703,7 +725,7 @@ export class StreamAgentChatJob {
responseMessage: Omit<ExtendedUIMessage, 'id'>;
isAborted: boolean;
streamError: unknown;
- outOfCredits: boolean;
+ stopReason: StepDebitResult['stopReason'];
threadId: string;
workspaceId: string;
workspaceMemberId: string;
@@ -732,7 +754,7 @@ export class StreamAgentChatJob {
responseMessage,
isAborted,
streamError,
- outOfCredits,
+ stopReason,
hasText,
threadId,
workspaceId,
@@ -752,7 +774,7 @@ export class StreamAgentChatJob {
isAborted,
isAwaitingUserAnswer: awaitingParts.length > 0,
isSilent,
- outOfCredits,
+ stopReason,
});
if (responseMessage.parts.length === 0) {
@@ -904,7 +926,7 @@ export class StreamAgentChatJob {
responseMessage,
isAborted,
streamError,
- outOfCredits,
+ stopReason,
hasText,
threadId,
workspaceId,
@@ -914,7 +936,7 @@ export class StreamAgentChatJob {
responseMessage: Omit<ExtendedUIMessage, 'id'>;
isAborted: boolean;
streamError: unknown;
- outOfCredits: boolean;
+ stopReason: StepDebitResult['stopReason'];
hasText: boolean;
threadId: string;
workspaceId: string;
@@ -925,9 +947,11 @@ export class StreamAgentChatJob {
? 'user-cancelled'
: streamError
? 'stream-error'
- : outOfCredits
- ? 'credits-exhausted'
- : 'empty-completion';
+ : stopReason === 'userAllowance'
+ ? 'user-credits-exhausted'
+ : stopReason === 'workspaceAllowance'
+ ? 'credits-exhausted'
+ : 'empty-completion';
const errorDetail = isDefined(streamError)
? formatErrorWithCause(streamError)
@@ -937,7 +961,7 @@ export class StreamAgentChatJob {
`[AI_CHAT_NO_TEXT] Assistant turn ended without a text reply — ` +
`reason=${reason}, model=${modelId}, ` +
`threadId=${threadId}, workspaceId=${workspaceId}, ` +
- `isAborted=${isAborted}, outOfCredits=${outOfCredits}, hasText=${hasText}, ` +
+ `isAborted=${isAborted}, stopReason=${stopReason}, hasText=${hasText}, ` +
`streamError=${errorDetail}, ` +
`inputTokens=${inputTokens},` +
`responseMessage.parts=${JSON.stringify(responseMessage.parts)}`,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service.ts
index 677c30aee41..27a5b506a1b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service.ts
@@ -36,11 +36,13 @@ export class AiChatUsageService {
});
if (enforcedLimits.length === 0) {
- const allowanceUsage =
- await this.usageLimitQuotaService.getAllowanceUsage(workspaceId);
+ const workspaceAllowanceUsage =
+ await this.usageLimitQuotaService.getWorkspaceAllowanceUsage(
+ workspaceId,
+ );
- return isDefined(allowanceUsage)
- ? { ...allowanceUsage, kind: 'allowance' }
+ return isDefined(workspaceAllowanceUsage)
+ ? { ...workspaceAllowanceUsage, kind: 'workspaceAllowance' }
: null;
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
index 0c957dcf444..4a555f5ff3b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
@@ -68,6 +68,7 @@ import { AGENT_CONFIG } from 'src/engine/metadata-modules/ai/ai-agent/constants/
import { BrowsingContextType } from 'src/engine/metadata-modules/ai/ai-agent/types/browsing-context.type';
import { repairToolCall } from 'src/engine/metadata-modules/ai/ai-agent/utils/repair-tool-call.util';
import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';
+import { type StepDebitResult } from 'src/engine/metadata-modules/ai/ai-billing/types/step-debit-result.type';
import { convertDollarsToCreditsMicro } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-credits-micro.util';
import { countNativeWebSearchCallsFromSteps } from 'src/engine/metadata-modules/ai/ai-billing/utils/count-native-web-search-calls-from-steps.util';
import {
@@ -136,12 +137,16 @@ export type ChatExecutionOptions = {
modelId?: string;
abortSignal: AbortSignal;
conversationSizeTokens: number;
+ onUserCreditsExhausted: (notice: {
+ renewsAt: Date;
+ isFallingBackToWorkspaceCredits: boolean;
+ }) => Promise<void>;
};
export type ChatExecutionResult = {
stream: ReturnType<typeof streamText>;
modelConfig: AiModelConfig;
- hasNoMoreAvailableCredits: () => boolean;
+ getStopReason: () => StepDebitResult['stopReason'];
getStreamError: () => unknown;
};
@@ -182,6 +187,7 @@ export class ChatExecutionService {
modelId,
abortSignal,
conversationSizeTokens,
+ onUserCreditsExhausted,
}: ChatExecutionOptions): Promise<ChatExecutionResult> {
const getAuthorization = createTurnAuthorizer({
authorize: () =>
@@ -486,13 +492,26 @@ export class ChatExecutionService {
const modelMessages = pruningResult.messages;
- let hasNoMoreAvailableCredits = false;
+ let stopReason: StepDebitResult['stopReason'] = null;
+ let turnUserCreditsUsedMicro = 0;
const streamStartedAt = performance.now();
let stepStartedAt = streamStartedAt;
let ttftRecorded = false;
let stepIndex = 0;
let lastUnderlyingStreamError: unknown;
+ const notifyUserCreditsCrossing = async (debit: StepDebitResult) => {
+ if (
+ isDefined(debit.userAllowanceExhaustedUntil) &&
+ debit.userCreditsUsedMicro > 0
+ ) {
+ await onUserCreditsExhausted({
+ renewsAt: debit.userAllowanceExhaustedUntil,
+ isFallingBackToWorkspaceCredits: debit.stopReason === null,
+ });
+ }
+ };
+
const emitTurnUsageEvent = async (steps: StepResult<ToolSet>[]) => {
const usage = steps.reduce(
(totals, step) => ({
@@ -521,13 +540,24 @@ export class ChatExecutionService {
modelId: registeredModel.modelId,
operationType: UsageOperationType.AI_CHAT_TOKEN,
spenders: { userWorkspaceId },
+ userCreditsUsedMicro: Math.min(
+ turnUserCreditsUsedMicro,
+ creditsUsedMicro,
+ ),
});
- void this.aiBillingService.billNativeWebSearchUsage({
- nativeWebSearchCallCount: countNativeWebSearchCallsFromSteps(steps),
- workspaceId: workspace.id,
- spenders: { userWorkspaceId },
- });
+ void this.aiBillingService
+ .billNativeWebSearchUsage({
+ nativeWebSearchCallCount: countNativeWebSearchCallsFromSteps(steps),
+ workspaceId: workspace.id,
+ operationType: UsageOperationType.WEB_SEARCH,
+ spenders: { userWorkspaceId },
+ })
+ .then(async (webSearchDebit) => {
+ if (isDefined(webSearchDebit) && stopReason !== 'userAllowance') {
+ await notifyUserCreditsCrossing(webSearchDebit);
+ }
+ });
const modelAttr = { model: registeredModel.modelId };
@@ -573,7 +603,7 @@ export class ChatExecutionService {
endsOnPausingToolCall({ steps: step.steps }) ||
hasToolCall(COMPLETE_WORKSPACE_SETUP_TOOL_NAME)(step) ||
hasToolCall(NO_REPLY_TOOL_NAME)(step) ||
- hasNoMoreAvailableCredits,
+ isDefined(stopReason),
...buildAiTelemetry({
functionId: isWorkspaceSetupThread
? AI_CHAT_WORKSPACE_SETUP_STREAM_FUNCTION_ID
@@ -645,7 +675,7 @@ export class ChatExecutionService {
bucketBoundaries: AI_LATENCY_MS_BUCKET_BOUNDARIES,
});
- const { hasNoMoreAvailableCredits: stepHasNoMoreAvailableCredits } =
+ const stepDebit =
await this.aiBillingService.decrementAndCheckAvailableCredits({
modelId: registeredModel.modelId,
billingInput: {
@@ -659,9 +689,10 @@ export class ChatExecutionService {
spenders: { userWorkspaceId },
});
- if (stepHasNoMoreAvailableCredits) {
- hasNoMoreAvailableCredits = true;
- }
+ stopReason ??= stepDebit.stopReason;
+ turnUserCreditsUsedMicro += stepDebit.userCreditsUsedMicro;
+
+ await notifyUserCreditsCrossing(stepDebit);
this.logger.log(
`[AI_CHAT_TOKENS] step #${++stepIndex} — ` +
@@ -761,7 +792,7 @@ export class ChatExecutionService {
return {
stream,
modelConfig,
- hasNoMoreAvailableCredits: () => hasNoMoreAvailableCredits,
+ getStopReason: () => stopReason,
getStreamError: () => lastUnderlyingStreamError,
};
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
index 39f7e72ea1d..0cb21221098 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
@@ -11,6 +11,8 @@ import {
import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
@@ -148,10 +150,16 @@ export class WorkspaceSetupChatService {
}
}
- const hasAvailableCredits =
- await this.usageQuotaAdmissionService.hasAvailableCredits(workspace.id);
+ const usageRefusal = await this.usageQuotaAdmissionService.findUsageRefusal(
+ {
+ workspaceId: workspace.id,
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenders: { userWorkspaceId },
+ },
+ );
- if (!hasAvailableCredits) {
+ if (isDefined(usageRefusal)) {
return { outcome: WorkspaceSetupChatOutcome.UNAVAILABLE, thread: null };
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type.ts
index 058a0bfb704..d994e1c0a72 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type.ts
@@ -4,6 +4,10 @@ export type AgentChatTurnOutcome =
| { kind: 'cancelled'; reason: 'user_cancelled' | 'superseded' }
| {
kind: 'failed';
- failurePhase: 'no_text' | 'credits_exhausted' | 'execution';
+ failurePhase:
+ | 'no_text'
+ | 'credits_exhausted'
+ | 'user_credits_exhausted'
+ | 'execution';
errorCode?: string;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/classify-agent-chat-turn-outcome.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/classify-agent-chat-turn-outcome.util.spec.ts
index 8d1cd3e399c..c0d1e31869f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/classify-agent-chat-turn-outcome.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/classify-agent-chat-turn-outcome.util.spec.ts
@@ -8,7 +8,7 @@ const baseTurn = {
isAborted: false,
isAwaitingUserAnswer: false,
isSilent: false,
- outOfCredits: false,
+ stopReason: null,
};
describe('classifyAgentChatTurnOutcome', () => {
@@ -76,14 +76,36 @@ describe('classifyAgentChatTurnOutcome', () => {
classifyAgentChatTurnOutcome({
...baseTurn,
hasText: false,
- outOfCredits: true,
+ stopReason: 'workspaceAllowance',
}),
).toEqual({ kind: 'failed', failurePhase: 'credits_exhausted' });
});
+ it('separates a member running out of their own credits from the workspace running out', () => {
+ expect(
+ classifyAgentChatTurnOutcome({
+ ...baseTurn,
+ hasText: false,
+ stopReason: 'userAllowance',
+ }),
+ ).toEqual({ kind: 'failed', failurePhase: 'user_credits_exhausted' });
+ });
+
+ it('still counts a turn that produced text before the user credits ran out as answered', () => {
+ expect(
+ classifyAgentChatTurnOutcome({
+ ...baseTurn,
+ stopReason: 'userAllowance',
+ }),
+ ).toEqual({ kind: 'completed', outcome: 'answered' });
+ });
+
it('still counts a turn that produced text before credits ran out as answered', () => {
expect(
- classifyAgentChatTurnOutcome({ ...baseTurn, outOfCredits: true }),
+ classifyAgentChatTurnOutcome({
+ ...baseTurn,
+ stopReason: 'workspaceAllowance',
+ }),
).toEqual({ kind: 'completed', outcome: 'answered' });
});
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util.ts
index cab353d10cc..149c8a177cb 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util.ts
@@ -1,3 +1,4 @@
+import { type StepDebitResult } from 'src/engine/metadata-modules/ai/ai-billing/types/step-debit-result.type';
import { type AgentChatTurnOutcome } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type';
export const classifyAgentChatTurnOutcome = ({
@@ -5,13 +6,13 @@ export const classifyAgentChatTurnOutcome = ({
isAborted,
isAwaitingUserAnswer,
isSilent,
- outOfCredits,
+ stopReason,
}: {
hasText: boolean;
isAborted: boolean;
isAwaitingUserAnswer: boolean;
isSilent: boolean;
- outOfCredits: boolean;
+ stopReason: StepDebitResult['stopReason'];
}): AgentChatTurnOutcome => {
// stopWhen ends the stream on a question, so this is a completed turn, not an abandoned one
if (isAwaitingUserAnswer) {
@@ -30,9 +31,14 @@ export const classifyAgentChatTurnOutcome = ({
return { kind: 'completed', outcome: 'silent' };
}
+ if (stopReason === 'userAllowance') {
+ return { kind: 'failed', failurePhase: 'user_credits_exhausted' };
+ }
+
return {
kind: 'failed',
- failurePhase: outOfCredits ? 'credits_exhausted' : 'no_text',
+ failurePhase:
+ stopReason === 'workspaceAllowance' ? 'credits_exhausted' : 'no_text',
};
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/map-agent-chat-turn-outcome-to-turn-status.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/map-agent-chat-turn-outcome-to-turn-status.util.ts
index 06c21a1d74b..d4685acb8ec 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/map-agent-chat-turn-outcome-to-turn-status.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/map-agent-chat-turn-outcome-to-turn-status.util.ts
@@ -2,6 +2,7 @@ import { assertUnreachable } from 'twenty-shared/utils';
import { type AgentChatTurnOutcome } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type';
import { AGENT_TURN_CREDITS_EXHAUSTED_ERROR } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-turn-credits-exhausted-error.constant';
+import { AGENT_TURN_USER_CREDITS_EXHAUSTED_ERROR } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-turn-user-credits-exhausted-error.constant';
import { type StreamErrorPayload } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';
@@ -17,6 +18,7 @@ const FAILURE_ERRORS: Record<
message: 'The agent stopped without replying.',
},
credits_exhausted: AGENT_TURN_CREDITS_EXHAUSTED_ERROR,
+ user_credits_exhausted: AGENT_TURN_USER_CREDITS_EXHAUSTED_ERROR,
};
export const mapAgentChatTurnOutcomeToTurnStatus = (
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-turn-user-credits-exhausted-error.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-turn-user-credits-exhausted-error.constant.ts
new file mode 100644
index 00000000000..9f235c960f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/constants/agent-turn-user-credits-exhausted-error.constant.ts
@@ -0,0 +1,6 @@
+import { type StreamErrorPayload } from 'src/engine/metadata-modules/ai/ai-history/utils/map-error-to-stream-error.util';
+
+export const AGENT_TURN_USER_CREDITS_EXHAUSTED_ERROR: StreamErrorPayload = {
+ code: 'USER_CREDITS_EXHAUSTED',
+ message: 'The member ran out of AI credits.',
+};
diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-send-refusal-exception.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-send-refusal-exception.util.spec.ts
index f70387f7859..2958d0576fb 100644
--- a/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-send-refusal-exception.util.spec.ts
+++ b/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-send-refusal-exception.util.spec.ts
@@ -32,7 +32,7 @@ const buildQuotaRefusal = (exhaustedKind: ExhaustedKind): UsageRefusal => ({
describe('buildCampaignSendRefusalException', () => {
it('advises topping up credits only when the allowance is what ran out', () => {
- const exception = buildException(buildQuotaRefusal('allowance'));
+ const exception = buildException(buildQuotaRefusal('workspaceAllowance'));
expect(exception.code).toBe(
EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS,
@@ -70,7 +70,7 @@ describe('buildCampaignSendRefusalException', () => {
it('gives each refusal its own user facing advice', () => {
const userFriendlyMessages = [
- buildException(buildQuotaRefusal('allowance')),
+ buildException(buildQuotaRefusal('workspaceAllowance')),
buildException(buildQuotaRefusal('limit')),
buildException({
kind: 'subscriptionInactive',
diff --git a/packages/twenty-server/src/modules/emailing/utils/build-campaign-send-refusal-exception.util.ts b/packages/twenty-server/src/modules/emailing/utils/build-campaign-send-refusal-exception.util.ts
index b50c0fb156e..ecd4a0e3d1b 100644
--- a/packages/twenty-server/src/modules/emailing/utils/build-campaign-send-refusal-exception.util.ts
+++ b/packages/twenty-server/src/modules/emailing/utils/build-campaign-send-refusal-exception.util.ts
@@ -29,7 +29,7 @@ export const buildCampaignSendRefusalException = ({
const { exhaustedKind, spenderType, limitValue } = sendRefusal.exhaustedScope;
- if (exhaustedKind === 'allowance') {
+ if (exhaustedKind === 'workspaceAllowance') {
return new EmailingDomainException(
`Campaign ${campaignId} cannot be sent to ${recipientCount} recipient(s): the workspace credit allowance is exhausted`,
EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS,
diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
index 7146745cd0f..1557efc20c9 100644
--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
@@ -71,7 +71,10 @@ describe('Billing credit rollover (integration)', () => {
});
// ClickHouse inserts are asynchronous, so the read is stubbed rather than racing ingestion
- usageSpy = jest.spyOn(billingUsageService, 'getCreditsUsedBetweenOrNull');
+ usageSpy = jest.spyOn(
+ billingUsageService,
+ 'getWorkspaceCreditsUsedMicroBetweenOrNull',
+ );
});
afterEach(async () => {
diff --git a/packages/twenty-server/test/integration/billing/suites/billing-user-credits-fallback.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-user-credits-fallback.integration-spec.ts
new file mode 100644
index 00000000000..5ac4e5fbc23
--- /dev/null
+++ b/packages/twenty-server/test/integration/billing/suites/billing-user-credits-fallback.integration-spec.ts
@@ -0,0 +1,101 @@
+import gql from 'graphql-tag';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
+import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { PermissionsExceptionMessage } from 'src/engine/metadata-modules/permissions/permissions.exception';
+
+const buildUpdateUserCreditsFallbackOperation = (
+ userCreditsFallback: UserCreditsFallback,
+) => ({
+ query: gql`
+ mutation UpdateUserCreditsFallback(
+ $userCreditsFallback: UserCreditsFallback!
+ ) {
+ updateUserCreditsFallback(userCreditsFallback: $userCreditsFallback) {
+ id
+ userCreditsFallback
+ }
+ }
+ `,
+ variables: { userCreditsFallback },
+});
+
+const CURRENT_WORKSPACE_USER_CREDITS_FALLBACK_OPERATION = {
+ query: gql`
+ query CurrentWorkspaceUserCreditsFallback {
+ currentWorkspace {
+ billingCustomer {
+ id
+ userCreditsFallback
+ }
+ }
+ }
+ `,
+};
+
+describe('billing user credits fallback', () => {
+ afterAll(async () => {
+ await makeMetadataApiRequest(
+ buildUpdateUserCreditsFallbackOperation(
+ UserCreditsFallback.WORKSPACE_CREDITS,
+ ),
+ );
+ });
+
+ it('should default to WORKSPACE_CREDITS', async () => {
+ const response = await makeMetadataApiRequest(
+ CURRENT_WORKSPACE_USER_CREDITS_FALLBACK_OPERATION,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(
+ response.body.data.currentWorkspace.billingCustomer.userCreditsFallback,
+ ).toBe(UserCreditsFallback.WORKSPACE_CREDITS);
+ });
+
+ it('should let a member with the billing permission switch to STOP', async () => {
+ const response = await makeMetadataApiRequest(
+ buildUpdateUserCreditsFallbackOperation(UserCreditsFallback.STOP),
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(
+ response.body.data.updateUserCreditsFallback.userCreditsFallback,
+ ).toBe(UserCreditsFallback.STOP);
+
+ const currentWorkspaceResponse = await makeMetadataApiRequest(
+ CURRENT_WORKSPACE_USER_CREDITS_FALLBACK_OPERATION,
+ );
+
+ expect(
+ currentWorkspaceResponse.body.data.currentWorkspace.billingCustomer
+ .userCreditsFallback,
+ ).toBe(UserCreditsFallback.STOP);
+ });
+
+ it('should refuse a member without the billing permission and keep the stored value', async () => {
+ const response = await makeMetadataApiRequest(
+ buildUpdateUserCreditsFallbackOperation(
+ UserCreditsFallback.WORKSPACE_CREDITS,
+ ),
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(response.body.data).toBeNull();
+ expect(response.body.errors[0].message).toBe(
+ PermissionsExceptionMessage.PERMISSION_DENIED,
+ );
+ expect(response.body.errors[0].extensions.code).toBe(ErrorCode.FORBIDDEN);
+
+ const currentWorkspaceResponse = await makeMetadataApiRequest(
+ CURRENT_WORKSPACE_USER_CREDITS_FALLBACK_OPERATION,
+ );
+
+ expect(
+ currentWorkspaceResponse.body.data.currentWorkspace.billingCustomer
+ .userCreditsFallback,
+ ).toBe(UserCreditsFallback.STOP);
+ });
+});
diff --git a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
index c24336026e5..0122032bd75 100644
--- a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
+++ b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
@@ -217,7 +217,7 @@ export const readAllowanceConsumedMicro = async (
workspaceId: string,
): Promise<number> => {
const allowanceUsage =
- await getUsageLimitQuotaService().getAllowanceUsage(workspaceId);
+ await getUsageLimitQuotaService().getWorkspaceAllowanceUsage(workspaceId);
if (!isDefined(allowanceUsage?.consumedValue)) {
throw new Error(`No allowance consumption for workspace ${workspaceId}`);
@@ -230,7 +230,7 @@ export const readAllowanceLimitMicro = async (
workspaceId: string,
): Promise<number> => {
const allowanceUsage =
- await getUsageLimitQuotaService().getAllowanceUsage(workspaceId);
+ await getUsageLimitQuotaService().getWorkspaceAllowanceUsage(workspaceId);
if (!isDefined(allowanceUsage)) {
throw new Error(`No allowance for workspace ${workspaceId}`);
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index b035463febf..0b2ea1ef277 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -214,6 +214,7 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an
"BillingResolver.setResourceCreditSubscriptionPrice {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"BillingResolver.switchBillingPlan {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"BillingResolver.switchSubscriptionInterval {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
+ "BillingResolver.updateUserCreditsFallback {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"BillingWebhookController.handleWebhooks {"applicationTarget":null,"authPrincipalGuards":[]}",
"CalendarChannelResolver.myCalendarChannels {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"CalendarChannelResolver.updateCalendarChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
diff --git a/packages/twenty-server/test/integration/usage-limit/quota-consumption.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/quota-consumption.integration-spec.ts
index 32eb0521174..cfbb82f0e24 100644
--- a/packages/twenty-server/test/integration/usage-limit/quota-consumption.integration-spec.ts
+++ b/packages/twenty-server/test/integration/usage-limit/quota-consumption.integration-spec.ts
@@ -1,3 +1,8 @@
+import {
+ readAllowanceConsumedMicro,
+ refreshCurrentBillingSubscription,
+ setupResourceCreditSubscription,
+} from 'test/integration/billing/utils/billing-credit-fixtures.util';
import { createOneLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/create-logic-function.util';
import { deleteLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/delete-logic-function.util';
import { executeLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/execute-logic-function.util';
@@ -13,12 +18,14 @@ import {
ClickHouseLogLevel,
createClient as createClickHouseClient,
} from '@clickhouse/client';
+import { addMonths, startOfMonth } from 'date-fns';
import { gql } from 'graphql-tag';
import { createClient as createRedisClient } from 'redis';
import { isNonEmptyArray } from 'twenty-shared/utils';
import { type Repository } from 'typeorm';
import { formatDateTimeForClickHouse } from 'src/database/clickhouse/utils/format-date-time-for-clickhouse.util';
+import { UserCreditsFallback } from 'src/engine/core-modules/billing/enums/billing-user-credits-fallback.enum';
import { type CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
import { type MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
@@ -71,6 +78,7 @@ const QUOTA_UNITS = [UsageUnit.INVOCATION, UsageUnit.CREDIT] as const;
const EXECUTED_RUN_COUNT = 2;
const UNREACHABLE_LIMIT_VALUE = 1_000_000_000_000;
const CREDIT_LIMIT_MICRO = 1_000;
+const USER_CREDITS_LIMIT_MICRO = 1_000;
const CONCURRENT_CHARGE_COUNT = 8;
const CLICKHOUSE_FLUSH_TIMEOUT_MS = 30_000;
const EXECUTION_TIMEOUT_MS = 120_000;
@@ -94,6 +102,18 @@ const USAGE_QUOTA_SCOPE_CONSUMPTION = gql`
}
`;
+const UPDATE_USER_CREDITS_FALLBACK = gql`
+ mutation UpdateUserCreditsFallback(
+ $userCreditsFallback: UserCreditsFallback!
+ ) {
+ updateUserCreditsFallback(userCreditsFallback: $userCreditsFallback) {
+ id
+ }
+ }
+`;
+
+const isBillingEnabled = process.env.IS_BILLING_ENABLED === 'true';
+
type QuotaUnit = (typeof QUOTA_UNITS)[number];
const buildRunEvent = ({
@@ -476,6 +496,8 @@ describe('Usage quota consumption', () => {
it.each(QUOTA_UNITS)(
'previews the same cold %s consumption as the quota list',
async (unit) => {
+ await flushQuotaCounters();
+
expect(await findQuotaCounterKeys()).toEqual([]);
const quotaConsumedValue = await findQuotaConsumedValue(unit);
@@ -956,4 +978,262 @@ describe('Usage quota consumption', () => {
unit: UsageUnit.CREDIT,
});
});
+
+ (isBillingEnabled ? describe : describe.skip)(
+ 'on the user credits default',
+ () => {
+ const chargedUserWorkspaceIds: string[] = [];
+
+ const generateUserWorkspaceId = () => {
+ const userWorkspaceId = randomUUID();
+
+ chargedUserWorkspaceIds.push(userWorkspaceId);
+
+ return userWorkspaceId;
+ };
+
+ const chargeChatTokens = ({
+ userWorkspaceId,
+ creditsUsedMicro,
+ }: {
+ userWorkspaceId: string;
+ creditsUsedMicro: number;
+ }) =>
+ getQuotaService().charge({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ events: [
+ {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ unit: UsageUnit.TOKEN,
+ quantity: 1,
+ creditsUsedMicro,
+ spenders: { userWorkspaceId },
+ },
+ ],
+ });
+
+ const readUserCreditsCounter = async (userWorkspaceId: string) => {
+ const [counterKey] = await redis.keys(
+ `*{${SEED_APPLE_WORKSPACE_ID}}:quota-consumed:*:userWorkspace:${userWorkspaceId}:${UsageUnit.USER_CREDIT}:week:*`,
+ );
+
+ jestExpectToBeDefined(counterKey);
+
+ return Number(await redis.get(counterKey));
+ };
+
+ const readWorkspaceAllowanceConsumed = () =>
+ readAllowanceConsumedMicro(SEED_APPLE_WORKSPACE_ID);
+
+ const updateUserCreditsFallback = async (
+ userCreditsFallback: UserCreditsFallback,
+ ) => {
+ const response = await makeMetadataApiRequest({
+ query: UPDATE_USER_CREDITS_FALLBACK,
+ variables: { userCreditsFallback },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ };
+
+ const findUserCreditsRows = async (userWorkspaceId: string) => {
+ const result = await clickHouseClient.query({
+ query: `SELECT creditsUsedMicro, userCreditsUsedMicro
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND userWorkspaceId = {userWorkspaceId:String}
+ ORDER BY creditsUsedMicro`,
+ query_params: {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ userWorkspaceId,
+ },
+ format: 'JSONEachRow',
+ });
+
+ const rows = await result.json<{
+ creditsUsedMicro: string;
+ userCreditsUsedMicro: string;
+ }>();
+
+ return rows.map((row) => ({
+ creditsUsedMicro: Number(row.creditsUsedMicro),
+ userCreditsUsedMicro: Number(row.userCreditsUsedMicro),
+ }));
+ };
+
+ const waitForUserCreditsRows = (
+ userWorkspaceId: string,
+ expectedRows: {
+ creditsUsedMicro: number;
+ userCreditsUsedMicro: number;
+ }[],
+ ) =>
+ expectEventually(
+ async () => {
+ expect(await findUserCreditsRows(userWorkspaceId)).toEqual(
+ expectedRows,
+ );
+ },
+ { timeoutMs: CLICKHOUSE_FLUSH_TIMEOUT_MS, intervalMs: 250 },
+ );
+
+ beforeAll(async () => {
+ const twentyConfigService =
+ getAppProviderByClassName<TwentyConfigService>('TwentyConfigService');
+ const readConfig = twentyConfigService.get.bind(twentyConfigService);
+ const periodStart = startOfMonth(new Date());
+
+ jest
+ .spyOn(twentyConfigService, 'get')
+ .mockImplementation((key) =>
+ key === 'AI_USER_CREDITS_LIMIT'
+ ? USER_CREDITS_LIMIT_MICRO
+ : readConfig(key),
+ );
+
+ await setupResourceCreditSubscription({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ periodStart,
+ periodEnd: addMonths(periodStart, 1),
+ creditAmountMicro: UNREACHABLE_LIMIT_VALUE,
+ });
+ await refreshCurrentBillingSubscription(SEED_APPLE_WORKSPACE_ID);
+ });
+
+ afterAll(async () => {
+ jest.restoreAllMocks();
+
+ if (isNonEmptyArray(chargedUserWorkspaceIds)) {
+ await clickHouseClient.command({
+ query: `ALTER TABLE usageEvent DELETE WHERE workspaceId = {workspaceId:String} AND userWorkspaceId IN {userWorkspaceIds:Array(String)}`,
+ query_params: {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ userWorkspaceIds: chargedUserWorkspaceIds,
+ },
+ clickhouse_settings: { mutations_sync: '2' },
+ });
+ }
+
+ await flushQuotaCounters();
+ }, EXECUTION_TIMEOUT_MS);
+
+ it(
+ 'debits user credits first and leaves the workspace allowance untouched',
+ async () => {
+ const userWorkspaceId = generateUserWorkspaceId();
+ const allowanceConsumed = await readWorkspaceAllowanceConsumed();
+
+ expect(
+ await chargeChatTokens({ userWorkspaceId, creditsUsedMicro: 600 }),
+ ).toEqual({ exhaustedKind: null });
+ expect(await readUserCreditsCounter(userWorkspaceId)).toBe(600);
+ expect(await readWorkspaceAllowanceConsumed()).toBe(
+ allowanceConsumed,
+ );
+
+ await waitForUserCreditsRows(userWorkspaceId, [
+ { creditsUsedMicro: 600, userCreditsUsedMicro: 600 },
+ ]);
+ },
+ EXECUTION_TIMEOUT_MS,
+ );
+
+ it(
+ 'splits a charge that crosses the user credits window exactly',
+ async () => {
+ const userWorkspaceId = generateUserWorkspaceId();
+
+ await chargeChatTokens({ userWorkspaceId, creditsUsedMicro: 600 });
+
+ const allowanceConsumed = await readWorkspaceAllowanceConsumed();
+
+ expect(
+ await chargeChatTokens({ userWorkspaceId, creditsUsedMicro: 700 }),
+ ).toEqual({ exhaustedKind: null });
+ expect(await readUserCreditsCounter(userWorkspaceId)).toBe(
+ USER_CREDITS_LIMIT_MICRO,
+ );
+ expect(await readWorkspaceAllowanceConsumed()).toBe(
+ allowanceConsumed + 300,
+ );
+
+ await waitForUserCreditsRows(userWorkspaceId, [
+ { creditsUsedMicro: 600, userCreditsUsedMicro: 600 },
+ { creditsUsedMicro: 700, userCreditsUsedMicro: 400 },
+ ]);
+ },
+ EXECUTION_TIMEOUT_MS,
+ );
+
+ it(
+ 'stops at the user credits window in STOP mode and records the full charge as user credits',
+ async () => {
+ const userWorkspaceId = generateUserWorkspaceId();
+
+ await updateUserCreditsFallback(UserCreditsFallback.STOP);
+
+ try {
+ const allowanceConsumed = await readWorkspaceAllowanceConsumed();
+
+ expect(
+ await chargeChatTokens({
+ userWorkspaceId,
+ creditsUsedMicro: 1_300,
+ }),
+ ).toEqual({ exhaustedKind: 'userAllowance' });
+ expect(await readUserCreditsCounter(userWorkspaceId)).toBe(1_300);
+ expect(await readWorkspaceAllowanceConsumed()).toBe(
+ allowanceConsumed,
+ );
+ } finally {
+ await updateUserCreditsFallback(
+ UserCreditsFallback.WORKSPACE_CREDITS,
+ );
+ }
+
+ await waitForUserCreditsRows(userWorkspaceId, [
+ { creditsUsedMicro: 1_300, userCreditsUsedMicro: 1_300 },
+ ]);
+ },
+ EXECUTION_TIMEOUT_MS,
+ );
+
+ it(
+ 'records the charge as user credits and leaves the workspace allowance untouched when the user credits window cannot warm',
+ async () => {
+ const userWorkspaceId = generateUserWorkspaceId();
+ const allowanceConsumed = await readWorkspaceAllowanceConsumed();
+ const clickHouseReadSpy = jest
+ .spyOn(
+ getAppProviderByClassName<UsageAnalyticsService>(
+ 'UsageAnalyticsService',
+ ),
+ 'getConsumptionRowsForAllScopes',
+ )
+ .mockRejectedValue(new Error('ClickHouse is unreachable'));
+
+ try {
+ expect(
+ await chargeChatTokens({
+ userWorkspaceId,
+ creditsUsedMicro: 600,
+ }),
+ ).toEqual({ exhaustedKind: null });
+ } finally {
+ clickHouseReadSpy.mockRestore();
+ }
+
+ expect(await readWorkspaceAllowanceConsumed()).toBe(
+ allowanceConsumed,
+ );
+
+ await waitForUserCreditsRows(userWorkspaceId, [
+ { creditsUsedMicro: 600, userCreditsUsedMicro: 600 },
+ ]);
+ },
+ EXECUTION_TIMEOUT_MS,
+ );
+ },
+ );
});
diff --git a/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts b/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
index 1785bfa0be0..232b88ceec0 100644
--- a/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
+++ b/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
@@ -16,4 +16,10 @@ export type AgentChatSubscriptionEvent =
}
| { type: 'stream-error'; code: string; message: string }
| { type: 'credits-exhausted' }
+ | {
+ type: 'user-credits-exhausted';
+ workspaceMemberId: string;
+ isFallingBackToWorkspaceCredits: boolean;
+ renewsAt: string;
+ }
| { type: 'keepalive' };