The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Show AI chat context and credit usage (#25923)
Thomas des Francsff99a7e13f7f
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 8880e3333d2..8a1f0eb251a 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -3299,6 +3299,12 @@ type EventLogQueryResult {pageInfo: EventLogPageInfo!}+type AiChatUsage {+ limitValue: BigInt!+ consumedValue: BigInt+ periodEnd: DateTime+}+type Skill {id: UUID!name: String!@@ -3329,6 +3335,7 @@ type AgentMessage {type AgentChatThread {id: ID!title: String+ totalCacheReadTokens: Int!totalInputTokens: Int!totalOutputTokens: Int!contextWindowTokens: Int@@ -3737,6 +3744,7 @@ type Query {appConnections(filter: ListAppConnectionsInput): [AppConnection!]!appConnection(id: ID!): AppConnection!findWorkspaceAiStats: WorkspaceAiStats!+ aiChatUsage: AiChatUsagechatThreads: [AgentChatThread!]!chatThread(id: UUID!): AgentChatThread!chatMessages(threadId: UUID!): [AgentMessage!]!diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 26f5915a252..69a85cc3d99 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -2901,6 +2901,13 @@ export interface EventLogQueryResult {__typename: 'EventLogQueryResult'}+export interface AiChatUsage {+ limitValue: Scalars['BigInt']+ consumedValue?: Scalars['BigInt']+ periodEnd?: Scalars['DateTime']+ __typename: 'AiChatUsage'+}+export interface Skill {id: Scalars['UUID']name: Scalars['String']@@ -2933,6 +2940,7 @@ export interface AgentMessage {export interface AgentChatThread {id: Scalars['ID']title?: Scalars['String']+ totalCacheReadTokens: Scalars['Int']totalInputTokens: Scalars['Int']totalOutputTokens: Scalars['Int']contextWindowTokens?: Scalars['Int']@@ -3276,6 +3284,7 @@ export interface Query {appConnections: AppConnection[]appConnection: AppConnectionfindWorkspaceAiStats: WorkspaceAiStats+ aiChatUsage?: AiChatUsagechatThreads: AgentChatThread[]chatThread: AgentChatThreadchatMessages: AgentMessage[]@@ -6614,6 +6623,14 @@ export interface EventLogQueryResultGenqlSelection{__scalar?: boolean | number}+export interface AiChatUsageGenqlSelection{+ limitValue?: boolean | number+ consumedValue?: boolean | number+ periodEnd?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}+export interface SkillGenqlSelection{id?: boolean | numbername?: boolean | number@@ -6648,6 +6665,7 @@ export interface AgentMessageGenqlSelection{export interface AgentChatThreadGenqlSelection{id?: boolean | numbertitle?: boolean | number+ totalCacheReadTokens?: boolean | numbertotalInputTokens?: boolean | numbertotalOutputTokens?: boolean | numbercontextWindowTokens?: boolean | number@@ -7005,6 +7023,7 @@ export interface QueryGenqlSelection{appConnections?: (AppConnectionGenqlSelection & { __args?: {filter?: (ListAppConnectionsInput | null)} })appConnection?: (AppConnectionGenqlSelection & { __args: {id: Scalars['ID']} })findWorkspaceAiStats?: WorkspaceAiStatsGenqlSelection+ aiChatUsage?: AiChatUsageGenqlSelectionchatThreads?: AgentChatThreadGenqlSelectionchatThread?: (AgentChatThreadGenqlSelection & { __args: {id: Scalars['UUID']} })chatMessages?: (AgentMessageGenqlSelection & { __args: {threadId: Scalars['UUID']} })@@ -9947,6 +9966,14 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null+ const AiChatUsage_possibleTypes: string[] = ['AiChatUsage']+ export const isAiChatUsage = (obj?: { __typename?: any } | null): obj is AiChatUsage => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isAiChatUsage"')+ return AiChatUsage_possibleTypes.includes(obj.__typename)+ }+++const Skill_possibleTypes: string[] = ['Skill']export const isSkill = (obj?: { __typename?: any } | null): obj is Skill => {if (!obj?.__typename) throw new Error('__typename is missing in "isSkill"')diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex 9daf1a2b22b..dab47c5b7ba 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -90,20 +90,20 @@ export default {334,335,338,- 375,- 382,- 384,+ 376,+ 383,385,386,387,- 389,- 391,- 396,- 413,- 425,- 545,- 549,- 576+ 388,+ 390,+ 392,+ 397,+ 414,+ 426,+ 546,+ 550,+ 577],"types": {"BillingProductDTO": {@@ -6496,6 +6496,20 @@ export default {1]},+ "AiChatUsage": {+ "limitValue": [+ 181+ ],+ "consumedValue": [+ 181+ ],+ "periodEnd": [+ 4+ ],+ "__typename": [+ 1+ ]+ },"Skill": {"id": [3@@ -6576,6 +6590,9 @@ export default {"title": [1],+ "totalCacheReadTokens": [+ 28+ ],"totalInputTokens": [28],@@ -6626,7 +6643,7 @@ export default {},"AiSystemPromptPreview": {"sections": [- 368+ 369],"estimatedTokenCount": [28@@ -6654,7 +6671,7 @@ export default {28],"error": [- 370+ 371],"__typename": [1@@ -6687,10 +6704,10 @@ export default {},"StartWorkspaceSetupChatResult": {"outcome": [- 375+ 376],"thread": [- 367+ 368],"__typename": [1@@ -6728,10 +6745,10 @@ export default {3],"evaluations": [- 376+ 377],"messages": [- 366+ 367],"createdAt": [4@@ -6793,7 +6810,7 @@ export default {9],"scope": [- 382+ 383],"__typename": [1@@ -6808,19 +6825,19 @@ export default {1],"syncStatus": [- 384+ 385],"syncStage": [- 385+ 386],"visibility": [- 386+ 387],"isContactAutoCreationEnabled": [8],"contactAutoCreationPolicy": [- 387+ 388],"isSyncEnabled": [8@@ -6871,7 +6888,7 @@ export default {1],"pendingSyncAction": [- 389+ 390],"messageChannelId": [3@@ -6913,7 +6930,7 @@ export default {1],"provenance": [- 391+ 392],"__typename": [1@@ -6942,7 +6959,7 @@ export default {3],"through": [- 392+ 393],"__typename": [1@@ -6962,7 +6979,7 @@ export default {1],"emit": [- 393+ 394],"action": [1@@ -6997,7 +7014,7 @@ export default {},"CollectionHash": {"collectionName": [- 396+ 397],"hash": [1@@ -7061,13 +7078,13 @@ export default {},"MinimalMetadata": {"objectMetadataItems": [- 397+ 398],"views": [- 398+ 399],"collectionHashes": [- 395+ 396],"__typename": [1@@ -7127,7 +7144,7 @@ export default {175,{"input": [- 401+ 402]}],@@ -7144,7 +7161,7 @@ export default {182,{"input": [- 402,+ 403,"UsageQuotaScopeInput!"]}@@ -7267,7 +7284,7 @@ export default {2,{"input": [- 403,+ 404,"GetApiKeyInput!"]}@@ -7385,7 +7402,7 @@ export default {10,{"input": [- 404,+ 405,"AgentIdInput!"]}@@ -7398,7 +7415,7 @@ export default {"CursorPaging!"],"filter": [- 405,+ 406,"ObjectFilter!"]}@@ -7428,7 +7445,7 @@ export default {21,{"input": [- 406,+ 407,"LogicFunctionIdInput!"]}@@ -7440,7 +7457,7 @@ export default {9,{"input": [- 406,+ 407,"LogicFunctionIdInput!"]}@@ -7449,7 +7466,7 @@ export default {1,{"input": [- 406,+ 407,"LogicFunctionIdInput!"]}@@ -7689,7 +7706,7 @@ export default {328,{"input": [- 407,+ 408,"PreviewMessageCampaignAudienceInput!"]}@@ -7698,7 +7715,7 @@ export default {336,{"input": [- 408,+ 409,"FindMessageSuppressionsInput!"]}@@ -7718,7 +7735,7 @@ export default {317,{"filter": [- 409+ 410]}],@@ -7750,7 +7767,7 @@ export default {}],"myMessageFolders": [- 388,+ 389,{"messageChannelId": [3@@ -7758,7 +7775,7 @@ export default {}],"myCalendarChannels": [- 383,+ 384,{"connectedAccountId": [3@@ -7766,17 +7783,17 @@ export default {}],"minimalMetadata": [- 399+ 400],"appKeyValue": [- 381,+ 382,{"key": [1,"String!"],"scope": [- 382+ 383]}],@@ -7793,7 +7810,7 @@ export default {228,{"filter": [- 410+ 411]}],@@ -7807,13 +7824,16 @@ export default {}],"findWorkspaceAiStats": [- 378+ 379+ ],+ "aiChatUsage": [+ 365],"chatThreads": [- 367+ 368],"chatThread": [- 367,+ 368,{"id": [3,@@ -7822,7 +7842,7 @@ export default {}],"chatMessages": [- 366,+ 367,{"threadId": [3,@@ -7831,7 +7851,7 @@ export default {}],"chatStreamCatchupChunks": [- 371,+ 372,{"threadId": [3,@@ -7840,13 +7860,13 @@ export default {}],"getAiSystemPromptPreview": [- 369+ 370],"skills": [- 365+ 366],"skill": [- 365,+ 366,{"id": [3,@@ -7855,7 +7875,7 @@ export default {}],"agentTurns": [- 377,+ 378,{"agentId": [3,@@ -7864,13 +7884,13 @@ export default {}],"timelineActivityTypes": [- 394+ 395],"metadataTranslations": [- 390,+ 391,{"input": [- 411,+ 412,"MetadataTranslationsInput!"]}@@ -7936,7 +7956,7 @@ export default {364,{"input": [- 412,+ 413,"EventLogQueryInput!"]}@@ -7945,7 +7965,7 @@ export default {358,{"input": [- 416,+ 417,"PieChartDataInput!"]}@@ -7954,7 +7974,7 @@ export default {356,{"input": [- 417,+ 418,"LineChartDataInput!"]}@@ -7963,7 +7983,7 @@ export default {353,{"input": [- 418,+ 419,"BarChartDataInput!"]}@@ -8095,10 +8115,10 @@ export default {},"ObjectFilter": {"and": [- 405+ 406],"or": [- 405+ 406],"id": [31@@ -8208,10 +8228,10 @@ export default {},"EventLogQueryInput": {"table": [- 413+ 414],"filters": [- 414+ 415],"first": [28@@ -8232,7 +8252,7 @@ export default {1],"dateRange": [- 415+ 416],"recordId": [1@@ -8293,7 +8313,7 @@ export default {8,{"input": [- 420,+ 421,"AddQuerySubscriptionInput!"]}@@ -8302,7 +8322,7 @@ export default {8,{"input": [- 421,+ 422,"RemoveQueryFromEventStreamInput!"]}@@ -8311,7 +8331,7 @@ export default {154,{"inputs": [- 422,+ 423,"[CreateNavigationMenuItemInput!]!"]}@@ -8320,7 +8340,7 @@ export default {154,{"input": [- 422,+ 423,"CreateNavigationMenuItemInput!"]}@@ -8329,7 +8349,7 @@ export default {154,{"inputs": [- 423,+ 424,"[UpdateOneNavigationMenuItemInput!]!"]}@@ -8338,7 +8358,7 @@ export default {154,{"input": [- 423,+ 424,"UpdateOneNavigationMenuItemInput!"]}@@ -8412,7 +8432,7 @@ export default {151,{"file": [- 425,+ 426,"Upload!"]}@@ -8421,7 +8441,7 @@ export default {151,{"file": [- 425,+ 426,"Upload!"]}@@ -8430,7 +8450,7 @@ export default {151,{"file": [- 425,+ 426,"Upload!"],"fieldMetadataUniversalIdentifier": [@@ -8443,7 +8463,7 @@ export default {183,{"input": [- 426,+ 427,"CreateUsageLimitInput!"]}@@ -8452,7 +8472,7 @@ export default {183,{"input": [- 427,+ 428,"UpdateUsageLimitInput!"]}@@ -8470,7 +8490,7 @@ export default {55,{"input": [- 428,+ 429,"CreateViewFilterGroupInput!"]}@@ -8483,7 +8503,7 @@ export default {"String!"],"input": [- 429,+ 430,"UpdateViewFilterGroupInput!"]}@@ -8510,7 +8530,7 @@ export default {57,{"input": [- 430,+ 431,"CreateViewFilterInput!"]}@@ -8519,7 +8539,7 @@ export default {57,{"input": [- 431,+ 432,"UpdateViewFilterInput!"]}@@ -8528,7 +8548,7 @@ export default {57,{"input": [- 433,+ 434,"DeleteViewFilterInput!"]}@@ -8537,7 +8557,7 @@ export default {57,{"input": [- 434,+ 435,"DestroyViewFilterInput!"]}@@ -8546,7 +8566,7 @@ export default {63,{"input": [- 435,+ 436,"CreateViewInput!"]}@@ -8559,7 +8579,7 @@ export default {"String!"],"input": [- 436,+ 437,"UpdateViewInput!"]}@@ -8586,7 +8606,7 @@ export default {63,{"input": [- 437,+ 438,"UpsertViewWidgetInput!"]}@@ -8595,7 +8615,7 @@ export default {60,{"input": [- 443,+ 444,"CreateViewSortInput!"]}@@ -8604,7 +8624,7 @@ export default {60,{"input": [- 444,+ 445,"UpdateViewSortInput!"]}@@ -8613,7 +8633,7 @@ export default {8,{"input": [- 446,+ 447,"DeleteViewSortInput!"]}@@ -8622,7 +8642,7 @@ export default {8,{"input": [- 447,+ 448,"DestroyViewSortInput!"]}@@ -8631,7 +8651,7 @@ export default {53,{"input": [- 448,+ 449,"UpdateViewFieldInput!"]}@@ -8640,7 +8660,7 @@ export default {53,{"input": [- 450,+ 451,"CreateViewFieldInput!"]}@@ -8649,7 +8669,7 @@ export default {53,{"inputs": [- 450,+ 451,"[CreateViewFieldInput!]!"]}@@ -8658,7 +8678,7 @@ export default {53,{"input": [- 451,+ 452,"DeleteViewFieldInput!"]}@@ -8667,7 +8687,7 @@ export default {53,{"input": [- 452,+ 453,"DestroyViewFieldInput!"]}@@ -8676,7 +8696,7 @@ export default {62,{"input": [- 453,+ 454,"UpdateViewFieldGroupInput!"]}@@ -8685,7 +8705,7 @@ export default {62,{"input": [- 455,+ 456,"CreateViewFieldGroupInput!"]}@@ -8694,7 +8714,7 @@ export default {62,{"inputs": [- 455,+ 456,"[CreateViewFieldGroupInput!]!"]}@@ -8703,7 +8723,7 @@ export default {62,{"input": [- 456,+ 457,"DeleteViewFieldGroupInput!"]}@@ -8712,7 +8732,7 @@ export default {62,{"input": [- 457,+ 458,"DestroyViewFieldGroupInput!"]}@@ -8721,7 +8741,7 @@ export default {63,{"input": [- 458,+ 459,"UpsertFieldsWidgetInput!"]}@@ -8730,7 +8750,7 @@ export default {2,{"input": [- 461,+ 462,"CreateApiKeyInput!"]}@@ -8739,7 +8759,7 @@ export default {2,{"input": [- 462,+ 463,"UpdateApiKeyInput!"]}@@ -8748,7 +8768,7 @@ export default {2,{"input": [- 463,+ 464,"RevokeApiKeyInput!"]}@@ -8950,7 +8970,7 @@ export default {184,{"input": [- 464,+ 465,"CreateApprovedAccessDomainInput!"]}@@ -8959,7 +8979,7 @@ export default {8,{"input": [- 465,+ 466,"DeleteApprovedAccessDomainInput!"]}@@ -8968,7 +8988,7 @@ export default {184,{"input": [- 466,+ 467,"ValidateApprovedAccessDomainInput!"]}@@ -8977,7 +8997,7 @@ export default {125,{"input": [- 467,+ 468,"CreatePageLayoutTabInput!"]}@@ -8990,7 +9010,7 @@ export default {"String!"],"input": [- 468,+ 469,"UpdatePageLayoutTabInput!"]}@@ -9008,7 +9028,7 @@ export default {126,{"input": [- 469,+ 470,"CreatePageLayoutInput!"]}@@ -9021,7 +9041,7 @@ export default {"String!"],"input": [- 470,+ 471,"UpdatePageLayoutInput!"]}@@ -9043,7 +9063,7 @@ export default {"String!"],"input": [- 471,+ 472,"UpdatePageLayoutWithTabsInput!"]}@@ -9079,7 +9099,7 @@ export default {81,{"input": [- 474,+ 475,"CreatePageLayoutWidgetInput!"]}@@ -9092,7 +9112,7 @@ export default {"String!"],"input": [- 475,+ 476,"UpdatePageLayoutWidgetInput!"]}@@ -9110,7 +9130,7 @@ export default {10,{"input": [- 476,+ 477,"CreateAgentInput!"]}@@ -9119,7 +9139,7 @@ export default {10,{"input": [- 477,+ 478,"UpdateAgentInput!"]}@@ -9128,7 +9148,7 @@ export default {10,{"input": [- 404,+ 405,"AgentIdInput!"]}@@ -9137,7 +9157,7 @@ export default {23,{"input": [- 478,+ 479,"CreateOneObjectInput!"]}@@ -9146,7 +9166,7 @@ export default {23,{"input": [- 480,+ 481,"DeleteOneObjectInput!"]}@@ -9155,7 +9175,7 @@ export default {23,{"input": [- 481,+ 482,"UpdateOneObjectInput!"]}@@ -9164,7 +9184,7 @@ export default {258,{"input": [- 484,+ 485,"CreateOneIndexInput!"]}@@ -9173,7 +9193,7 @@ export default {258,{"input": [- 487,+ 488,"DeleteOneIndexInput!"]}@@ -9182,7 +9202,7 @@ export default {21,{"input": [- 406,+ 407,"LogicFunctionIdInput!"]}@@ -9191,7 +9211,7 @@ export default {21,{"input": [- 488,+ 489,"CreateLogicFunctionFromSourceInput!"]}@@ -9200,7 +9220,7 @@ export default {147,{"input": [- 489,+ 490,"ExecuteOneLogicFunctionInput!"]}@@ -9209,7 +9229,7 @@ export default {8,{"input": [- 490,+ 491,"UpdateLogicFunctionFromSourceInput!"]}@@ -9218,7 +9238,7 @@ export default {14,{"input": [- 492,+ 493,"CreateCommandMenuItemInput!"]}@@ -9227,7 +9247,7 @@ export default {14,{"input": [- 493,+ 494,"UpdateCommandMenuItemInput!"]}@@ -9254,7 +9274,7 @@ export default {13,{"input": [- 494,+ 495,"CreateFrontComponentInput!"]}@@ -9263,7 +9283,7 @@ export default {13,{"input": [- 495,+ 496,"UpdateFrontComponentInput!"]}@@ -9281,7 +9301,7 @@ export default {69,{"data": [- 497,+ 498,"ActivateWorkspaceInput!"]}@@ -9290,7 +9310,7 @@ export default {69,{"data": [- 498,+ 499,"UpdateWorkspaceInput!"]}@@ -9321,7 +9341,7 @@ export default {225,{"input": [- 499,+ 500,"CreateApplicationRegistrationInput!"]}@@ -9330,7 +9350,7 @@ export default {76,{"input": [- 500,+ 501,"UpdateApplicationRegistrationInput!"]}@@ -9357,7 +9377,7 @@ export default {198,{"input": [- 502,+ 503,"CreateApplicationRegistrationVariableInput!"]}@@ -9366,7 +9386,7 @@ export default {198,{"input": [- 503,+ 504,"UpdateApplicationRegistrationVariableInput!"]}@@ -9384,7 +9404,7 @@ export default {76,{"file": [- 425,+ 426,"Upload!"],"universalIdentifier": [@@ -9442,7 +9462,7 @@ export default {245,{"input": [- 505,+ 506,"TriggerInstallApplicationJobInput!"]}@@ -9451,7 +9471,7 @@ export default {246,{"input": [- 506,+ 507,"TriggerUninstallApplicationJobInput!"]}@@ -9464,7 +9484,7 @@ export default {"UUID!"],"input": [- 507,+ 508,"UpdateApplicationInput!"]}@@ -9485,7 +9505,7 @@ export default {250,{"input": [- 508,+ 509,"CreateOneFieldMetadataInput!"]}@@ -9494,7 +9514,7 @@ export default {250,{"input": [- 510,+ 511,"UpdateOneFieldMetadataInput!"]}@@ -9503,7 +9523,7 @@ export default {250,{"input": [- 512,+ 513,"DeleteOneFieldInput!"]}@@ -9512,7 +9532,7 @@ export default {59,{"input": [- 513,+ 514,"CreateViewGroupInput!"]}@@ -9521,7 +9541,7 @@ export default {59,{"inputs": [- 513,+ 514,"[CreateViewGroupInput!]!"]}@@ -9530,7 +9550,7 @@ export default {59,{"input": [- 514,+ 515,"UpdateViewGroupInput!"]}@@ -9539,7 +9559,7 @@ export default {59,{"inputs": [- 514,+ 515,"[UpdateViewGroupInput!]!"]}@@ -9548,7 +9568,7 @@ export default {59,{"input": [- 516,+ 517,"DeleteViewGroupInput!"]}@@ -9557,7 +9577,7 @@ export default {59,{"input": [- 517,+ 518,"DestroyViewGroupInput!"]}@@ -9579,7 +9599,7 @@ export default {48,{"createRoleInput": [- 518,+ 519,"CreateRoleInput!"]}@@ -9588,7 +9608,7 @@ export default {48,{"updateRoleInput": [- 519,+ 520,"UpdateRoleInput!"]}@@ -9606,7 +9626,7 @@ export default {45,{"upsertObjectPermissionsInput": [- 521,+ 522,"UpsertObjectPermissionsInput!"]}@@ -9615,7 +9635,7 @@ export default {46,{"upsertPermissionFlagsInput": [- 523,+ 524,"UpsertPermissionFlagsInput!"]}@@ -9624,7 +9644,7 @@ export default {40,{"upsertFieldPermissionsInput": [- 524,+ 525,"UpsertFieldPermissionsInput!"]}@@ -9633,7 +9653,7 @@ export default {271,{"input": [- 526,+ 527,"UpsertRowLevelPermissionPredicatesInput!"]}@@ -9664,7 +9684,7 @@ export default {330,{"input": [- 529,+ 530,"SendEmailViaDomainInput!"]}@@ -9673,7 +9693,7 @@ export default {331,{"input": [- 530,+ 531,"SendMessageCampaignInput!"]}@@ -9682,7 +9702,7 @@ export default {329,{"input": [- 531,+ 532,"CancelMessageCampaignInput!"]}@@ -9691,7 +9711,7 @@ export default {330,{"input": [- 532,+ 533,"SendMessageCampaignTestInput!"]}@@ -9709,7 +9729,7 @@ export default {333,{"input": [- 533,+ 534,"CreateMessageSuppressionInput!"]}@@ -9727,7 +9747,7 @@ export default {337,{"input": [- 534,+ 535,"CreateUnsubscribeTopicInput!"]}@@ -9736,7 +9756,7 @@ export default {337,{"input": [- 535,+ 536,"UpdateUnsubscribeTopicInput!"]}@@ -9754,7 +9774,7 @@ export default {317,{"input": [- 536,+ 537,"UpdateMessageChannelInput!"]}@@ -9763,7 +9783,7 @@ export default {327,{"input": [- 538,+ 539,"CreateEmailGroupChannelInput!"]}@@ -9772,7 +9792,7 @@ export default {317,{"input": [- 539,+ 540,"UpdateEmailGroupChannelInput!"]}@@ -9790,7 +9810,7 @@ export default {317,{"input": [- 540,+ 541,"CreateAppMessageChannelInput!"]}@@ -9799,7 +9819,7 @@ export default {317,{"input": [- 541,+ 542,"UpdateAppMessageChannelInput!"]}@@ -9817,7 +9837,7 @@ export default {326,{"input": [- 542,+ 543,"IngestAppMessagesInput!"]}@@ -9826,7 +9846,7 @@ export default {313,{"input": [- 546,+ 547,"CreateEmailingDomainInput!"]}@@ -9853,7 +9873,7 @@ export default {349,{"input": [- 547,+ 548,"RunAgentInput!"]}@@ -9862,7 +9882,7 @@ export default {346,{"input": [- 551,+ 552,"CreateWebhookInput!"]}@@ -9871,7 +9891,7 @@ export default {346,{"input": [- 552,+ 553,"UpdateWebhookInput!"]}@@ -9886,37 +9906,37 @@ export default {}],"updateMessageFolder": [- 388,+ 389,{"input": [- 554,+ 555,"UpdateMessageFolderInput!"]}],"updateMessageFolders": [- 388,+ 389,{"input": [- 556,+ 557,"UpdateMessageFoldersInput!"]}],"updateCalendarChannel": [- 383,+ 384,{"input": [- 557,+ 558,"UpdateCalendarChannelInput!"]}],"setAppKeyValue": [- 381,+ 382,{"input": [- 559,+ 560,"SetAppKeyValueInput!"]}@@ -9929,24 +9949,24 @@ export default {"String!"],"scope": [- 382+ 383]}],"enqueueJob": [- 379,+ 380,{"input": [- 560,+ 561,"EnqueueJobInput!"]}],"enqueueJobs": [- 380,+ 381,{"input": [- 561,+ 562,"EnqueueJobsInput!"]}@@ -9955,16 +9975,16 @@ export default {8,{"input": [- 563,+ 564,"ReportAppConnectionAuthFailureInput!"]}],"createChatThread": [- 367+ 368],"sendChatMessage": [- 372,+ 373,{"threadId": [3,@@ -9985,13 +10005,13 @@ export default {1],"fileAttachments": [- 564,+ 565,"[FileAttachmentInput!]"]}],"retryChatMessage": [- 372,+ 373,{"threadId": [3,@@ -10003,7 +10023,7 @@ export default {}],"answerAgentChatQuestion": [- 372,+ 373,{"threadId": [3,@@ -10014,14 +10034,14 @@ export default {"UUID!"],"answers": [- 565,+ 566,"[AgentChatQuestionAnswerInput!]!"],"modelId": [1],"fileAttachments": [- 564,+ 565,"[FileAttachmentInput!]"]}@@ -10036,7 +10056,7 @@ export default {}],"renameChatThread": [- 367,+ 368,{"id": [3,@@ -10049,7 +10069,7 @@ export default {}],"archiveChatThread": [- 367,+ 368,{"id": [3,@@ -10058,7 +10078,7 @@ export default {}],"unarchiveChatThread": [- 367,+ 368,{"id": [3,@@ -10085,7 +10105,7 @@ export default {}],"startWorkspaceSetupChat": [- 374,+ 375,{"companyContext": [9@@ -10096,25 +10116,25 @@ export default {}],"createSkill": [- 365,+ 366,{"input": [- 566,+ 567,"CreateSkillInput!"]}],"updateSkill": [- 365,+ 366,{"input": [- 567,+ 568,"UpdateSkillInput!"]}],"deleteSkill": [- 365,+ 366,{"id": [3,@@ -10123,7 +10143,7 @@ export default {}],"activateSkill": [- 365,+ 366,{"id": [3,@@ -10132,7 +10152,7 @@ export default {}],"deactivateSkill": [- 365,+ 366,{"id": [3,@@ -10141,7 +10161,7 @@ export default {}],"evaluateAgentTurn": [- 376,+ 377,{"turnId": [3,@@ -10150,7 +10170,7 @@ export default {}],"runEvaluationInput": [- 377,+ 378,{"agentId": [3,@@ -10163,16 +10183,16 @@ export default {}],"updateTimelineActivityType": [- 394,+ 395,{"input": [- 568,+ 569,"UpdateTimelineActivityTypeInput!"]}],"resetTimelineActivityType": [- 394,+ 395,{"id": [3,@@ -10184,7 +10204,7 @@ export default {280,{"input": [- 569,+ 570,"GetAuthorizationUrlForSSOInput!"]}@@ -10350,7 +10370,7 @@ export default {283,{"input": [- 570+ 571]}],@@ -10362,7 +10382,7 @@ export default {"String!"],"file": [- 425,+ 426,"Upload!"]}@@ -10528,7 +10548,7 @@ export default {8,{"input": [- 571,+ 572,"UpdateWorkspaceMemberSettingsInput!"]}@@ -10562,7 +10582,7 @@ export default {235,{"input": [- 572,+ 573,"SetupOIDCSsoInput!"]}@@ -10571,7 +10591,7 @@ export default {235,{"input": [- 573,+ 574,"SetupSAMLSsoInput!"]}@@ -10580,7 +10600,7 @@ export default {231,{"input": [- 574,+ 575,"DeleteSsoInput!"]}@@ -10589,7 +10609,7 @@ export default {232,{"input": [- 575,+ 576,"EditSsoInput!"]}@@ -10618,7 +10638,7 @@ export default {361,{"type": [- 576,+ 577,"AnalyticsType!"],"name": [@@ -10661,7 +10681,7 @@ export default {351,{"input": [- 577,+ 578,"CreateCalendarEventInput!"]}@@ -10670,7 +10690,7 @@ export default {360,{"input": [- 578,+ 579,"SendEmailInput!"]}@@ -10692,7 +10712,7 @@ export default {"String!"],"connectionParameters": [- 580,+ 581,"EmailAccountConnectionParameters!"],"id": [@@ -10704,7 +10724,7 @@ export default {195,{"input": [- 582,+ 583,"UpdateLabPublicFeatureFlagInput!"]}@@ -10772,7 +10792,7 @@ export default {302,{"file": [- 425,+ 426,"Upload!"],"applicationUniversalIdentifier": [@@ -10797,7 +10817,7 @@ export default {"String!"],"files": [- 583,+ 584,"[ApplicationFileUploadRequestInput!]!"]}@@ -10920,7 +10940,7 @@ export default {3],"update": [- 424+ 425],"__typename": [1@@ -10993,7 +11013,7 @@ export default {3],"payload": [- 426+ 427],"__typename": [1@@ -11076,7 +11096,7 @@ export default {3],"update": [- 432+ 433],"__typename": [1@@ -11247,19 +11267,19 @@ export default {3],"view": [- 438+ 439],"viewFields": [- 439+ 440],"viewFilters": [- 440+ 441],"viewFilterGroups": [- 441+ 442],"viewSorts": [- 442+ 443],"__typename": [1@@ -11408,7 +11428,7 @@ export default {3],"update": [- 445+ 446],"__typename": [1@@ -11446,7 +11466,7 @@ export default {3],"update": [- 449+ 450],"__typename": [1@@ -11522,7 +11542,7 @@ export default {3],"update": [- 454+ 455],"__typename": [1@@ -11586,10 +11606,10 @@ export default {3],"groups": [- 459+ 460],"fields": [- 460+ 461],"__typename": [1@@ -11609,7 +11629,7 @@ export default {8],"fields": [- 460+ 461],"__typename": [1@@ -11780,7 +11800,7 @@ export default {8],"tabs": [- 472+ 473],"__typename": [1@@ -11803,7 +11823,7 @@ export default {85],"widgets": [- 473+ 474],"__typename": [1@@ -11968,7 +11988,7 @@ export default {},"CreateOneObjectInput": {"object": [- 479+ 480],"__typename": [1@@ -12028,7 +12048,7 @@ export default {},"UpdateOneObjectInput": {"update": [- 482+ 483],"id": [3@@ -12081,7 +12101,7 @@ export default {24],"translations": [- 483+ 484],"__typename": [1@@ -12103,7 +12123,7 @@ export default {},"CreateOneIndexInput": {"index": [- 485+ 486],"__typename": [1@@ -12114,7 +12134,7 @@ export default {3],"fields": [- 486+ 487],"indexType": [259@@ -12199,7 +12219,7 @@ export default {3],"update": [- 491+ 492],"__typename": [1@@ -12368,7 +12388,7 @@ export default {3],"update": [- 496+ 497],"__typename": [1@@ -12495,7 +12515,7 @@ export default {1],"update": [- 501+ 502],"__typename": [1@@ -12540,7 +12560,7 @@ export default {1],"update": [- 504+ 505],"__typename": [1@@ -12586,7 +12606,7 @@ export default {},"CreateOneFieldMetadataInput": {"field": [- 509+ 510],"__typename": [1@@ -12665,7 +12685,7 @@ export default {3],"update": [- 511+ 512],"__typename": [1@@ -12730,7 +12750,7 @@ export default {9],"translations": [- 483+ 484],"__typename": [1@@ -12769,7 +12789,7 @@ export default {3],"update": [- 515+ 516],"__typename": [1@@ -12854,7 +12874,7 @@ export default {},"UpdateRoleInput": {"update": [- 520+ 521],"id": [3@@ -12909,7 +12929,7 @@ export default {3],"objectPermissions": [- 522+ 523],"__typename": [1@@ -12951,7 +12971,7 @@ export default {3],"fieldPermissions": [- 525+ 526],"__typename": [1@@ -12982,10 +13002,10 @@ export default {3],"predicates": [- 527+ 528],"predicateGroups": [- 528+ 529],"__typename": [1@@ -13161,7 +13181,7 @@ export default {3],"update": [- 537+ 538],"__typename": [1@@ -13254,7 +13274,7 @@ export default {3],"messages": [- 543+ 544],"__typename": [1@@ -13277,7 +13297,7 @@ export default {4],"participants": [- 544+ 545],"__typename": [1@@ -13285,7 +13305,7 @@ export default {},"AppMessageParticipantInput": {"role": [- 545+ 546],"handle": [1@@ -13323,7 +13343,7 @@ export default {3],"messages": [- 548+ 549],"__typename": [1@@ -13331,13 +13351,13 @@ export default {},"RunAgentMessageInput": {"role": [- 549+ 550],"content": [1],"attachments": [- 550+ 551],"__typename": [1@@ -13380,7 +13400,7 @@ export default {3],"update": [- 553+ 554],"__typename": [1@@ -13408,7 +13428,7 @@ export default {3],"update": [- 555+ 556],"__typename": [1@@ -13427,7 +13447,7 @@ export default {3],"update": [- 555+ 556],"__typename": [1@@ -13438,7 +13458,7 @@ export default {3],"update": [- 558+ 559],"__typename": [1@@ -13446,13 +13466,13 @@ export default {},"UpdateCalendarChannelInputUpdates": {"visibility": [- 386+ 387],"isContactAutoCreationEnabled": [8],"contactAutoCreationPolicy": [- 387+ 388],"isSyncEnabled": [8@@ -13469,7 +13489,7 @@ export default {9],"scope": [- 382+ 383],"__typename": [1@@ -13503,7 +13523,7 @@ export default {9],"jobs": [- 562+ 563],"retryLimit": [28@@ -13625,7 +13645,7 @@ export default {8],"translations": [- 483+ 484],"__typename": [1@@ -13791,7 +13811,7 @@ export default {1],"files": [- 579+ 580],"__typename": [1@@ -13813,13 +13833,13 @@ export default {1],"IMAP": [- 581+ 582],"SMTP": [- 581+ 582],"CALDAV": [- 581+ 582],"__typename": [1@@ -13884,13 +13904,13 @@ export default {272,{"input": [- 585,+ 586,"LogicFunctionLogsInput!"]}],"onAgentChatEvent": [- 373,+ 374,{"threadId": [3,@@ -13902,7 +13922,7 @@ export default {362,{"table": [- 413,+ 414,"EventLogTable!"]}diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 3d779698f13..123468bd41d 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -73,6 +73,7 @@ export type AgentChatThread = {id: Scalars['ID']['output'];lastMessageAt?: Maybe<Scalars['DateTime']['output']>;title?: Maybe<Scalars['String']['output']>;+ totalCacheReadTokens: Scalars['Int']['output'];totalInputCredits: Scalars['Float']['output'];totalInputTokens: Scalars['Int']['output'];totalOutputCredits: Scalars['Float']['output'];@@ -180,6 +181,13 @@ export enum AggregateOperations {SUM = 'SUM'}+export type AiChatUsage = {+ __typename?: 'AiChatUsage';+ consumedValue?: Maybe<Scalars['BigInt']['output']>;+ limitValue: Scalars['BigInt']['output'];+ periodEnd?: Maybe<Scalars['DateTime']['output']>;+};+export enum AiModelTier {balanced = 'balanced',extraFast = 'extraFast',@@ -4999,6 +5007,7 @@ export type PublicWorkspaceDataSummary = {export type Query = {__typename?: 'Query';agentTurns: Array<AgentTurn>;+ aiChatUsage?: Maybe<AiChatUsage>;apiKey?: Maybe<ApiKey>;apiKeys: Array<ApiKey>;appConnection: AppConnection;@@ -7760,6 +7769,11 @@ export type GetAgentTurnsQueryVariables = Exact<{export type GetAgentTurnsQuery = { __typename?: 'Query', agentTurns: Array<{ __typename?: 'AgentTurn', id: string, threadId: string, agentId?: string | null, createdAt: string, evaluations: Array<{ __typename?: 'AgentTurnEvaluation', id: string, score: number, comment?: string | null, createdAt: string }>, messages: Array<{ __typename?: 'AgentMessage', id: string, role: string, createdAt: string, parts: Array<{ __typename?: 'AgentMessagePart', id: string, type: string, textContent?: string | null, reasoningContent?: string | null, toolName?: string | null, toolCallId?: string | null, toolInput?: any | null, toolOutput?: any | null, errorMessage?: string | null, state?: string | null, providerExecuted?: boolean | null, errorDetails?: any | null, sourceUrlSourceId?: string | null, sourceUrlUrl?: string | null, sourceUrlTitle?: string | null, sourceDocumentSourceId?: string | null, sourceDocumentMediaType?: string | null, sourceDocumentTitle?: string | null, sourceDocumentFilename?: string | null, fileMediaType?: string | null, fileFilename?: string | null, fileUrl?: string | null, providerMetadata?: any | null }> }> }> };+export type GetAiChatUsageQueryVariables = Exact<{ [key: string]: never; }>;+++export type GetAiChatUsageQuery = { __typename?: 'Query', aiChatUsage?: { __typename?: 'AiChatUsage', limitValue: any, consumedValue?: any | null, periodEnd?: string | null } | null };+export type GetChatMessagesQueryVariables = Exact<{threadId: Scalars['UUID']['input'];}>;@@ -7770,7 +7784,7 @@ export type GetChatMessagesQuery = { __typename?: 'Query', chatMessages: Array<{export type GetChatThreadsQueryVariables = Exact<{ [key: string]: never; }>;-export type GetChatThreadsQuery = { __typename?: 'Query', chatThreads: Array<{ __typename?: 'AgentChatThread', id: string, title?: string | null, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, lastMessageAt?: string | null, createdAt: string, updatedAt: string }> };+export type GetChatThreadsQuery = { __typename?: 'Query', chatThreads: Array<{ __typename?: 'AgentChatThread', id: string, title?: string | null, totalCacheReadTokens: number, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, lastMessageAt?: string | null, createdAt: string, updatedAt: string }> };export type GetToolIndexQueryVariables = Exact<{ [key: string]: never; }>;@@ -8585,7 +8599,7 @@ export type StartWorkspaceSetupChatMutationVariables = Exact<{}>;-export type StartWorkspaceSetupChatMutation = { __typename?: 'Mutation', startWorkspaceSetupChat: { __typename?: 'StartWorkspaceSetupChatResult', outcome: WorkspaceSetupChatOutcome, thread?: { __typename?: 'AgentChatThread', id: string, title?: string | null, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, lastMessageAt?: string | null, createdAt: string, updatedAt: string } | null } };+export type StartWorkspaceSetupChatMutation = { __typename?: 'Mutation', startWorkspaceSetupChat: { __typename?: 'StartWorkspaceSetupChatResult', outcome: WorkspaceSetupChatOutcome, thread?: { __typename?: 'AgentChatThread', id: string, title?: string | null, totalCacheReadTokens: number, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, lastMessageAt?: string | null, createdAt: string, updatedAt: string } | null } };export type TriggerInstallAppsOnboardingStepMutationVariables = Exact<{universalIdentifiers: Array<Scalars['String']['input']> | Scalars['String']['input'];@@ -10119,8 +10133,9 @@ export const FindOneAgentDocument = {"kind":"Document","definitions":[{"kind":"Oexport const FindOneSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneSkill"},"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":"skill"},"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":"SkillFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"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":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindOneSkillQuery, FindOneSkillQueryVariables>;export const FindWorkspaceAiStatsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindWorkspaceAiStats"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findWorkspaceAiStats"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"conversationsCount"}},{"kind":"Field","name":{"kind":"Name","value":"skillsCount"}},{"kind":"Field","name":{"kind":"Name","value":"toolsCount"}}]}}]}}]} as unknown as DocumentNode<FindWorkspaceAiStatsQuery, FindWorkspaceAiStatsQueryVariables>;export const GetAgentTurnsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAgentTurns"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"agentTurns"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"agentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"evaluations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"score"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"messages"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"parts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"textContent"}},{"kind":"Field","name":{"kind":"Name","value":"reasoningContent"}},{"kind":"Field","name":{"kind":"Name","value":"toolName"}},{"kind":"Field","name":{"kind":"Name","value":"toolCallId"}},{"kind":"Field","name":{"kind":"Name","value":"toolInput"}},{"kind":"Field","name":{"kind":"Name","value":"toolOutput"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"providerExecuted"}},{"kind":"Field","name":{"kind":"Name","value":"errorDetails"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlSourceId"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlUrl"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlTitle"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentSourceId"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentMediaType"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentTitle"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentFilename"}},{"kind":"Field","name":{"kind":"Name","value":"fileMediaType"}},{"kind":"Field","name":{"kind":"Name","value":"fileFilename"}},{"kind":"Field","name":{"kind":"Name","value":"fileUrl"}},{"kind":"Field","name":{"kind":"Name","value":"providerMetadata"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetAgentTurnsQuery, GetAgentTurnsQueryVariables>;+export const GetAiChatUsageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAiChatUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"aiChatUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"consumedValue"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}}]}}]}}]} as unknown as DocumentNode<GetAiChatUsageQuery, GetAiChatUsageQueryVariables>;export const GetChatMessagesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetChatMessages"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"chatMessages"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"turnId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"parts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"orderIndex"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"textContent"}},{"kind":"Field","name":{"kind":"Name","value":"reasoningContent"}},{"kind":"Field","name":{"kind":"Name","value":"toolName"}},{"kind":"Field","name":{"kind":"Name","value":"toolCallId"}},{"kind":"Field","name":{"kind":"Name","value":"toolInput"}},{"kind":"Field","name":{"kind":"Name","value":"toolOutput"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"providerExecuted"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"errorDetails"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlSourceId"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlUrl"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlTitle"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentSourceId"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentMediaType"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentTitle"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentFilename"}},{"kind":"Field","name":{"kind":"Name","value":"fileMediaType"}},{"kind":"Field","name":{"kind":"Name","value":"fileFilename"}},{"kind":"Field","name":{"kind":"Name","value":"fileUrl"}},{"kind":"Field","name":{"kind":"Name","value":"fileId"}},{"kind":"Field","name":{"kind":"Name","value":"providerMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"chatStreamCatchupChunks"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"chunks"}},{"kind":"Field","name":{"kind":"Name","value":"maxSeq"}},{"kind":"Field","name":{"kind":"Name","value":"error"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"message"}}]}}]}}]}}]} as unknown as DocumentNode<GetChatMessagesQuery, GetChatMessagesQueryVariables>;-export const GetChatThreadsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetChatThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"chatThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetChatThreadsQuery, GetChatThreadsQueryVariables>;+export const GetChatThreadsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetChatThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"chatThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalCacheReadTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetChatThreadsQuery, GetChatThreadsQueryVariables>;export const GetToolIndexDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetToolIndex"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getToolIndex"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"category"}},{"kind":"Field","name":{"kind":"Name","value":"objectName"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}}]}}]}}]} as unknown as DocumentNode<GetToolIndexQuery, GetToolIndexQueryVariables>;export const GetToolInputSchemaDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetToolInputSchema"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"toolName"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getToolInputSchema"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"toolName"},"value":{"kind":"Variable","name":{"kind":"Name","value":"toolName"}}}]}]}}]} as unknown as DocumentNode<GetToolInputSchemaQuery, GetToolInputSchemaQueryVariables>;export const OnAgentChatEventDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"OnAgentChatEvent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"onAgentChatEvent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"event"}}]}}]}}]} as unknown as DocumentNode<OnAgentChatEventSubscription, OnAgentChatEventSubscriptionVariables>;@@ -10214,7 +10229,7 @@ export const CompleteBookCallOnboardingStepDocument = {"kind":"Document","definiexport const EnrichWorkspaceCompanyDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"EnrichWorkspaceCompany"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"enrichWorkspaceCompany"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"outcome"}},{"kind":"Field","name":{"kind":"Name","value":"enrichment"}},{"kind":"Field","name":{"kind":"Name","value":"personOutcome"}},{"kind":"Field","name":{"kind":"Name","value":"personEnrichment"}},{"kind":"Field","name":{"kind":"Name","value":"isBookCallOnboardingStepPending"}}]}}]}}]} as unknown as DocumentNode<EnrichWorkspaceCompanyMutation, EnrichWorkspaceCompanyMutationVariables>;export const GoBackToPreviousOnboardingStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GoBackToPreviousOnboardingStep"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"goBackToPreviousOnboardingStep"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"onboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"previousOnboardingStatus"}}]}}]}}]} as unknown as DocumentNode<GoBackToPreviousOnboardingStepMutation, GoBackToPreviousOnboardingStepMutationVariables>;export const SkipSyncEmailOnboardingStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SkipSyncEmailOnboardingStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"isAutoSkipped"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"skipSyncEmailOnboardingStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"isAutoSkipped"},"value":{"kind":"Variable","name":{"kind":"Name","value":"isAutoSkipped"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}}]}}]}}]} as unknown as DocumentNode<SkipSyncEmailOnboardingStepMutation, SkipSyncEmailOnboardingStepMutationVariables>;-export const StartWorkspaceSetupChatDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"StartWorkspaceSetupChat"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"companyContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"personContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"startWorkspaceSetupChat"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"companyContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"companyContext"}}},{"kind":"Argument","name":{"kind":"Name","value":"personContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"personContext"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"outcome"}},{"kind":"Field","name":{"kind":"Name","value":"thread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]} as unknown as DocumentNode<StartWorkspaceSetupChatMutation, StartWorkspaceSetupChatMutationVariables>;+export const StartWorkspaceSetupChatDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"StartWorkspaceSetupChat"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"companyContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"personContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"startWorkspaceSetupChat"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"companyContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"companyContext"}}},{"kind":"Argument","name":{"kind":"Name","value":"personContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"personContext"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"outcome"}},{"kind":"Field","name":{"kind":"Name","value":"thread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalCacheReadTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]} as unknown as DocumentNode<StartWorkspaceSetupChatMutation, StartWorkspaceSetupChatMutationVariables>;export const TriggerInstallAppsOnboardingStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"TriggerInstallAppsOnboardingStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifiers"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"isAutoSkipped"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"triggerInstallAppsOnboardingStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifiers"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifiers"}}},{"kind":"Argument","name":{"kind":"Name","value":"isAutoSkipped"},"value":{"kind":"Variable","name":{"kind":"Name","value":"isAutoSkipped"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}}]}}]}}]} as unknown as DocumentNode<TriggerInstallAppsOnboardingStepMutation, TriggerInstallAppsOnboardingStepMutationVariables>;export const GetInviteSuggestionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetInviteSuggestions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getInviteSuggestions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}}]}}]}}]} as unknown as DocumentNode<GetInviteSuggestionsQuery, GetInviteSuggestionsQueryVariables>;export const ResetPageLayoutTabToDefaultDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ResetPageLayoutTabToDefault"},"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":"resetPageLayoutTabToDefault"},"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":"PageLayoutTabFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutWidgetFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidget"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalAvailabilityExpression"}},{"kind":"Field","name":{"kind":"Name","value":"gridPosition"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}}]}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetGridPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetVerticalListPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"index"}},{"kind":"Field","name":{"kind":"Name","value":"heightBehavior"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetCanvasPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"configuration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BarChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"groupMode"}},{"kind":"Field","name":{"kind":"Name","value":"layout"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LineChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"isStacked"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PieChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"groupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"groupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"dateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"orderBy"}},{"kind":"Field","name":{"kind":"Name","value":"manualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"showCenterMetric"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"hideEmptyCategory"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AggregateChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"prefix"}},{"kind":"Field","name":{"kind":"Name","value":"suffix"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}},{"kind":"Field","name":{"kind":"Name","value":"ratioAggregateConfig"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"optionValue"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"IframeConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"StandaloneRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"body"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"blocknote"}},{"kind":"Field","name":{"kind":"Name","value":"markdown"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CalendarConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailThreadConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingSummaryConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingTranscriptConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignBodyConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignDetailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldDisplayMode"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"nestedRelationFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"newFieldDefaultVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"shouldAllowUserToSeeHiddenFields"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FormFieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FilesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NotesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TasksConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ViewConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RecordTableConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"recordLimit"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowRunConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowVersionConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FrontComponentConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentId"}},{"kind":"Field","name":{"kind":"Name","value":"headerCommandMenuItemUniversalIdentifiers"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutTabId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutTabFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutTab"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"widgets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PageLayoutWidgetFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutId"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<ResetPageLayoutTabToDefaultMutation, ResetPageLayoutTabToDefaultMutationVariables>;diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsxindex 78a2849f9dd..eee03723b86 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx@@ -6,6 +6,7 @@ import {tipTapDocumentToMarkdown,} from 'twenty-shared/utils';+import { getAgentChatUsageFromThread } from '@/ai/utils/getAgentChatUsageFromThread';import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';import {AGENT_CHAT_NEW_THREAD_DRAFT_KEY,@@ -26,7 +27,10 @@ import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jimport { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';-import { PermissionFlagType } from '~/generated-metadata/graphql';+import {+ type AgentChatThread,+ PermissionFlagType,+} from '~/generated-metadata/graphql';const AGENT_CHAT_THREADS_REFRESH_RETRY_DELAY_MS = 3000;@@ -97,12 +101,22 @@ export const AgentChatThreadInitializationEffect = () => {useEffect(() => {if (hasInitializedAgentChatThreads ||- (currentAiChatThread !== null && isValidUuid(currentAiChatThread))+ (storeEntry.status === 'empty' && hasAiPermission)) {return;}- if (storeEntry.status === 'empty' && hasAiPermission) {+ if (isDefined(currentAiChatThread) && isValidUuid(currentAiChatThread)) {+ const selectedThread = (storeEntry.current as AgentChatThread[]).find(+ ({ id }) => id === currentAiChatThread,+ );+ if (isDefined(selectedThread)) {+ store.set(+ agentChatUsageFamilyCallback({ threadId: selectedThread.id }),+ getAgentChatUsageFromThread(selectedThread),+ );+ }+ setHasInitializedAgentChatThreads(true);return;}@@ -127,23 +141,9 @@ export const AgentChatThreadInitializationEffect = () => {firstThread.title ?? null,);- const hasUsageData =- (firstThread.conversationSize ?? 0) > 0 &&- isDefined(firstThread.contextWindowTokens);-store.set(agentChatUsageFamilyCallback(firstThreadFamilyKey),- hasUsageData- ? {- lastMessage: null,- conversationSize: firstThread.conversationSize ?? 0,- contextWindowTokens: firstThread.contextWindowTokens ?? 0,- inputTokens: firstThread.totalInputTokens,- outputTokens: firstThread.totalOutputTokens,- inputCredits: firstThread.totalInputCredits,- outputCredits: firstThread.totalOutputCredits,- }- : null,+ getAgentChatUsageFromThread(firstThread),);} else {store.set(hasTriggeredCreateForDraftState.atom, false);@@ -163,6 +163,7 @@ export const AgentChatThreadInitializationEffect = () => {hasInitializedAgentChatThreads,setHasInitializedAgentChatThreads,storeEntry.status,+ storeEntry.current,setCurrentAiChatThread,setAgentChatInput,store,diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsxindex 168eed9c390..e79c6ac2953 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsx@@ -1,3 +1,7 @@+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { type AgentChatThread } from '~/generated-metadata/graphql';import { act, render } from '@testing-library/react';import { createStore, Provider as JotaiProvider } from 'jotai';@@ -54,4 +58,52 @@ describe('AgentChatThreadInitializationEffect', () => {expect(refreshAgentChatThreadsMock).toHaveBeenCalledTimes(2);});+ it('seeds an already-selected deep link when metadata arrives', async () => {+ refreshAgentChatThreadsMock.mockResolvedValue([]);+ const store = createStore();+ const threadId = '9ebfd0b0-a703-4478-8859-9b01c2eef391';+ store.set(currentAiChatThreadState.atom, threadId);+ const usageAtom = agentChatUsageComponentFamilyState.atomFamily({+ instanceId: 'agent-chat-initialization-test',+ familyKey: { threadId },+ });+ render(+ <JotaiProvider store={store}>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: 'agent-chat-initialization-test' }}+ >+ <AgentChatThreadInitializationEffect />+ </AgentChatComponentInstanceContext.Provider>+ </JotaiProvider>,+ );+ expect(store.get(usageAtom)).toBeNull();+ const metadataAtom = metadataStoreState.atomFamily('agentChatThreads');+ await act(async () => {+ store.set(metadataAtom, {+ ...store.get(metadataAtom),+ status: 'up-to-date',+ current: [+ {+ id: threadId,+ deletedAt: '2026-09-01',+ createdAt: '2026-08-01',+ updatedAt: '2026-09-01',+ conversationSize: 120,+ totalInputTokens: 250,+ totalOutputTokens: 30,+ totalCacheReadTokens: 80,+ contextWindowTokens: 1000,+ totalInputCredits: 0.125,+ totalOutputCredits: 0.05,+ } satisfies AgentChatThread,+ ],+ });+ });+ expect(store.get(usageAtom)).toMatchObject({+ inputTokens: 250,+ cachedInputTokens: 80,+ lastMessage: null,+ });+ expect(store.get(currentAiChatThreadState.atom)).toBe(threadId);+ });});diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsxindex e517566ae77..a2d942f2769 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx@@ -57,6 +57,7 @@ const THREAD: AgentChatThread = {lastMessageAt: '2026-09-01T00:00:00.000Z',totalInputTokens: 0,totalOutputTokens: 0,+ totalCacheReadTokens: 0,conversationSize: 0,totalInputCredits: 0,totalOutputCredits: 0,diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageButton.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageButton.tsxindex 6fde37e4fe1..2b8df1f001a 100644--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageButton.tsx+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageButton.tsx@@ -1,253 +1,255 @@+import { getAiChatUsageLabel } from '@/ai/utils/getAiChatUsageLabel';+import { formatAiChatTokens } from '@/ai/utils/formatAiChatTokens';+import { useQuery } from '@apollo/client/react';+import {+ FloatingPortal,+ autoUpdate,+ flip,+ offset,+ safePolygon,+ shift,+ useClick,+ useDismiss,+ useFloating,+ useFocus,+ useHover,+ useInteractions,+ useRole,+ useTransitionStyles,+} from '@floating-ui/react';import { styled } from '@linaria/react';-import { t } from '@lingui/core/macro';import { useLingui } from '@lingui/react/macro';import { useState } from 'react';+import { useReducedMotion } from 'framer-motion';import { isDefined } from 'twenty-shared/utils';+import { Button } from 'twenty-ui/primitives/input';+import { IconWindow, IconGauge } from 'twenty-ui/icon';import { HorizontalSeparator } from 'twenty-ui/primitives/layout';-import { ProgressBar } from 'twenty-ui/primitives/feedback';import { themeCssVariables } from 'twenty-ui/theme-constants';+import { AiChatContextUsageDetails } from '@/ai/components/internal/AiChatContextUsageDetails';import { ContextUsageProgressRing } from '@/ai/components/internal/ContextUsageProgressRing';-import { agentChatHasMessageComponentSelector } from '@/ai/states/selectors/agentChatHasMessageComponentSelector';-import {- agentChatUsageComponentFamilyState,- type AgentChatLastMessageUsage,-} from '@/ai/states/agentChatUsageComponentFamilyState';+import { useAiModelTiers } from '@/ai/hooks/useAiModelTiers';+import { useWorkspaceAiModelTiers } from '@/ai/hooks/useWorkspaceAiModelTiers';+import { useIsWorkspaceSetupChat } from '@/ai/hooks/useIsWorkspaceSetupChat';+import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { agentChatUserSelectedModelTierState } from '@/ai/states/agentChatUserSelectedModelTierState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';-import { billingState } from '@/client-config/states/billingState';-import { SettingsBillingLabelValueItem } from '@/settings/billing/components/internal/SettingsBillingLabelValueItem';-import { useUsageValueFormatter } from '@/settings/usage/hooks/useUsageValueFormatter';+import { getUsageLimitRingColor } from '@/settings/billing/utils/getUsageLimitRingColor';+import { computeUsageLimitProgress } from '@/settings/billing/utils/computeUsageLimitProgress';+import { StyledInformationCard } from '@/ui/layout/information-card/components/StyledInformationCard';+import { UsageProgressRow } from '@/ui/feedback/progress-ring/components/UsageProgressRow';import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';-import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { GetAiChatUsageDocument } from '~/generated-metadata/graphql';import { formatNumber } from '~/utils/format/formatNumber';-const StyledContainer = styled.div`- position: relative;-`;--const StyledTrigger = styled.div<{ hasUsage: boolean }>`+const StyledTrigger = styled.button`align-items: center;+ background: transparent;+ border: none;border-radius: ${themeCssVariables.border.radius.md};- cursor: ${({ hasUsage }) => (hasUsage ? 'pointer' : 'default')};+ cursor: pointer;display: flex;height: 24px;justify-content: center;- min-width: 24px;- transition: background calc(${themeCssVariables.animation.duration.fast} * 1s)- ease;+ padding: 0;+ width: 24px;&:hover {- background: ${({ hasUsage }) =>- hasUsage- ? themeCssVariables.background.transparent.light- : 'transparent'};+ background: ${themeCssVariables.background.transparent.light};+ }+ &:focus-visible {+ outline: 2px solid ${themeCssVariables.color.blue};}`;-const StyledHoverCard = styled.div`- background: ${themeCssVariables.background.primary};- border: 1px solid ${themeCssVariables.border.color.medium};- border-radius: ${themeCssVariables.border.radius.md};- bottom: calc(100% + 8px);- box-shadow: ${themeCssVariables.boxShadow.strong};- left: 0;- min-width: 280px;- position: absolute;- z-index: ${themeCssVariables.lastLayerZIndex};-`;--const StyledSection = styled.div`+const StyledFooter = styled.div`display: flex;- flex-direction: column;- gap: ${themeCssVariables.spacing[2]};- padding: ${themeCssVariables.spacing[3]};-`;--const StyledRow = styled.div`- align-items: center;- display: flex;- justify-content: space-between;-`;--const StyledContextWindowValue = styled.span`- color: ${themeCssVariables.font.color.secondary};- font-size: ${themeCssVariables.font.size.sm};- font-weight: ${themeCssVariables.font.weight.medium};+ justify-content: flex-end;+ padding-top: ${themeCssVariables.spacing[1]};`;-const StyledSectionTitle = styled.span`- color: ${themeCssVariables.font.color.primary};- font-size: ${themeCssVariables.font.size.xs};- font-weight: ${themeCssVariables.font.weight.semiBold};- padding-bottom: ${themeCssVariables.spacing[2]};-`;+export const AiChatContextUsageButton = () => {+ const { t } = useLingui();-const getCachedLabel = (lastMessage: AgentChatLastMessageUsage): string => {- if (lastMessage.cachedInputTokens <= 0 || lastMessage.inputTokens <= 0) {- return '';- }+ const shouldReduceMotion = useReducedMotion();- const cachedPercent = Math.round(- (lastMessage.cachedInputTokens / lastMessage.inputTokens) * 100,- );+ const [isOpen, setIsOpen] = useState(false);- return ` (${t`${cachedPercent}% cached`})`;-};+ const [showDetails, setShowDetails] = useState(false);-export const AiChatContextUsageButton = () => {- const { t } = useLingui();- const [isHovered, setIsHovered] = useState(false);const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+const agentChatUsage = useAtomComponentFamilyStateValue(agentChatUsageComponentFamilyState,{ threadId: currentAiChatThread },);- const billing = useAtomStateValue(billingState);- const isBillingEnabled = billing?.isBillingEnabled ?? false;- const { formatUsageValue } = useUsageValueFormatter();-- // Values from the streaming API arrive as display credits (micro-credits).- const formatChatCost = (displayCredits: number): string => {- if (isBillingEnabled) {- return `${formatUsageValue(displayCredits)}`;- }- const dollars = displayCredits / 1000;-- return `$${formatNumber(dollars, { decimals: 2 })}`;- };-- const hasMessages = useAtomComponentSelectorValue(- agentChatHasMessageComponentSelector,- );- if (!hasMessages) {- return null;- }+ const tiers = useAiModelTiers();- if (!agentChatUsage) {- return (- <StyledContainer>- <StyledTrigger hasUsage={false}>- <ContextUsageProgressRing percentage={0} />- </StyledTrigger>- </StyledContainer>- );- }+ const { chatTier } = useWorkspaceAiModelTiers();- const percentage = Math.min(- (agentChatUsage.conversationSize / agentChatUsage.contextWindowTokens) *- 100,- 100,+ const agentChatUserSelectedModelTier = useAtomStateValue(+ agentChatUserSelectedModelTierState,);- const formattedPercentage = percentage.toFixed(1);- const totalCredits =- agentChatUsage.inputCredits + agentChatUsage.outputCredits;- const lastMessage = agentChatUsage.lastMessage;++ const isWorkspaceSetupChat = useIsWorkspaceSetupChat();++ const modelTier = isWorkspaceSetupChat+ ? 'fast'+ : (agentChatUserSelectedModelTier ?? chatTier);++ const contextWindow =+ agentChatUsage?.contextWindowTokens ??+ tiers.find(({ tier }) => tier === modelTier)?.model?.contextWindowTokens ??+ 0;++ const conversationSize = agentChatUsage?.conversationSize ?? 0;++ const percentage =+ contextWindow > 0+ ? Math.min(100, Math.max(0, (conversationSize / contextWindow) * 100))+ : 0;++ const { data, loading, error } = useQuery(GetAiChatUsageDocument, {+ skip: !isOpen || isWorkspaceSetupChat,+ fetchPolicy: 'network-only',+ });++ const creditUsage = data?.aiChatUsage;++ const limitValue = isDefined(creditUsage)+ ? Number(creditUsage.limitValue)+ : null;++ const consumedValue = isDefined(creditUsage?.consumedValue)+ ? Number(creditUsage?.consumedValue)+ : null;++ const progress = isDefined(limitValue)+ ? computeUsageLimitProgress({ limitValue, consumedValue })+ : null;++ const creditPercentage =+ limitValue === 0 ? 100 : (progress?.consumedPercentage ?? null);++ const daysUntilReset = isDefined(creditUsage?.periodEnd)+ ? Math.max(+ 0,+ Math.ceil(+ (new Date(creditUsage.periodEnd).getTime() - Date.now()) / 86400000,+ ),+ )+ : null;++ const { refs, floatingStyles, context } = useFloating({+ open: isOpen,+ onOpenChange: (open) => {+ setIsOpen(open);+ if (open) {+ setShowDetails(false);+ }+ },+ placement: 'top-start',+ middleware: [offset(8), flip(), shift({ padding: 8 })],+ whileElementsMounted: autoUpdate,+ });++ const { isMounted, styles: transitionStyles } = useTransitionStyles(context, {+ duration: shouldReduceMotion ? 0 : { open: 150, close: 100 },+ initial: { opacity: 0 },+ });++ const hover = useHover(context, { handleClose: safePolygon() });++ const focus = useFocus(context);++ const click = useClick(context);++ const dismiss = useDismiss(context);++ const role = useRole(context, { role: 'dialog' });++ const { getReferenceProps, getFloatingProps } = useInteractions([+ hover,+ focus,+ click,+ dismiss,+ role,+ ]);return (- <StyledContainer- onMouseEnter={() => setIsHovered(true)}- onMouseLeave={() => setIsHovered(false)}- >- <StyledTrigger hasUsage={true}>+ <>+ <StyledTrigger+ ref={refs.setReference}+ type="button"+ aria-label={t`Context and usage`}+ // oxlint-disable-next-line react/jsx-props-no-spreading+ {...getReferenceProps()}+ ><ContextUsageProgressRing percentage={percentage} /></StyledTrigger>-- {isHovered && (- <StyledHoverCard>- <StyledSection>- <StyledSectionTitle>{t`Context window`}</StyledSectionTitle>- <StyledRow>- <StyledContextWindowValue>- {formattedPercentage}%- </StyledContextWindowValue>- <StyledContextWindowValue>- {formatNumber(agentChatUsage.conversationSize, {- abbreviate: true,- decimals: 1,- })}{' '}- /{' '}- {formatNumber(agentChatUsage.contextWindowTokens, {- abbreviate: true,- decimals: 1,- })}{' '}- {t`tokens`}- </StyledContextWindowValue>- </StyledRow>- <ProgressBar+ {isMounted && (+ <FloatingPortal>+ <StyledInformationCard+ ref={refs.setFloating}+ style={{ ...floatingStyles, ...transitionStyles }}+ aria-label={t`Context and usage`}+ // oxlint-disable-next-line react/jsx-props-no-spreading+ {...getFloatingProps()}+ >+ <UsageProgressRow+ Icon={IconWindow}+ label={t`Context window`}value={percentage}- barColor={- percentage > 80- ? themeCssVariables.color.red- : percentage > 60- ? themeCssVariables.color.orange- : themeCssVariables.color.blue+ valueLabel={+ contextWindow > 0+ ? `(${formatAiChatTokens(conversationSize)}/${formatAiChatTokens(contextWindow)}) ${formatNumber(percentage, { decimals: 1 })}%`+ : t`Not available`}- backgroundColor={themeCssVariables.background.tertiary}- withBorderRadius- />- </StyledSection>-- {isDefined(lastMessage) && (- <>- <HorizontalSeparator- noMargin- color={themeCssVariables.background.tertiary}- />- <StyledSection>- <StyledSectionTitle>{t`Last message`}</StyledSectionTitle>- <SettingsBillingLabelValueItem- label={t`Input tokens`}- value={`${formatNumber(lastMessage.inputTokens, {- abbreviate: true,- decimals: 1,- })}${getCachedLabel(lastMessage)}`}- />- <SettingsBillingLabelValueItem- label={t`Output tokens`}- value={formatNumber(lastMessage.outputTokens, {- abbreviate: true,- decimals: 1,- })}- />- <SettingsBillingLabelValueItem- label={t`Cost`}- value={formatChatCost(- lastMessage.inputCredits + lastMessage.outputCredits,- )}- />- </StyledSection>- </>- )}-- <HorizontalSeparator- noMargin- color={themeCssVariables.background.tertiary}- />- <StyledSection>- <StyledSectionTitle>{t`Conversation`}</StyledSectionTitle>- <SettingsBillingLabelValueItem- label={t`Input tokens`}- value={formatNumber(agentChatUsage.inputTokens, {- abbreviate: true,- decimals: 1,- })}- />- <SettingsBillingLabelValueItem- label={t`Output tokens`}- value={formatNumber(agentChatUsage.outputTokens, {- abbreviate: true,- decimals: 1,+ barColor={getUsageLimitRingColor({+ consumedPercentage: percentage,+ isExhausted: percentage >= 100,})}/>- <SettingsBillingLabelValueItem- label={t`Total cost`}- value={formatChatCost(totalCredits)}- />- </StyledSection>- </StyledHoverCard>+ {!isWorkspaceSetupChat && (+ <UsageProgressRow+ Icon={IconGauge}+ label={t`Usage`}+ value={+ loading || isDefined(error) ? 0 : (creditPercentage ?? 0)+ }+ valueLabel={getAiChatUsageLabel({+ loading,+ hasError: isDefined(error),+ hasUsage: isDefined(creditUsage),+ daysUntilReset,+ creditPercentage,+ })}+ barColor={getUsageLimitRingColor({+ consumedPercentage: creditPercentage ?? 0,+ isExhausted: creditPercentage === 100,+ })}+ />+ )}+ {showDetails && <AiChatContextUsageDetails />}+ {isDefined(agentChatUsage) && (+ <>+ <HorizontalSeparator noMargin />+ <StyledFooter>+ <Button+ title={showDetails ? t`Less` : t`More`}+ size="small"+ variant="secondary"+ onClick={() => setShowDetails(!showDetails)}+ />+ </StyledFooter>+ </>+ )}+ </StyledInformationCard>+ </FloatingPortal>)}- </StyledContainer>+ </>);};diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageDetails.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageDetails.tsxnew file mode 100644index 00000000000..2e3b26a25c5--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageDetails.tsx@@ -0,0 +1,119 @@+import { formatAiChatTokens } from '@/ai/utils/formatAiChatTokens';+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { isDefined } from 'twenty-shared/utils';+import { HorizontalSeparator } from 'twenty-ui/primitives/layout';+import {+ IconArrowUp,+ IconArrowDown,+ IconCoins,+ IconHistory,+} from 'twenty-ui/icon';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { UsageProgressRow } from '@/ui/feedback/progress-ring/components/UsageProgressRow';+import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { formatNumber } from '~/utils/format/formatNumber';++const StyledSection = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[1]};+`;++const StyledSectionTitle = styled.span`+ align-items: center;+ color: ${themeCssVariables.font.color.secondary};+ display: flex;+ font-size: ${themeCssVariables.font.size.xs};+ font-weight: ${themeCssVariables.font.weight.semiBold};+ height: 20px;+`;++export const AiChatContextUsageDetails = () => {+ const { t } = useLingui();+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+ const agentChatUsage = useAtomComponentFamilyStateValue(+ agentChatUsageComponentFamilyState,+ { threadId: currentAiChatThread },+ );+ if (!isDefined(agentChatUsage)) {+ return null;+ }++ const lastMessage = agentChatUsage.lastMessage;++ return (+ <>+ {isDefined(lastMessage) && (+ <>+ <HorizontalSeparator noMargin />+ <StyledSection>+ <StyledSectionTitle>{t`Last message`}</StyledSectionTitle>+ <UsageProgressRow+ Icon={IconArrowUp}+ label={t`Input tokens`}+ value={null}+ valueLabel={formatAiChatTokens(lastMessage.inputTokens)}+ />+ <UsageProgressRow+ Icon={IconHistory}+ label={t`Cached input`}+ value={null}+ valueLabel={formatAiChatTokens(lastMessage.cachedInputTokens)}+ />+ <UsageProgressRow+ Icon={IconArrowDown}+ label={t`Output tokens`}+ value={null}+ valueLabel={formatAiChatTokens(lastMessage.outputTokens)}+ />+ <UsageProgressRow+ Icon={IconCoins}+ label={t`Credits`}+ value={null}+ valueLabel={formatNumber(+ lastMessage.inputCredits + lastMessage.outputCredits,+ { decimals: 3 },+ )}+ />+ </StyledSection>+ </>+ )}+ <HorizontalSeparator noMargin />+ <StyledSection>+ <StyledSectionTitle>{t`Conversation`}</StyledSectionTitle>+ <UsageProgressRow+ Icon={IconArrowUp}+ label={t`Input tokens`}+ value={null}+ valueLabel={formatAiChatTokens(agentChatUsage.inputTokens)}+ />+ <UsageProgressRow+ Icon={IconHistory}+ label={t`Cached input`}+ value={null}+ valueLabel={formatAiChatTokens(agentChatUsage.cachedInputTokens)}+ />+ <UsageProgressRow+ Icon={IconArrowDown}+ label={t`Output tokens`}+ value={null}+ valueLabel={formatAiChatTokens(agentChatUsage.outputTokens)}+ />+ <UsageProgressRow+ Icon={IconCoins}+ label={t`Credits`}+ value={null}+ valueLabel={formatNumber(+ agentChatUsage.inputCredits + agentChatUsage.outputCredits,+ { decimals: 3 },+ )}+ />+ </StyledSection>+ </>+ );+};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.tsxnew file mode 100644index 00000000000..131887e082e--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/internal/__stories__/AiChatContextUsageButton.stories.tsx@@ -0,0 +1,163 @@+import { MockedProvider } from '@apollo/client/testing/react';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { createStore, Provider } from 'jotai';+import { type ReactNode, useState } from 'react';+import { expect, userEvent, waitFor, within } from 'storybook/test';+import { ComponentDecorator } from 'twenty-ui/testing';+import { AiChatContextUsageButton } from '@/ai/components/internal/AiChatContextUsageButton';+import { AiChatContextUsageDetails } from '@/ai/components/internal/AiChatContextUsageDetails';+import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';+import {+ agentChatUsageComponentFamilyState,+ type AgentChatUsageState,+} from '@/ai/states/agentChatUsageComponentFamilyState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { GetAiChatUsageDocument } from '~/generated-metadata/graphql';++const USAGE: AgentChatUsageState = {+ conversationSize: 200000,+ contextWindowTokens: 1000000,+ inputTokens: 200000,+ outputTokens: 40000,+ cachedInputTokens: 75000,+ inputCredits: 80,+ outputCredits: 20,+ lastMessage: {+ inputTokens: 100000,+ outputTokens: 20000,+ cachedInputTokens: 50000,+ inputCredits: 40,+ outputCredits: 10,+ },+};++const UsageStory = ({+ usage = null,+ limit = 1000,+ consumed = 800,+ error = false,+ loading = false,+ children,+}: {+ usage?: AgentChatUsageState | null;+ limit?: number | null;+ consumed?: number | null;+ error?: boolean;+ loading?: boolean;+ children?: ReactNode;+}) => {+ const [store] = useState(() => {+ const storyStore = createStore();+ storyStore.set(currentAiChatThreadState.atom, 'story-thread');+ storyStore.set(+ agentChatUsageComponentFamilyState.atomFamily({+ instanceId: 'usage-story',+ familyKey: { threadId: 'story-thread' },+ }),+ usage,+ );+ return storyStore;+ });+ return (+ <Provider store={store}>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: 'usage-story' }}+ >+ <MockedProvider+ mocks={[+ {+ request: { query: GetAiChatUsageDocument },+ maxUsageCount: Infinity,+ delay: loading ? Infinity : 0,+ ...(error+ ? { error: new Error('Usage unavailable') }+ : {+ result: {+ data: {+ aiChatUsage:+ limit === null+ ? null+ : {+ limitValue: limit,+ consumedValue: consumed,+ periodEnd: null,+ },+ },+ },+ }),+ },+ ]}+ >+ {children ?? <AiChatContextUsageButton />}+ </MockedProvider>+ </AgentChatComponentInstanceContext.Provider>+ </Provider>+ );+};++const meta = {+ title: 'Modules/AI/AiChatContextUsageButton',+ component: AiChatContextUsageButton,+ decorators: [ComponentDecorator],+ parameters: { container: { width: 400, height: 650 } },+} satisfies Meta<typeof AiChatContextUsageButton>;+export default meta;+type Story = StoryObj<typeof meta>;++export const NewChat: Story = {+ render: () => <UsageStory />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const page = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ canvas.getByRole('button', { name: 'Context and usage' }),+ );+ await waitFor(() => expect(page.getByText('80%')).toBeVisible());+ await expect(+ page.queryByRole('button', { name: /^More/ }),+ ).not.toBeInTheDocument();+ await userEvent.keyboard('{Escape}');+ await waitFor(() =>+ expect(page.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ },+};+export const Expanded: Story = {+ render: () => <UsageStory usage={USAGE} />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const page = within(canvasElement.ownerDocument.body);+ await userEvent.tab();+ await waitFor(() => expect(page.getByRole('dialog')).toBeVisible());+ await userEvent.click(page.getByRole('button', { name: /^More/ }));+ await expect(page.getByText('Last message')).toBeVisible();+ await expect(page.getByText('Conversation')).toBeVisible();+ await expect(page.getAllByText('Cached input')).toHaveLength(2);+ await expect(page.getByText('50k')).toBeVisible();+ await expect(page.getByText('75k')).toBeVisible();+ await userEvent.click(page.getByRole('button', { name: /^Less/ }));+ await expect(page.queryByText('Last message')).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Context and usage' }),+ );+ },+};+export const ReopenedConversation: Story = {+ render: () => <UsageStory usage={{ ...USAGE, lastMessage: null }} />,+};+export const NoLimit: Story = { render: () => <UsageStory limit={null} /> };+export const UnknownConsumption: Story = {+ render: () => <UsageStory consumed={null} />,+};+export const Exhausted: Story = {+ render: () => <UsageStory limit={0} consumed={0} />,+};+export const Unavailable: Story = { render: () => <UsageStory error /> };+export const Loading: Story = { render: () => <UsageStory loading /> };+export const Details: Story = {+ render: () => (+ <UsageStory usage={USAGE}>+ <AiChatContextUsageDetails />+ </UsageStory>+ ),+};diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getAiChatUsage.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getAiChatUsage.tsnew file mode 100644index 00000000000..f75cefc042a--- /dev/null+++ b/packages/twenty-front/src/modules/ai/graphql/queries/getAiChatUsage.ts@@ -0,0 +1,11 @@+import { gql } from '@apollo/client';++export const GET_AI_CHAT_USAGE = gql`+ query GetAiChatUsage {+ aiChatUsage {+ limitValue+ consumedValue+ periodEnd+ }+ }+`;diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.tsindex e47fd5922e7..c8df6eb83f0 100644--- a/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.ts+++ b/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.ts@@ -5,6 +5,7 @@ export const GET_CHAT_THREADS = gql`chatThreads {idtitle+ totalCacheReadTokenstotalInputTokenstotalOutputTokenscontextWindowTokensdiff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsxindex 94ed1ccbcbf..f5c9eeb47d8 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx@@ -23,6 +23,7 @@ const buildThread = (id: string, title: string): AgentChatThread => ({lastMessageAt: '2026-09-07T00:00:00.000Z',totalInputTokens: 0,totalOutputTokens: 0,+ totalCacheReadTokens: 0,conversationSize: 0,totalInputCredits: 0,totalOutputCredits: 0,diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsxindex 37d081ac534..abd9661da9d 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx@@ -1,3 +1,7 @@+import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';+import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { type AgentChatThread } from '~/generated-metadata/graphql';import { act, renderHook } from '@testing-library/react';import { Provider as JotaiProvider } from 'jotai';import { type ReactNode } from 'react';@@ -57,4 +61,41 @@ describe('useSelectAiChatThread', () => {true,);});+ it('restores usage from an archived thread and preserves it on reselection', () => {+ const thread = {+ id: 'archived-thread',+ deletedAt: '2026-09-01',+ createdAt: '2026-08-01',+ updatedAt: '2026-09-01',+ conversationSize: 120,+ contextWindowTokens: 1000,+ totalInputTokens: 250,+ totalOutputTokens: 30,+ totalCacheReadTokens: 80,+ totalInputCredits: 0.125,+ totalOutputCredits: 0.05,+ } satisfies AgentChatThread;+ const metadataAtom = metadataStoreState.atomFamily('agentChatThreads');+ jotaiStore.set(metadataAtom, {+ ...jotaiStore.get(metadataAtom),+ current: [thread],+ });+ const usageAtom = agentChatUsageComponentFamilyState.atomFamily({+ instanceId: AGENT_CHAT_INSTANCE_ID,+ familyKey: { threadId: thread.id },+ });+ const { result } = renderHook(() => useSelectAiChatThread(), {+ wrapper: Wrapper,+ });+ act(() => result.current.selectAiChatThread(thread.id));+ expect(jotaiStore.get(usageAtom)).toMatchObject({+ inputTokens: 250,+ cachedInputTokens: 80,+ lastMessage: null,+ });+ const liveUsage = { ...jotaiStore.get(usageAtom)!, inputTokens: 500 };+ jotaiStore.set(usageAtom, liveUsage);+ act(() => result.current.selectAiChatThread(thread.id));+ expect(jotaiStore.get(usageAtom)).toEqual(liveUsage);+ });});diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.tsindex ec2b25e204b..09b536c67a1 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts@@ -269,6 +269,8 @@ export const useAgentChatSubscription = (threadId: string | null) => {inputCredits: usage.inputCredits,outputCredits: usage.outputCredits,},+ cachedInputTokens:+ (prev?.cachedInputTokens ?? 0) + usage.cachedInputTokens,conversationSize: usage.conversationSize,contextWindowTokens: model.contextWindowTokens,inputTokens: (prev?.inputTokens ?? 0) + usage.inputTokens,diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.tsindex 46ff82f1f8e..3762fb66016 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts@@ -1,4 +1,3 @@-import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';import { currentAiChatThreadTitleComponentFamilyState } from '@/ai/states/currentAiChatThreadTitleComponentFamilyState';import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';@@ -6,7 +5,6 @@ import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageimport { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { useStore } from 'jotai';-import { isDefined } from 'twenty-shared/utils';import { type AgentChatThread } from '~/generated-metadata/graphql';import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';@@ -25,9 +23,6 @@ export const useAiChatThreadClick = (const threadTitleFamilyCallback = useAtomComponentFamilyStateCallbackState(currentAiChatThreadTitleComponentFamilyState,);- const agentChatUsageFamilyCallback = useAtomComponentFamilyStateCallbackState(- agentChatUsageComponentFamilyState,- );const store = useStore();const { openAskAiPage } = useOpenAskAiPageInSidePanel();@@ -43,24 +38,6 @@ export const useAiChatThreadClick = (thread.title ?? null,);- const hasUsageData =- (thread.conversationSize ?? 0) > 0 &&- isDefined(thread.contextWindowTokens);- store.set(- agentChatUsageFamilyCallback(clickedFamilyKey),- hasUsageData- ? {- lastMessage: null,- conversationSize: thread.conversationSize ?? 0,- contextWindowTokens: thread.contextWindowTokens ?? 0,- inputTokens: thread.totalInputTokens,- outputTokens: thread.totalOutputTokens,- inputCredits: thread.totalInputCredits,- outputCredits: thread.totalOutputCredits,- }- : null,- );-if (isCurrentPathAiChatPage()) {return;}diff --git a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.tsindex 019d3847036..0c71952a00e 100644--- a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts@@ -43,6 +43,7 @@ export const useCreateAgentChatThread = () => {contextWindowTokens: null,totalInputTokens: 0,totalOutputTokens: 0,+ totalCacheReadTokens: 0,totalInputCredits: 0,totalOutputCredits: 0,};diff --git a/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts b/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.tsindex d5e5c354948..37b88c94a36 100644--- a/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts@@ -1,3 +1,9 @@+import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';+import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { getAgentChatUsageFromThread } from '@/ai/utils/getAgentChatUsageFromThread';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';+import { type AgentChatThread } from '~/generated-metadata/graphql';import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';import { agentChatInputState } from '@/ai/states/agentChatInputState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';@@ -5,7 +11,7 @@ import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { useStore } from 'jotai';import { useCallback } from 'react';-import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';+import { isDefined, tipTapDocumentToMarkdown } from 'twenty-shared/utils';export const useSwitchAgentChatThreadWithDraft = () => {const [currentAiChatThread, setCurrentAiChatThread] = useAtomState(@@ -13,6 +19,10 @@ export const useSwitchAgentChatThreadWithDraft = () => {);const setAgentChatInput = useSetAtomState(agentChatInputState);const store = useStore();+ const usageFamilyCallback = useAtomComponentFamilyStateCallbackState(+ agentChatUsageComponentFamilyState,+ AGENT_CHAT_INSTANCE_ID,+ );const switchThreadWithDraft = useCallback((toThreadId: string) => {@@ -21,12 +31,26 @@ export const useSwitchAgentChatThreadWithDraft = () => {setCurrentAiChatThread(toThreadId);if (!isSameThread) {+ const threads = store.get(+ metadataStoreState.atomFamily('agentChatThreads'),+ ).current as AgentChatThread[];+ const thread = threads.find(({ id }) => id === toThreadId);+ store.set(+ usageFamilyCallback({ threadId: toThreadId }),+ isDefined(thread) ? getAgentChatUsageFromThread(thread) : null,+ );const destinationDraft =store.get(agentChatDraftsByThreadIdState.atom)[toThreadId] ?? '';setAgentChatInput(tipTapDocumentToMarkdown(destinationDraft));}},- [currentAiChatThread, setCurrentAiChatThread, setAgentChatInput, store],+ [+ currentAiChatThread,+ setCurrentAiChatThread,+ setAgentChatInput,+ store,+ usageFamilyCallback,+ ],);return { switchThreadWithDraft };diff --git a/packages/twenty-front/src/modules/ai/states/agentChatUsageComponentFamilyState.ts b/packages/twenty-front/src/modules/ai/states/agentChatUsageComponentFamilyState.tsindex 9fbfe1ae23a..7791d1b42c5 100644--- a/packages/twenty-front/src/modules/ai/states/agentChatUsageComponentFamilyState.ts+++ b/packages/twenty-front/src/modules/ai/states/agentChatUsageComponentFamilyState.ts@@ -11,6 +11,7 @@ export type AgentChatLastMessageUsage = {export type AgentChatUsageState = {lastMessage: AgentChatLastMessageUsage | null;+ cachedInputTokens: number;conversationSize: number;contextWindowTokens: number;inputTokens: number;diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatUsageFromThread.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatUsageFromThread.test.tsnew file mode 100644index 00000000000..ee4920e110a--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatUsageFromThread.test.ts@@ -0,0 +1,32 @@+import { getAgentChatUsageFromThread } from '@/ai/utils/getAgentChatUsageFromThread';++const storedThread = {+ conversationSize: 120,+ contextWindowTokens: 1000,+ totalInputTokens: 250,+ totalOutputTokens: 30,+ totalCacheReadTokens: 80,+ totalInputCredits: 0.125,+ totalOutputCredits: 0.05,+};++describe('getAgentChatUsageFromThread', () => {+ it('restores cumulative usage without restoring the last message', () => {+ expect(getAgentChatUsageFromThread(storedThread)).toEqual({+ conversationSize: 120,+ contextWindowTokens: 1000,+ inputTokens: 250,+ outputTokens: 30,+ cachedInputTokens: 80,+ inputCredits: 0.125,+ outputCredits: 0.05,+ lastMessage: null,+ });+ });++ it('does not show a breakdown for an unused thread', () => {+ expect(+ getAgentChatUsageFromThread({ ...storedThread, conversationSize: 0 }),+ ).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatUsageLabel.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatUsageLabel.test.tsnew file mode 100644index 00000000000..c497a587d32--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatUsageLabel.test.ts@@ -0,0 +1,35 @@+import { getAiChatUsageLabel } from '@/ai/utils/getAiChatUsageLabel';++const base = {+ loading: false,+ hasError: false,+ hasUsage: true,+ daysUntilReset: null as number | null,+ creditPercentage: 80 as number | null,+};++describe('getAiChatUsageLabel', () => {+ it.each<[number, string]>([+ [1, 'Reset in 1 day (80%)'],+ [2, 'Reset in 2 days (80%)'],+ [0, 'Reset in 0 days (80%)'],+ ])('pluralizes %s days', (daysUntilReset, expected) => {+ expect(getAiChatUsageLabel({ ...base, daysUntilReset })).toBe(expected);+ });++ it('shows the bare percentage when no reset date applies', () => {+ expect(getAiChatUsageLabel(base)).toBe('80%');+ });++ it('distinguishes unavailable consumption from no limit', () => {+ expect(getAiChatUsageLabel({ ...base, creditPercentage: null })).toBe('—');+ expect(getAiChatUsageLabel({ ...base, hasUsage: false })).toBe('No limit');+ });++ it('prioritizes loading and errors over stale data', () => {+ expect(getAiChatUsageLabel({ ...base, loading: true })).toBe('Loading…');+ expect(getAiChatUsageLabel({ ...base, hasError: true })).toBe(+ 'Not available',+ );+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.tsindex db6367bf4ee..bf0b2ab69dc 100644--- a/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts@@ -25,6 +25,7 @@ describe('groupThreadsByDate', () => {createdAt: twoDaysAgo.toISOString(),totalInputTokens: 0,totalOutputTokens: 0,+ totalCacheReadTokens: 0,contextWindowTokens: null,conversationSize: 0,totalInputCredits: 0,diff --git a/packages/twenty-front/src/modules/ai/utils/formatAiChatTokens.ts b/packages/twenty-front/src/modules/ai/utils/formatAiChatTokens.tsnew file mode 100644index 00000000000..5c70530cf13--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/formatAiChatTokens.ts@@ -0,0 +1,4 @@+import { formatNumber } from '~/utils/format/formatNumber';++export const formatAiChatTokens = (tokens: number) =>+ formatNumber(tokens, { abbreviate: true, decimals: 1 });diff --git a/packages/twenty-front/src/modules/ai/utils/getAgentChatUsageFromThread.ts b/packages/twenty-front/src/modules/ai/utils/getAgentChatUsageFromThread.tsnew file mode 100644index 00000000000..7f0789bfff5--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAgentChatUsageFromThread.ts@@ -0,0 +1,30 @@+import { isDefined } from 'twenty-shared/utils';+import { type AgentChatUsageState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { type AgentChatThread } from '~/generated-metadata/graphql';++export const getAgentChatUsageFromThread = (+ thread: Pick<+ AgentChatThread,+ | 'totalCacheReadTokens'+ | 'conversationSize'+ | 'contextWindowTokens'+ | 'totalInputTokens'+ | 'totalOutputTokens'+ | 'totalInputCredits'+ | 'totalOutputCredits'+ >,+): AgentChatUsageState | null => {+ if (thread.conversationSize <= 0 || !isDefined(thread.contextWindowTokens)) {+ return null;+ }+ return {+ lastMessage: null,+ cachedInputTokens: thread.totalCacheReadTokens,+ conversationSize: thread.conversationSize,+ contextWindowTokens: thread.contextWindowTokens,+ inputTokens: thread.totalInputTokens,+ outputTokens: thread.totalOutputTokens,+ inputCredits: thread.totalInputCredits,+ outputCredits: thread.totalOutputCredits,+ };+};diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatUsageLabel.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatUsageLabel.tsnew file mode 100644index 00000000000..d8120276216--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatUsageLabel.ts@@ -0,0 +1,41 @@+import { plural, t } from '@lingui/core/macro';+import { isDefined } from 'twenty-shared/utils';+import { formatNumber } from '~/utils/format/formatNumber';++export const getAiChatUsageLabel = ({+ loading,+ hasError,+ hasUsage,+ daysUntilReset,+ creditPercentage,+}: {+ loading: boolean;+ hasError: boolean;+ hasUsage: boolean;+ daysUntilReset: number | null;+ creditPercentage: number | null;+}): string => {+ if (loading) {+ return t`Loading…`;+ }++ if (hasError) {+ return t`Not available`;+ }++ if (!hasUsage) {+ return t`No limit`;+ }++ if (!isDefined(creditPercentage)) {+ return '—';+ }++ const percentage = formatNumber(creditPercentage, { decimals: 1 });++ if (!isDefined(daysUntilReset)) {+ return `${percentage}%`;+ }++ return t`Reset in ${plural(daysUntilReset, { one: '# day', other: '# days' })} (${percentage}%)`;+};diff --git a/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatKickoffEffect.tsx b/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatKickoffEffect.tsxindex 7a5801d7525..53e071353cf 100644--- a/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatKickoffEffect.tsx+++ b/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatKickoffEffect.tsx@@ -93,6 +93,7 @@ export const WorkspaceSetupChatKickoffEffect = () => {updatedAt: thread.updatedAt,conversationSize: thread.conversationSize,contextWindowTokens: thread.contextWindowTokens ?? null,+ totalCacheReadTokens: thread.totalCacheReadTokens,totalInputTokens: thread.totalInputTokens,totalOutputTokens: thread.totalOutputTokens,totalInputCredits: thread.totalInputCredits,diff --git a/packages/twenty-front/src/modules/onboarding/graphql/mutations/startWorkspaceSetupChat.ts b/packages/twenty-front/src/modules/onboarding/graphql/mutations/startWorkspaceSetupChat.tsindex efc87753edd..31bbafe7f1d 100644--- a/packages/twenty-front/src/modules/onboarding/graphql/mutations/startWorkspaceSetupChat.ts+++ b/packages/twenty-front/src/modules/onboarding/graphql/mutations/startWorkspaceSetupChat.ts@@ -13,6 +13,7 @@ export const START_WORKSPACE_SETUP_CHAT = gql`thread {idtitle+ totalCacheReadTokenstotalInputTokenstotalOutputTokenscontextWindowTokensdiff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitsTable.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitsTable.tsxindex a1525cac7ec..fd796467f4c 100644--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitsTable.tsx+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitsTable.tsx@@ -18,14 +18,12 @@ import { getUsageLimitRingColor } from '@/settings/billing/utils/getUsageLimitRiimport { SettingsEmptyPlaceholder } from '@/settings/components/SettingsEmptyPlaceholder';import { SettingsNameCellSecondaryLabel } from '@/settings/components/SettingsNameCellSecondaryLabel';import { SettingsTableListSection } from '@/settings/components/SettingsTableListSection';-import { ProgressRing } from '@/ui/feedback/progress-ring/components/ProgressRing';+import { ProgressRingWithLabel } from '@/ui/feedback/progress-ring/components/ProgressRingWithLabel';import { type UsageResourceType } from '~/generated-metadata/graphql';import { useNavigateSettings } from '~/hooks/useNavigateSettings';const GRID_AUTO_COLUMNS = '1.2fr 1fr 120px 96px';-const USED_RING_SIZE = 14;-const StyledCell = styled.div`align-items: center;display: flex;@@ -124,17 +122,13 @@ const UsedCell = ({ item }: { item: UsageLimitRow }) => {return (<StyledUsed id={anchorId}>{isDefined(item.consumedPercentage) ? (- <>- <span>{item.consumedPercentage}%</span>- <ProgressRing- size={USED_RING_SIZE}- value={item.consumedPercentage}- barColor={getUsageLimitRingColor({- consumedPercentage: item.consumedPercentage,- isExhausted: item.isExhausted,- })}- />- </>+ <ProgressRingWithLabel+ value={item.consumedPercentage}+ barColor={getUsageLimitRingColor({+ consumedPercentage: item.consumedPercentage,+ isExhausted: item.isExhausted,+ })}+ />) : (<StyledEmptyValue>—</StyledEmptyValue>)}diff --git a/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/ProgressRingWithLabel.tsx b/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/ProgressRingWithLabel.tsxnew file mode 100644index 00000000000..24ae754d647--- /dev/null+++ b/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/ProgressRingWithLabel.tsx@@ -0,0 +1,31 @@+import { styled } from '@linaria/react';+import { type ReactNode } from 'react';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import { ProgressRing } from '@/ui/feedback/progress-ring/components/ProgressRing';++type ProgressRingWithLabelProps = {+ value: number;+ label?: ReactNode;+ barColor?: string;+};++const StyledContainer = styled.div`+ align-items: center;+ display: flex;+ flex-shrink: 0;+ gap: ${themeCssVariables.spacing[2]};+ justify-content: flex-end;+ white-space: nowrap;+`;++export const ProgressRingWithLabel = ({+ value,+ label,+ barColor,+}: ProgressRingWithLabelProps) => (+ <StyledContainer>+ <span>{label ?? `${value}%`}</span>+ <ProgressRing size={14} value={value} barColor={barColor} />+ </StyledContainer>+);diff --git a/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/UsageProgressRow.tsx b/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/UsageProgressRow.tsxnew file mode 100644index 00000000000..2a6f245a997--- /dev/null+++ b/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/UsageProgressRow.tsx@@ -0,0 +1,58 @@+import { isDefined } from 'twenty-shared/utils';+import { styled } from '@linaria/react';+import { type ReactNode } from 'react';+import { type IconComponent } from 'twenty-ui/icon';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import { ProgressRingWithLabel } from '@/ui/feedback/progress-ring/components/ProgressRingWithLabel';++type UsageProgressRowProps = {+ Icon: IconComponent;+ label: string;+ value: number | null;+ valueLabel?: ReactNode;+ barColor?: string;+};++const StyledRow = styled.div`+ align-items: center;+ color: ${themeCssVariables.font.color.primary};+ display: flex;+ font-size: ${themeCssVariables.font.size.sm};+ font-weight: ${themeCssVariables.font.weight.medium};+ gap: ${themeCssVariables.spacing[2]};+ min-height: 24px;+`;++const StyledLabel = styled.div`+ align-items: center;+ color: ${themeCssVariables.font.color.tertiary};+ display: flex;+ flex: 1;+ gap: ${themeCssVariables.spacing[1]};+ min-width: 0;+`;++export const UsageProgressRow = ({+ Icon,+ label,+ value,+ valueLabel,+ barColor,+}: UsageProgressRowProps) => (+ <StyledRow>+ <StyledLabel>+ <Icon size={14} />+ <span>{label}</span>+ </StyledLabel>+ {!isDefined(value) ? (+ <span>{valueLabel ?? '—'}</span>+ ) : (+ <ProgressRingWithLabel+ value={value}+ label={valueLabel}+ barColor={barColor}+ />+ )}+ </StyledRow>+);diff --git a/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/__stories__/ProgressRingWithLabel.stories.tsx b/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/__stories__/ProgressRingWithLabel.stories.tsxnew file mode 100644index 00000000000..b907f289a03--- /dev/null+++ b/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/__stories__/ProgressRingWithLabel.stories.tsx@@ -0,0 +1,15 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { ComponentDecorator } from 'twenty-ui/testing';+import { ProgressRingWithLabel } from '@/ui/feedback/progress-ring/components/ProgressRingWithLabel';+const meta = {+ title: 'UI/Feedback/ProgressRingWithLabel',+ component: ProgressRingWithLabel,+ decorators: [ComponentDecorator],+ args: { value: 80 },+} satisfies Meta<typeof ProgressRingWithLabel>;+export default meta;+type Story = StoryObj<typeof meta>;+export const Default: Story = {};+export const Empty: Story = { args: { value: 0, label: 'No limit' } };+export const Full: Story = { args: { value: 100 } };+export const LongLabel: Story = { args: { label: 'Reset in 14 days (80%)' } };diff --git a/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/__stories__/UsageProgressRow.stories.tsx b/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/__stories__/UsageProgressRow.stories.tsxnew file mode 100644index 00000000000..7793f0d9f61--- /dev/null+++ b/packages/twenty-front/src/modules/ui/feedback/progress-ring/components/__stories__/UsageProgressRow.stories.tsx@@ -0,0 +1,17 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { IconGauge } from 'twenty-ui/icon';+import { ComponentDecorator } from 'twenty-ui/testing';+import { UsageProgressRow } from '@/ui/feedback/progress-ring/components/UsageProgressRow';+const meta = {+ title: 'UI/Feedback/UsageProgressRow',+ component: UsageProgressRow,+ decorators: [ComponentDecorator],+ parameters: { container: { width: 300 } },+ args: { Icon: IconGauge, label: 'Usage', value: 80 },+} satisfies Meta<typeof UsageProgressRow>;+export default meta;+type Story = StoryObj<typeof meta>;+export const Default: Story = {};+export const PlainValue: Story = { args: { value: null, valueLabel: '100k' } };+export const NoLimit: Story = { args: { value: 0, valueLabel: 'No limit' } };+export const Exhausted: Story = { args: { value: 100 } };diff --git a/packages/twenty-front/src/modules/ui/layout/information-card/components/StyledInformationCard.tsx b/packages/twenty-front/src/modules/ui/layout/information-card/components/StyledInformationCard.tsxnew file mode 100644index 00000000000..35647f0a052--- /dev/null+++ b/packages/twenty-front/src/modules/ui/layout/information-card/components/StyledInformationCard.tsx@@ -0,0 +1,18 @@+import { styled } from '@linaria/react';+import { themeCssVariables } from 'twenty-ui/theme-constants';++export const StyledInformationCard = styled.div`+ backdrop-filter: blur(20px);+ background: ${themeCssVariables.background.transparent.secondary};+ border: 1px solid ${themeCssVariables.border.color.medium};+ border-radius: ${themeCssVariables.border.radius.md};+ box-shadow: ${themeCssVariables.boxShadow.strong};+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[1]};+ max-width: calc(100vw - 16px);+ padding: ${themeCssVariables.spacing[2]};+ width: 300px;+ z-index: ${themeCssVariables.lastLayerZIndex};+`;diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.tsindex ff53ba1d5a1..a50fc509576 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts@@ -676,6 +676,50 @@ describe('UsageLimitQuotaService', () => {});});+ describe('getAllowanceUsage', () => {+ it('reports consumption and reset from the allowance counter', async () => {+ setAllowance(2000);+ cacheStorage.mget.mockResolvedValue([1500]);+ await expect(service.getAllowanceUsage('workspace-1')).resolves.toEqual({+ limitValue: 2000,+ consumedValue: 500,+ periodEnd: ALLOWANCE_PERIOD.periodEnd,+ });+ });++ it('preserves unavailable consumption instead of reporting zero usage', async () => {+ setAllowance(2000);+ cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));+ await expect(service.getAllowanceUsage('workspace-1')).resolves.toEqual({+ limitValue: 2000,+ consumedValue: null,+ periodEnd: ALLOWANCE_PERIOD.periodEnd,+ });+ });++ it('reports unknown consumption when the allowance period changes', async () => {+ setAllowance(2000);+ creditAllowanceProvider.getCreditAllowance.mockResolvedValue({+ ...ALLOWANCE_PERIOD,+ periodStart: new Date('2026-09-15T09:00:00.000Z'),+ allowanceMicro: 2000,+ });+ await expect(service.getAllowanceUsage('workspace-1')).resolves.toEqual({+ limitValue: 2000,+ consumedValue: null,+ periodEnd: ALLOWANCE_PERIOD.periodEnd,+ });+ expect(cacheStorage.mget).not.toHaveBeenCalled();+ });++ it('returns no limit when the allowance is disabled', async () => {+ creditAllowanceProvider.isCreditAllowanceEnabled.mockResolvedValue(false);+ await expect(+ service.getAllowanceUsage('workspace-1'),+ ).resolves.toBeNull();+ });+ });+describe('getAllowanceRemainingMicro', () => {it('reads the warm allowance counter', async () => {setAllowance(2_000_000);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.tsindex ffa090e8045..ba651d5f7ef 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@@ -205,6 +205,54 @@ export class UsageLimitQuotaService implements OnModuleInit {});}+ async getAllowanceUsage(workspaceId: string): Promise<{+ limitValue: number;+ consumedValue: number | null;+ periodEnd: Date;+ } | null> {+ const counter = await this.buildAllowanceCounter(workspaceId);++ if (!isDefined(counter)) {+ return null;+ }++ const allowance =+ await this.creditAllowanceProvider.getCreditAllowance(workspaceId);++ if (!isDefined(allowance)) {+ return null;+ }++ if (allowance.periodStart.getTime() !== counter.periodStart.getTime()) {+ return {+ limitValue: allowance.allowanceMicro,+ consumedValue: null,+ periodEnd: allowance.periodEnd,+ };+ }++ let consumedValue: number | null = null;++ try {+ const [remaining] = await this.readRemainings({+ workspaceId,+ counters: [counter],+ });++ consumedValue = isDefined(remaining)+ ? Math.max(0, allowance.allowanceMicro - remaining)+ : null;+ } catch (error) {+ this.admitOnFailure({ error, workspaceId, admitted: null });+ }++ return {+ limitValue: allowance.allowanceMicro,+ consumedValue,+ periodEnd: allowance.periodEnd,+ };+ }+async getAllowanceRemainingMicro(workspaceId: string,): Promise<number | null> {diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.tsindex 54b8474b5d4..94dfc4effbb 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts@@ -59,6 +59,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheprovideWorkspaceScopedRepository(LogicFunctionEntity),],exports: [+ UsageLimitEntitlementService,UsageLimitQuotaService,UsageLimitSpeedService,UsageLimitsCacheService,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.tsindex ba14864a303..37743f4e1ba 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts@@ -1,3 +1,6 @@+import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';+import { AiChatUsageService } from 'src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service';+import { AiChatUsageResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/ai-chat-usage.resolver';import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';@@ -44,6 +47,7 @@ import { SystemPromptBuilderService } from './services/system-prompt-builder.ser@Module({imports: [+ UsageLimitModule,TypeOrmModule.forFeature([AgentChatThreadEntity,FileEntity,@@ -68,6 +72,8 @@ import { SystemPromptBuilderService } from './services/system-prompt-builder.serWorkflowToolsModule,],providers: [+ AiChatUsageService,+ AiChatUsageResolver,AgentChatCancelSubscriberService,AgentChatEventPublisherService,AgentChatStreamHeartbeatService,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto.tsindex 2d69961b2a0..b68f7bd1fc9 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto.ts@@ -8,6 +8,9 @@ export class AgentChatThreadDTO {@Field({ nullable: true })title: string;+ @Field(() => Int)+ totalCacheReadTokens: number;+@Field(() => Int)totalInputTokens: number;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.tsnew file mode 100644index 00000000000..acf2bf0a122--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto.ts@@ -0,0 +1,14 @@+import { Field, ObjectType } from '@nestjs/graphql';+import { GraphQLBigInt } from 'graphql-scalars';++@ObjectType('AiChatUsage')+export class AiChatUsageDTO {+ @Field(() => GraphQLBigInt)+ limitValue: number;++ @Field(() => GraphQLBigInt, { nullable: true })+ consumedValue: number | null;++ @Field(() => Date, { nullable: true })+ periodEnd: Date | null;+}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity.tsindex f66298dbd29..fda0ff87697 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity.ts@@ -13,6 +13,7 @@ import {import { ADD_LAST_STREAM_ERROR_TO_AGENT_CHAT_THREAD_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-19/add-last-stream-error-to-agent-chat-thread-upgrade-command-name.constant';import { ADD_PENDING_QUESTION_MESSAGE_ID_TO_AGENT_CHAT_THREAD_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-19/add-pending-question-message-id-to-agent-chat-thread-upgrade-command-name.constant';import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';+import { nullableBigintColumnTransformer } from 'src/engine/core-modules/usage-limit/utils/nullable-bigint-column-transformer.util';import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';import { AgentMessageEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';import { AgentTurnEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-turn.entity';@@ -59,16 +60,32 @@ export class AgentChatThreadEntity {@Column({ type: 'int', default: 0 })conversationSize: number;- @Column({ type: 'bigint', default: 0 })+ @Column({+ type: 'bigint',+ default: 0,+ transformer: nullableBigintColumnTransformer,+ })totalInputCredits: number;- @Column({ type: 'bigint', default: 0 })+ @Column({+ type: 'bigint',+ default: 0,+ transformer: nullableBigintColumnTransformer,+ })totalOutputCredits: number;- @Column({ type: 'bigint', default: 0 })+ @Column({+ type: 'bigint',+ default: 0,+ transformer: nullableBigintColumnTransformer,+ })totalCacheReadTokens: number;- @Column({ type: 'bigint', default: 0 })+ @Column({+ type: 'bigint',+ default: 0,+ transformer: nullableBigintColumnTransformer,+ })totalCacheCreationTokens: number;@Column({ type: 'varchar', nullable: true })diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/ai-chat-usage.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/ai-chat-usage.resolver.tsnew file mode 100644index 00000000000..f98d793f549--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/ai-chat-usage.resolver.ts@@ -0,0 +1,28 @@+import { UseFilters, UseGuards } from '@nestjs/common';+import { Query } from '@nestjs/graphql';+import { PermissionFlagType } from 'twenty-shared/constants';++import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';+import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';+import { AiChatUsageDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto';+import { AiChatUsageService } from 'src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service';+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';+import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';++@MetadataResolver(() => AiChatUsageDTO)+@UseGuards(WorkspaceAuthGuard, SettingsPermissionGuard(PermissionFlagType.AI))+@UseFilters(PreventNestToAutoLogGraphqlErrorsFilter)+export class AiChatUsageResolver {+ constructor(private readonly aiChatUsageService: AiChatUsageService) {}++ @Query(() => AiChatUsageDTO, { nullable: true })+ async aiChatUsage(+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUserWorkspaceId() userWorkspaceId: string,+ ): Promise<AiChatUsageDTO | null> {+ return this.aiChatUsageService.findUsage({ workspaceId, userWorkspaceId });+ }+}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.tsnew file mode 100644index 00000000000..7749e8ee3e1--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service.ts@@ -0,0 +1,48 @@+import { Injectable } from '@nestjs/common';++import { type AiChatUsageDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto';+import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { findAiChatCreditLimits } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util';+import { selectAiChatUsage } from 'src/engine/metadata-modules/ai/ai-chat/utils/select-ai-chat-usage.util';++@Injectable()+export class AiChatUsageService {+ constructor(+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly usageLimitEntitlementService: UsageLimitEntitlementService,+ private readonly usageLimitQuotaService: UsageLimitQuotaService,+ ) {}++ async findUsage({+ workspaceId,+ userWorkspaceId,+ }: {+ workspaceId: string;+ userWorkspaceId: string;+ }): Promise<AiChatUsageDTO | null> {+ const { usageLimits } = await this.workspaceCacheService.getOrRecompute(+ workspaceId,+ ['usageLimits'],+ );++ const enforcedLimits =+ await this.usageLimitEntitlementService.findEnforceableLimits({+ workspaceId,+ limits: findAiChatCreditLimits({ usageLimits, userWorkspaceId }),+ });++ if (enforcedLimits.length === 0) {+ return this.usageLimitQuotaService.getAllowanceUsage(workspaceId);+ }++ const consumptionById =+ await this.usageLimitQuotaService.readLimitConsumptions({+ workspaceId,+ limits: enforcedLimits,+ });++ return selectAiChatUsage({ limits: enforcedLimits, consumptionById });+ }+}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-ai-chat-credit-limits.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-ai-chat-credit-limits.util.spec.tsnew file mode 100644index 00000000000..482a8874adf--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-ai-chat-credit-limits.util.spec.ts@@ -0,0 +1,73 @@+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';+import { type UsageLimits } from 'src/engine/core-modules/usage-limit/types/usage-limits.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 { findAiChatCreditLimits } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util';++const buildLimit = (+ overrides: Partial<FlatUsageLimit> = {},+): FlatUsageLimit => ({+ id: 'limit-1',+ resourceType: UsageResourceType.AI,+ operationType: UsageOperationType.AI_CHAT_TOKEN,+ spenderType: 'userWorkspace',+ spenderId: 'member-1',+ limitKind: 'quota',+ periodCount: 1,+ periodUnit: 'month',+ meter: 'creditsUsedMicro',+ limitValue: 1000,+ burstValue: null,+ ...overrides,+});++const buildUsageLimits = (limits: FlatUsageLimit[]): UsageLimits =>+ limits.reduce<UsageLimits>(+ (usageLimits, limit) => {+ usageLimits.byResourceType[limit.resourceType] = [+ ...(usageLimits.byResourceType[limit.resourceType] ?? []),+ limit,+ ];++ return usageLimits;+ },+ { byResourceType: {} },+ );++const findLimits = (limits: FlatUsageLimit[]) =>+ findAiChatCreditLimits({+ usageLimits: buildUsageLimits(limits),+ userWorkspaceId: 'member-1',+ });++describe('findAiChatCreditLimits', () => {+ it('keeps the credit quota of the current member', () => {+ expect(findLimits([buildLimit()])).toEqual([buildLimit()]);+ });++ it('keeps the member pool and limits covering all operations', () => {+ const memberPool = buildLimit({+ spenderId: '',+ operationType: UsageOperationType.ALL,+ });++ expect(findLimits([memberPool])).toEqual([memberPool]);+ });++ it.each<[string, Partial<FlatUsageLimit>]>([+ ['another member', { spenderId: 'other-member' }],+ ['another resource', { resourceType: UsageResourceType.WORKFLOW }],+ [+ 'another operation',+ { operationType: UsageOperationType.AI_WORKFLOW_TOKEN },+ ],+ ['another meter', { meter: 'quantity' }],+ ['a speed limit', { limitKind: 'speed' }],+ ])('ignores %s', (_, overrides) => {+ expect(findLimits([buildLimit(overrides)])).toEqual([]);+ });++ it('returns nothing when the workspace has no AI limits', () => {+ expect(findLimits([])).toEqual([]);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/select-ai-chat-usage.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/select-ai-chat-usage.util.spec.tsnew file mode 100644index 00000000000..748ea07f480--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/select-ai-chat-usage.util.spec.ts@@ -0,0 +1,100 @@+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';+import { type LimitConsumption } from 'src/engine/core-modules/usage-limit/types/limit-consumption.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 { selectAiChatUsage } from 'src/engine/metadata-modules/ai/ai-chat/utils/select-ai-chat-usage.util';++const periodStart = new Date('2026-09-01T00:00:00Z');+const periodEnd = new Date('2026-10-01T00:00:00Z');++const buildLimit = (+ overrides: Partial<FlatUsageLimit> = {},+): FlatUsageLimit => ({+ id: 'limit-1',+ resourceType: UsageResourceType.AI,+ operationType: UsageOperationType.AI_CHAT_TOKEN,+ spenderType: 'userWorkspace',+ spenderId: 'member-1',+ limitKind: 'quota',+ periodCount: 1,+ periodUnit: 'month',+ meter: 'creditsUsedMicro',+ limitValue: 1000,+ burstValue: null,+ ...overrides,+});++const buildConsumption = (consumedValue: number): LimitConsumption => ({+ consumedValue,+ remainingValue: null,+ periodStart,+ periodEnd,+});++describe('selectAiChatUsage', () => {+ it('reports the consumption of the only limit', () => {+ expect(+ selectAiChatUsage({+ limits: [buildLimit()],+ consumptionById: new Map([['limit-1', buildConsumption(200)]]),+ }),+ ).toEqual({ limitValue: 1000, consumedValue: 200, periodEnd });+ });++ it('surfaces the limit closest to exhaustion when several periods apply', () => {+ expect(+ selectAiChatUsage({+ limits: [+ buildLimit(),+ buildLimit({ id: 'daily', periodUnit: 'day', limitValue: 100 }),+ ],+ consumptionById: new Map([+ ['limit-1', buildConsumption(200)],+ ['daily', buildConsumption(90)],+ ]),+ }),+ ).toEqual({ limitValue: 100, consumedValue: 90, periodEnd });+ });++ it('treats a zero limit as the most exhausted', () => {+ expect(+ selectAiChatUsage({+ limits: [+ buildLimit({ id: 'exhausted', limitValue: 0 }),+ buildLimit({ id: 'warm', limitValue: 100 }),+ ],+ consumptionById: new Map([+ ['exhausted', buildConsumption(0)],+ ['warm', buildConsumption(90)],+ ]),+ }),+ ).toMatchObject({ limitValue: 0 });+ });++ it('reports an unreadable counter rather than a zero consumption', () => {+ expect(+ selectAiChatUsage({+ limits: [buildLimit()],+ consumptionById: new Map(),+ }),+ ).toEqual({ limitValue: 1000, consumedValue: null, periodEnd: null });+ });++ it('prefers an unreadable counter over a warm one', () => {+ expect(+ selectAiChatUsage({+ limits: [+ buildLimit({ id: 'warm' }),+ buildLimit({ id: 'cold', limitValue: 100 }),+ ],+ consumptionById: new Map([['warm', buildConsumption(200)]]),+ }),+ ).toEqual({ limitValue: 100, consumedValue: null, periodEnd: null });+ });++ it('returns nothing when no limit applies', () => {+ expect(+ selectAiChatUsage({ limits: [], consumptionById: new Map() }),+ ).toBeNull();+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util.tsnew file mode 100644index 00000000000..524cd9e66a1--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util.ts@@ -0,0 +1,21 @@+import { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';+import { type UsageLimits } from 'src/engine/core-modules/usage-limit/types/usage-limits.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';++export const findAiChatCreditLimits = ({+ usageLimits,+ userWorkspaceId,+}: {+ usageLimits: UsageLimits;+ userWorkspaceId: string;+}): FlatUsageLimit[] =>+ findLimitsForSpender({+ limits: (usageLimits.byResourceType[UsageResourceType.AI] ?? []).filter(+ (limit) =>+ limit.limitKind === 'quota' && limit.meter === 'creditsUsedMicro',+ ),+ spender: { spenderType: 'userWorkspace', spenderId: userWorkspaceId },+ operationType: UsageOperationType.AI_CHAT_TOKEN,+ });diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/select-ai-chat-usage.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/select-ai-chat-usage.util.tsnew file mode 100644index 00000000000..3e99f60c937--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/select-ai-chat-usage.util.ts@@ -0,0 +1,50 @@+import { isDefined } from 'twenty-shared/utils';++import { type AiChatUsageDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto';+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';+import { type LimitConsumption } from 'src/engine/core-modules/usage-limit/types/limit-consumption.type';++const pressure = ({+ limitValue,+ consumedValue,+}: {+ limitValue: number;+ consumedValue: number;+}) => (limitValue === 0 ? Infinity : consumedValue / limitValue);++export const selectAiChatUsage = ({+ limits,+ consumptionById,+}: {+ limits: FlatUsageLimit[];+ consumptionById: Map<string, LimitConsumption>;+}): AiChatUsageDTO | null => {+ const usages = limits.map((limit) => {+ const consumption = consumptionById.get(limit.id);++ return {+ limitValue: limit.limitValue,+ consumedValue: consumption?.consumedValue ?? null,+ periodEnd: consumption?.periodEnd ?? null,+ };+ });++ const unknownUsage = usages.find((usage) => !isDefined(usage.consumedValue));++ if (isDefined(unknownUsage)) {+ return unknownUsage;+ }++ const knownUsages = usages.flatMap(+ ({ limitValue, consumedValue, periodEnd }) =>+ isDefined(consumedValue)+ ? [{ limitValue, consumedValue, periodEnd }]+ : [],+ );++ // Several periods can apply simultaneously; surface the closest to exhaustion.+ return (+ knownUsages.sort((left, right) => pressure(right) - pressure(left))[0] ??+ null+ );+};