The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(ai-chat): show workspace-scoped AI limits and warn before the composer (#26674)
Etienne963b5e6993ad
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 3649d0563ef..a501850dff5 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -3430,6 +3430,7 @@ type AiChatUsage {limitValue: BigInt!consumedValue: BigIntperiodEnd: DateTime+ kind: String!}type Skill {diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 65f6f7a4095..f929174351a 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -3019,6 +3019,7 @@ export interface AiChatUsage {limitValue: Scalars['BigInt']consumedValue?: Scalars['BigInt']periodEnd?: Scalars['DateTime']+ kind: Scalars['String']__typename: 'AiChatUsage'}@@ -6907,6 +6908,7 @@ export interface AiChatUsageGenqlSelection{limitValue?: boolean | numberconsumedValue?: boolean | numberperiodEnd?: boolean | number+ kind?: boolean | number__typename?: boolean | number__scalar?: boolean | number}diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex 77105004182..d4b7dd2029b 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -6764,6 +6764,9 @@ export default {"periodEnd": [4],+ "kind": [+ 1+ ],"__typename": [1]diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex a856225d4fb..3a51726e2f3 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -185,6 +185,7 @@ export enum AggregateOperations {export type AiChatUsage = {__typename?: 'AiChatUsage';consumedValue?: Maybe<Scalars['BigInt']['output']>;+ kind: Scalars['String']['output'];limitValue: Scalars['BigInt']['output'];periodEnd?: Maybe<Scalars['DateTime']['output']>;};@@ -8093,7 +8094,7 @@ export type GetAgentTurnsQuery = { __typename?: 'Query', agentTurns: Array<{ __texport 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 GetAiChatUsageQuery = { __typename?: 'Query', aiChatUsage?: { __typename?: 'AiChatUsage', limitValue: any, consumedValue?: any | null, periodEnd?: string | null, kind: string } | null };export type GetChatMessagesQueryVariables = Exact<{threadId: Scalars['UUID']['input'];@@ -10526,7 +10527,7 @@ 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 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"}},{"kind":"Field","name":{"kind":"Name","value":"kind"}}]}}]}}]} 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":"senderUserWorkspaceId"}},{"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":"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"}},{"kind":"Field","name":{"kind":"Name","value":"widgetName"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentId"}}]}}]}}]} as unknown as DocumentNode<GetToolIndexQuery, GetToolIndexQueryVariables>;diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsxindex f85ee585197..ac042d79622 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -14,6 +14,7 @@ import { AiModelTierDropdown } from '@/ai/components/AiModelTierDropdown';import { AiChatEmptyState } from '@/ai/components/AiChatEmptyState';import { AiChatQuestionCard } from '@/ai/components/AiChatQuestionCard';import { AIChatNoMoreBillingCreditsBanner } from '@/ai/components/AIChatNoMoreBillingCreditsBanner';+import { AiChatUsageLimitReachedBanner } from '@/ai/components/AiChatUsageLimitReachedBanner';import { AiChatStandaloneError } from '@/ai/components/AiChatStandaloneError';import { AgentChatContextPreview } from '@/ai/components/internal/AgentChatContextPreview';import { AgentChatFileUploadButton } from '@/ai/components/internal/AgentChatFileUploadButton';@@ -27,6 +28,7 @@ import { useAiChatEditor } from '@/ai/hooks/useAiChatEditor';import { useInsertDictatedText } from '@/ai/dictation/hooks/useInsertDictatedText';import { useIsAiChatComposerCentered } from '@/ai/hooks/useIsAiChatComposerCentered';import { useHasReachedAiChatCreditsCap } from '@/ai/hooks/useHasReachedAiChatCreditsCap';+import { useHasReachedAiChatUsageLimit } from '@/ai/hooks/useHasReachedAiChatUsageLimit';import { agentChatPendingQuestionComponentSelector } from '@/ai/states/selectors/agentChatPendingQuestionComponentSelector';import { aiModelsState } from '@/client-config/states/aiModelsState';import { useIsMobile } from 'twenty-ui/utilities';@@ -150,6 +152,9 @@ const EditableAiChatEditorSection = () => {const isMobile = useIsMobile();const isComposerCentered = useIsAiChatComposerCentered();const hasReachedAiChatCreditsCap = useHasReachedAiChatCreditsCap();+ const hasReachedAiChatUsageLimit = useHasReachedAiChatUsageLimit();+ const shouldShowUsageLimitBanner =+ !hasReachedAiChatCreditsCap && hasReachedAiChatUsageLimit;const aiModels = useAtomStateValue(aiModelsState);const hasNoEnabledModels = aiModels.length === 0;@@ -180,6 +185,7 @@ const EditableAiChatEditorSection = () => {/>)}{hasReachedAiChatCreditsCap && <AIChatNoMoreBillingCreditsBanner />}+ {shouldShowUsageLimitBanner && <AiChatUsageLimitReachedBanner />}{isDefined(pendingQuestion) ? (<AiChatQuestionCard pendingQuestion={pendingQuestion} />) : (diff --git a/packages/twenty-front/src/modules/ai/components/AiChatErrorMessage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatErrorMessage.tsxindex 035c2c110eb..981ade9aba9 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatErrorMessage.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatErrorMessage.tsx@@ -1,6 +1,8 @@import { CombinedGraphQLErrors } from '@apollo/client/errors';import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';+import { type ComponentProps } from 'react';+import { type InlineBanner } from 'twenty-ui/components';import { IconAlertCircle, IconRefresh } from 'twenty-ui/icon';import { Button } from 'twenty-ui/primitives/input';import { isDefined } from 'twenty-shared/utils';@@ -48,12 +50,14 @@ type AiChatErrorMessageProps = {error: AiChatError;hint?: string;onRetry?: () => void;+ button?: ComponentProps<typeof InlineBanner>['button'];};export const AiChatErrorMessage = ({error,hint,onRetry,+ button,}: AiChatErrorMessageProps) => {const theme = useTheme();const errorMessage = CombinedGraphQLErrors.is(error)@@ -80,6 +84,17 @@ export const AiChatErrorMessage = ({variant="outline">{t`Retry`}</Button>)}+ {isDefined(button) && !button.hidden && (+ <Button+ size="sm"+ startIcon={isDefined(button.Icon) ? <button.Icon /> : undefined}+ onClick={button.onClick}+ disabled={button.disabled}+ variant="outline"+ >+ {button.title}+ </Button>+ )}</StyledErrorContainer>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsxindex cd4de43857b..48618d402b7 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx@@ -1,7 +1,6 @@-import { t } from '@lingui/core/macro';-import { AiChatApiKeyNotConfiguredMessage } from '@/ai/components/AiChatApiKeyNotConfiguredMessage';import { AiChatErrorMessage } from '@/ai/components/AiChatErrorMessage';+import { AiChatQuotaLimitExhaustedMessage } from '@/ai/components/AiChatQuotaLimitExhaustedMessage';import { type AiChatError } from '@/ai/types/AiChatError';import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';import { getAiChatQuotaExhaustedKind } from '@/ai/utils/getAiChatQuotaExhaustedKind';@@ -37,12 +36,7 @@ export const AiChatErrorRenderer = ({// The quota is checked before persistence, so a retry repeats the same refusalif (getAiChatQuotaExhaustedKind(error) === 'limit') {- return (- <AiChatErrorMessage- error={error}- hint={t`Ask a workspace admin to raise the limit.`}- />- );+ return <AiChatQuotaLimitExhaustedMessage error={error} />;}return <AiChatErrorMessage error={error} onRetry={onRetry} />;diff --git a/packages/twenty-front/src/modules/ai/components/AiChatQuotaLimitExhaustedMessage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatQuotaLimitExhaustedMessage.tsxnew file mode 100644index 00000000000..e51f7a95ea7--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatQuotaLimitExhaustedMessage.tsx@@ -0,0 +1,30 @@+import { useLingui } from '@lingui/react/macro';+import { isDefined } from 'twenty-shared/utils';++import { AiChatErrorMessage } from '@/ai/components/AiChatErrorMessage';+import { type AiChatError } from '@/ai/types/AiChatError';+import { useManageUsageLimitsButton } from '@/settings/billing/hooks/useManageUsageLimitsButton';++type AiChatQuotaLimitExhaustedMessageProps = {+ error: AiChatError;+};++export const AiChatQuotaLimitExhaustedMessage = ({+ error,+}: AiChatQuotaLimitExhaustedMessageProps) => {+ const { t } = useLingui();++ const manageLimitsButton = useManageUsageLimitsButton();++ return (+ <AiChatErrorMessage+ error={error}+ hint={+ isDefined(manageLimitsButton)+ ? undefined+ : t`Ask an admin to raise the limit.`+ }+ button={manageLimitsButton}+ />+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatUsageLimitReachedBanner.tsx b/packages/twenty-front/src/modules/ai/components/AiChatUsageLimitReachedBanner.tsxnew file mode 100644index 00000000000..76c183c9542--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatUsageLimitReachedBanner.tsx@@ -0,0 +1,22 @@+import { useLingui } from '@lingui/react/macro';+import { isDefined } from 'twenty-shared/utils';++import { AiChatInlineBanner } from '@/ai/components/AiChatInlineBanner';+import { useManageUsageLimitsButton } from '@/settings/billing/hooks/useManageUsageLimitsButton';++export const AiChatUsageLimitReachedBanner = () => {+ const { t } = useLingui();++ const manageLimitsButton = useManageUsageLimitsButton();++ return (+ <AiChatInlineBanner+ message={+ isDefined(manageLimitsButton)+ ? t`AI usage limit reached for this period.`+ : t`AI usage limit reached. Ask an admin to raise the limit.`+ }+ button={manageLimitsButton}+ />+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuotaLimitExhaustedMessage.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuotaLimitExhaustedMessage.stories.tsxnew file mode 100644index 00000000000..3e22396df56--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuotaLimitExhaustedMessage.stories.tsx@@ -0,0 +1,26 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';++import { AiChatQuotaLimitExhaustedMessage } from '@/ai/components/AiChatQuotaLimitExhaustedMessage';+import { PermissionFlagType } from '~/generated-metadata/graphql';+import { ComponentWithRouterDecorator } from '~/testing/decorators/ComponentWithRouterDecorator';+import { PermissionFlagsDecorator } from '~/testing/decorators/PermissionFlagsDecorator';++const meta: Meta<typeof AiChatQuotaLimitExhaustedMessage> = {+ title: 'Modules/AI/AiChatQuotaLimitExhaustedMessage',+ component: AiChatQuotaLimitExhaustedMessage,+ decorators: [PermissionFlagsDecorator, ComponentWithRouterDecorator],+ args: {+ error: new Error('You have reached your AI usage limit for this period.'),+ },+};++export default meta;+type Story = StoryObj<typeof AiChatQuotaLimitExhaustedMessage>;++export const WithWorkspacePermission: Story = {+ parameters: { permissionFlags: [PermissionFlagType.WORKSPACE] },+};++export const WithoutWorkspacePermission: Story = {+ parameters: { permissionFlags: [] },+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatUsageLimitReachedBanner.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatUsageLimitReachedBanner.stories.tsxnew file mode 100644index 00000000000..9a5646694ef--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatUsageLimitReachedBanner.stories.tsx@@ -0,0 +1,23 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';++import { AiChatUsageLimitReachedBanner } from '@/ai/components/AiChatUsageLimitReachedBanner';+import { PermissionFlagType } from '~/generated-metadata/graphql';+import { ComponentWithRouterDecorator } from '~/testing/decorators/ComponentWithRouterDecorator';+import { PermissionFlagsDecorator } from '~/testing/decorators/PermissionFlagsDecorator';++const meta: Meta<typeof AiChatUsageLimitReachedBanner> = {+ title: 'Modules/AI/AiChatUsageLimitReachedBanner',+ component: AiChatUsageLimitReachedBanner,+ decorators: [PermissionFlagsDecorator, ComponentWithRouterDecorator],+};++export default meta;+type Story = StoryObj<typeof AiChatUsageLimitReachedBanner>;++export const WithWorkspacePermission: Story = {+ parameters: { permissionFlags: [PermissionFlagType.WORKSPACE] },+};++export const WithoutWorkspacePermission: Story = {+ parameters: { permissionFlags: [] },+};diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageButton.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageButton.tsxindex d160af4cc28..276a5065bcc 100644--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageButton.tsx+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatContextUsageButton.tsx@@ -1,6 +1,5 @@import { getAiChatUsageLabel } from '@/ai/utils/getAiChatUsageLabel';import { formatAiChatTokens } from '@/ai/utils/formatAiChatTokens';-import { useQuery } from '@apollo/client/react';import {FloatingPortal,autoUpdate,@@ -29,6 +28,7 @@ import { themeCssVariables } from 'twenty-ui/theme';import { AiChatContextUsageDetails } from '@/ai/components/internal/AiChatContextUsageDetails';import { ContextUsageProgressRing } from '@/ai/components/internal/ContextUsageProgressRing';+import { useAiChatUsage } from '@/ai/hooks/useAiChatUsage';import { useAiModelTiers } from '@/ai/hooks/useAiModelTiers';import { useWorkspaceAiModelTiers } from '@/ai/hooks/useWorkspaceAiModelTiers';import { useIsWorkspaceSetupChat } from '@/ai/hooks/useIsWorkspaceSetupChat';@@ -41,7 +41,6 @@ import { StyledInformationCard } from '@/ui/layout/information-card/components/Simport { 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 { GetAiChatUsageDocument } from '~/generated-metadata/graphql';import { formatNumber } from '~/utils/format/formatNumber';const StyledTrigger = styled.button`@@ -112,23 +111,22 @@ export const AiChatContextUsageButton = () => {? Math.min(100, Math.max(0, (conversationSize / contextWindow) * 100)): 0;- const { data, loading, error } = useQuery(GetAiChatUsageDocument, {+ const {+ usage: creditUsage,+ loading,+ error,+ } = useAiChatUsage({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 limitValue = creditUsage?.limitValue ?? null;const progress = isDefined(limitValue)- ? computeUsageLimitProgress({ limitValue, consumedValue })+ ? computeUsageLimitProgress({+ limitValue,+ consumedValue: creditUsage?.consumedValue ?? null,+ }): null;const creditPercentage =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.tsxindex 131887e082e..22f22214c40 100644--- a/packages/twenty-front/src/modules/ai/components/internal/__stories__/AiChatContextUsageButton.stories.tsx+++ b/packages/twenty-front/src/modules/ai/components/internal/__stories__/AiChatContextUsageButton.stories.tsx@@ -81,6 +81,7 @@ const UsageStory = ({limitValue: limit,consumedValue: consumed,periodEnd: null,+ kind: 'allowance',},},},diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getAiChatUsage.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getAiChatUsage.tsindex f75cefc042a..b46f87d1e00 100644--- a/packages/twenty-front/src/modules/ai/graphql/queries/getAiChatUsage.ts+++ b/packages/twenty-front/src/modules/ai/graphql/queries/getAiChatUsage.ts@@ -6,6 +6,7 @@ export const GET_AI_CHAT_USAGE = gql`limitValueconsumedValueperiodEnd+ kind}}`;diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatUsage.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatUsage.tsnew file mode 100644index 00000000000..7b8e855b156--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatUsage.ts@@ -0,0 +1,34 @@+import { type WatchQueryFetchPolicy } from '@apollo/client';+import { useQuery } from '@apollo/client/react';+import { isDefined } from 'twenty-shared/utils';++import { type AiChatUsage } from '@/ai/types/AiChatUsage';+import { GetAiChatUsageDocument } from '~/generated-metadata/graphql';++export const useAiChatUsage = ({+ skip = false,+ fetchPolicy,+}: {+ skip?: boolean;+ fetchPolicy: WatchQueryFetchPolicy;+}) => {+ const { data, loading, error } = useQuery(GetAiChatUsageDocument, {+ skip,+ fetchPolicy,+ });++ const aiChatUsage = data?.aiChatUsage;++ const usage: AiChatUsage | null = isDefined(aiChatUsage)+ ? {+ limitValue: Number(aiChatUsage.limitValue),+ consumedValue: isDefined(aiChatUsage.consumedValue)+ ? Number(aiChatUsage.consumedValue)+ : null,+ periodEnd: aiChatUsage.periodEnd ?? null,+ kind: aiChatUsage.kind,+ }+ : null;++ return { usage, loading, error };+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatUsageLimit.ts b/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatUsageLimit.tsnew file mode 100644index 00000000000..058a4f623e1--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatUsageLimit.ts@@ -0,0 +1,14 @@+import { useAiChatUsage } from '@/ai/hooks/useAiChatUsage';+import { useIsWorkspaceSetupChat } from '@/ai/hooks/useIsWorkspaceSetupChat';+import { isAiChatUsageLimitReached } from '@/ai/utils/isAiChatUsageLimitReached';++export const useHasReachedAiChatUsageLimit = () => {+ const isWorkspaceSetupChat = useIsWorkspaceSetupChat();++ const { usage } = useAiChatUsage({+ skip: isWorkspaceSetupChat,+ fetchPolicy: 'cache-and-network',+ });++ return isAiChatUsageLimitReached(usage);+};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatUsage.ts b/packages/twenty-front/src/modules/ai/types/AiChatUsage.tsnew file mode 100644index 00000000000..b812056999a--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatUsage.ts@@ -0,0 +1,6 @@+export type AiChatUsage = {+ limitValue: number;+ consumedValue: number | null;+ periodEnd: string | null;+ kind: string;+};diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatUsageLimitReached.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatUsageLimitReached.test.tsnew file mode 100644index 00000000000..0f6c8006bdd--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatUsageLimitReached.test.ts@@ -0,0 +1,48 @@+import { type AiChatUsage } from '@/ai/types/AiChatUsage';+import { isAiChatUsageLimitReached } from '@/ai/utils/isAiChatUsageLimitReached';++const buildUsage = (overrides: Partial<AiChatUsage> = {}): AiChatUsage => ({+ limitValue: 1000,+ consumedValue: 100,+ periodEnd: '2026-10-01T00:00:00.000Z',+ kind: 'limit',+ ...overrides,+});++describe('isAiChatUsageLimitReached', () => {+ it('reports a limit consumed up to its value', () => {+ expect(isAiChatUsageLimitReached(buildUsage({ consumedValue: 1000 }))).toBe(+ true,+ );+ });++ it('reports a limit blocking every send', () => {+ expect(+ isAiChatUsageLimitReached(+ buildUsage({ limitValue: 0, consumedValue: 0 }),+ ),+ ).toBe(true);+ });++ it('ignores a limit with room left', () => {+ expect(isAiChatUsageLimitReached(buildUsage())).toBe(false);+ });++ it('ignores an unreadable counter', () => {+ expect(isAiChatUsageLimitReached(buildUsage({ consumedValue: null }))).toBe(+ false,+ );+ });++ it('ignores the plan allowance, which the credits banner owns', () => {+ expect(+ isAiChatUsageLimitReached(+ buildUsage({ consumedValue: 1000, kind: 'allowance' }),+ ),+ ).toBe(false);+ });++ it('ignores a workspace with no usage at all', () => {+ expect(isAiChatUsageLimitReached(null)).toBe(false);+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/isAiChatUsageLimitReached.ts b/packages/twenty-front/src/modules/ai/utils/isAiChatUsageLimitReached.tsnew file mode 100644index 00000000000..461b05a62e7--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/isAiChatUsageLimitReached.ts@@ -0,0 +1,9 @@+import { isDefined } from 'twenty-shared/utils';++import { type AiChatUsage } from '@/ai/types/AiChatUsage';++export const isAiChatUsageLimitReached = (usage: AiChatUsage | null): boolean =>+ isDefined(usage) &&+ usage.kind === 'limit' &&+ isDefined(usage.consumedValue) &&+ usage.consumedValue >= usage.limitValue;diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useManageUsageLimitsButton.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useManageUsageLimitsButton.tsnew file mode 100644index 00000000000..3d54b3ac313--- /dev/null+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useManageUsageLimitsButton.ts@@ -0,0 +1,30 @@+import { useLingui } from '@lingui/react/macro';+import { type ComponentProps } from 'react';+import { SettingsPath } from 'twenty-shared/types';+import { type InlineBanner } from 'twenty-ui/components';+import { IconSettings } from 'twenty-ui/icon';++import { usePermissionFlagMap } from '@/settings/roles/hooks/usePermissionFlagMap';+import { PermissionFlagType } from '~/generated-metadata/graphql';+import { useNavigateSettings } from '~/hooks/useNavigateSettings';++export const useManageUsageLimitsButton = (): ComponentProps<+ typeof InlineBanner+>['button'] => {+ const { t } = useLingui();++ const { [PermissionFlagType.WORKSPACE]: hasPermissionToManageUsageLimits } =+ usePermissionFlagMap();++ const navigateSettings = useNavigateSettings();++ if (!hasPermissionToManageUsageLimits) {+ return undefined;+ }++ return {+ title: t`Manage limits`,+ Icon: IconSettings,+ onClick: () => navigateSettings(SettingsPath.BillingLimits),+ };+};diff --git a/packages/twenty-front/src/testing/decorators/PermissionFlagsDecorator.tsx b/packages/twenty-front/src/testing/decorators/PermissionFlagsDecorator.tsxnew file mode 100644index 00000000000..967a264f527--- /dev/null+++ b/packages/twenty-front/src/testing/decorators/PermissionFlagsDecorator.tsx@@ -0,0 +1,24 @@+import { type Decorator } from '@storybook/react-vite';+import { useEffect } from 'react';++import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';+import { type PermissionFlagType } from '~/generated-metadata/graphql';++export const PermissionFlagsDecorator: Decorator = (Story, { parameters }) => {+ const setCurrentUserWorkspace = useSetAtomState(currentUserWorkspaceState);++ const { permissionFlags }: { permissionFlags?: PermissionFlagType[] } =+ parameters;++ useEffect(() => {+ setCurrentUserWorkspace({+ permissionFlags: permissionFlags ?? [],+ twoFactorAuthenticationMethodSummary: [],+ isImpersonating: false,+ objectsPermissions: [],+ });+ }, [setCurrentUserWorkspace, permissionFlags]);++ return <Story />;+};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.tsindex acf2bf0a122..6e86b624aff 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/ai-chat-usage.dto.ts@@ -1,6 +1,8 @@import { Field, ObjectType } from '@nestjs/graphql';import { GraphQLBigInt } from 'graphql-scalars';+import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';+@ObjectType('AiChatUsage')export class AiChatUsageDTO {@Field(() => GraphQLBigInt)@@ -11,4 +13,7 @@ export class AiChatUsageDTO {@Field(() => Date, { nullable: true })periodEnd: Date | null;++ @Field(() => String)+ kind: ExhaustedKind;}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.tsindex 7749e8ee3e1..677c30aee41 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service.ts@@ -1,5 +1,7 @@import { Injectable } from '@nestjs/common';+import { isDefined } from 'twenty-shared/utils';+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';@@ -34,7 +36,12 @@ export class AiChatUsageService {});if (enforcedLimits.length === 0) {- return this.usageLimitQuotaService.getAllowanceUsage(workspaceId);+ const allowanceUsage =+ await this.usageLimitQuotaService.getAllowanceUsage(workspaceId);++ return isDefined(allowanceUsage)+ ? { ...allowanceUsage, kind: 'allowance' }+ : null;}const 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.tsindex 9631c8f8c6f..081ed2c1525 100644--- 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.ts@@ -55,8 +55,32 @@ describe('findAiChatCreditLimits', () => {expect(findLimits([memberPool])).toEqual([memberPool]);});+ it('keeps the workspace-wide quota the send is billed against', () => {+ const workspaceQuota = buildLimit({+ spenderType: 'workspace',+ spenderId: '',+ operationType: UsageOperationType.ALL,+ });++ expect(findLimits([workspaceQuota])).toEqual([workspaceQuota]);+ });++ it('keeps both the workspace quota and the member quota', () => {+ const workspaceQuota = buildLimit({+ id: 'workspace-quota',+ spenderType: 'workspace',+ spenderId: '',+ });++ expect(findLimits([workspaceQuota, buildLimit()])).toEqual([+ buildLimit(),+ workspaceQuota,+ ]);+ });+it.each<[string, Partial<FlatUsageLimit>]>([['another member', { spenderId: 'other-member' }],+ ['another spender type', { spenderType: 'agent', spenderId: '' }],['another resource', { resourceType: UsageResourceType.WORKFLOW }],['another operation',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.tsindex 198752cf934..5f5926e2b66 100644--- 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.ts@@ -39,7 +39,12 @@ describe('selectAiChatUsage', () => {limits: [buildLimit()],consumptionById: new Map([['limit-1', buildConsumption(200)]]),}),- ).toEqual({ limitValue: 1000, consumedValue: 200, periodEnd });+ ).toEqual({+ limitValue: 1000,+ consumedValue: 200,+ periodEnd,+ kind: 'limit',+ });});it('surfaces the limit closest to exhaustion when several periods apply', () => {@@ -54,7 +59,12 @@ describe('selectAiChatUsage', () => {['daily', buildConsumption(90)],]),}),- ).toEqual({ limitValue: 100, consumedValue: 90, periodEnd });+ ).toEqual({+ limitValue: 100,+ consumedValue: 90,+ periodEnd,+ kind: 'limit',+ });});it('treats a zero limit as the most exhausted', () => {@@ -78,7 +88,12 @@ describe('selectAiChatUsage', () => {limits: [buildLimit()],consumptionById: new Map(),}),- ).toEqual({ limitValue: 1000, consumedValue: null, periodEnd: null });+ ).toEqual({+ limitValue: 1000,+ consumedValue: null,+ periodEnd: null,+ kind: 'limit',+ });});it('prefers an unreadable counter over a warm one', () => {@@ -90,7 +105,12 @@ describe('selectAiChatUsage', () => {],consumptionById: new Map([['warm', buildConsumption(200)]]),}),- ).toEqual({ limitValue: 100, consumedValue: null, periodEnd: null });+ ).toEqual({+ limitValue: 100,+ consumedValue: null,+ periodEnd: null,+ kind: 'limit',+ });});it('returns nothing when no limit applies', () => {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.tsindex 524cd9e66a1..3e440908a17 100644--- 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.ts@@ -1,3 +1,4 @@+import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';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';@@ -10,12 +11,20 @@ export const findAiChatCreditLimits = ({}: {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,- });+}): FlatUsageLimit[] => {+ const creditQuotas = (+ usageLimits.byResourceType[UsageResourceType.AI] ?? []+ ).filter(+ (limit) =>+ limit.limitKind === 'quota' && limit.meter === 'creditsUsedMicro',+ );++ return buildSpendersFromUsageSpenders({ userWorkspaceId }).flatMap(+ (spender) =>+ findLimitsForSpender({+ limits: creditQuotas,+ spender,+ 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.tsindex 3e99f60c937..a4bfbd03c35 100644--- 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.ts@@ -19,13 +19,14 @@ export const selectAiChatUsage = ({limits: FlatUsageLimit[];consumptionById: Map<string, LimitConsumption>;}): AiChatUsageDTO | null => {- const usages = limits.map((limit) => {+ const usages = limits.map((limit): AiChatUsageDTO => {const consumption = consumptionById.get(limit.id);return {limitValue: limit.limitValue,consumedValue: consumption?.consumedValue ?? null,periodEnd: consumption?.periodEnd ?? null,+ kind: 'limit',};});@@ -36,9 +37,9 @@ export const selectAiChatUsage = ({}const knownUsages = usages.flatMap(- ({ limitValue, consumedValue, periodEnd }) =>+ ({ limitValue, consumedValue, periodEnd, kind }) =>isDefined(consumedValue)- ? [{ limitValue, consumedValue, periodEnd }]+ ? [{ limitValue, consumedValue, periodEnd, kind }]: [],);