Skip to content

The open alternative to Salesforce, designed for AI.

fix(ai-chat): answer a refused message with what actually clears it (#25622)

Etienne17447874d13d
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatErrorMessage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatErrorMessage.tsx
index a9d54dc868f..98a1983afe6 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatErrorMessage.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatErrorMessage.tsx
@@ -47,11 +47,13 @@ const StyledErrorMessage = styled.div`
type AiChatErrorMessageProps = {
error: AiChatError;
+ hint?: string;
onRetry?: () => void;
};
export const AiChatErrorMessage = ({
error,
+ hint,
onRetry,
}: AiChatErrorMessageProps) => {
const { theme } = useContext(ThemeContext);
@@ -69,6 +71,7 @@ export const AiChatErrorMessage = ({
<StyledErrorMessage>
{errorMessage || t`An error occurred while processing your message`}
</StyledErrorMessage>
+ {isDefined(hint) && <StyledErrorMessage>{hint}</StyledErrorMessage>}
</StyledErrorContent>
{isDefined(onRetry) && (
<Button
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx
index 06359f81403..cd4de43857b 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx
@@ -1,7 +1,11 @@
+import { t } from '@lingui/core/macro';
+
import { AiChatApiKeyNotConfiguredMessage } from '@/ai/components/AiChatApiKeyNotConfiguredMessage';
import { AiChatErrorMessage } from '@/ai/components/AiChatErrorMessage';
import { type AiChatError } from '@/ai/types/AiChatError';
import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
+import { getAiChatQuotaExhaustedKind } from '@/ai/utils/getAiChatQuotaExhaustedKind';
+import { isAiChatCreditsExhaustedError } from '@/ai/utils/isAiChatCreditsExhaustedError';
import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
type AiChatErrorRendererProps = {
@@ -13,9 +17,9 @@ export const AiChatErrorRenderer = ({
error,
onRetry,
}: AiChatErrorRendererProps) => {
- if (isGraphqlErrorOfType(error, AiChatErrorCode.BILLING_CREDITS_EXHAUSTED)) {
- // Handled by AIChatNoMoreBillingCreditsBanner, which useHasReachedAiChatCreditsCap
- // keeps mounted for exactly this error so nothing is swallowed here
+ // Handled by AIChatNoMoreBillingCreditsBanner, which useHasReachedAiChatCreditsCap
+ // keeps mounted for exactly this error so nothing is swallowed here
+ if (isAiChatCreditsExhaustedError(error)) {
return null;
}
@@ -31,5 +35,15 @@ export const AiChatErrorRenderer = ({
return <AiChatErrorMessage error={error} />;
}
+ // The quota is checked before persistence, so a retry repeats the same refusal
+ if (getAiChatQuotaExhaustedKind(error) === 'limit') {
+ return (
+ <AiChatErrorMessage
+ error={error}
+ hint={t`Ask a workspace admin to raise the limit.`}
+ />
+ );
+ }
+
return <AiChatErrorMessage error={error} onRetry={onRetry} />;
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
index b2377368a33..07bd2c4b60f 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
@@ -35,7 +35,7 @@ import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMess
import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';
import { agentChatUploadedFilesState } from '@/ai/states/agentChatUploadedFilesState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
+import { isAiChatCreditsExhaustedError } from '@/ai/utils/isAiChatCreditsExhaustedError';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';
import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';
@@ -46,7 +46,6 @@ import {
markWorkspaceCreditsAvailable,
markWorkspaceCreditsExhausted,
} from '@/workspace/utils/updateWorkspaceResourceCreditCap';
-import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
export const useAgentChat = (
ensureThreadIdForSend: () => Promise<string | null>,
@@ -201,12 +200,7 @@ export const useAgentChat = (
// credits-exhausted before this response resolves; that event marks the
// thread error, so its presence means the exhaustion is newer information
// than the gate pass this response proves.
- if (
- !isGraphqlErrorOfType(
- store.get(errorAtom),
- AiChatErrorCode.BILLING_CREDITS_EXHAUSTED,
- )
- ) {
+ if (!isAiChatCreditsExhaustedError(store.get(errorAtom))) {
store.set(currentWorkspaceState.atom, markWorkspaceCreditsAvailable);
}
@@ -259,9 +253,7 @@ export const useAgentChat = (
: new Error('An unexpected error occurred'),
);
- if (
- isGraphqlErrorOfType(error, AiChatErrorCode.BILLING_CREDITS_EXHAUSTED)
- ) {
+ if (isAiChatCreditsExhaustedError(error)) {
store.set(currentWorkspaceState.atom, markWorkspaceCreditsExhausted);
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts b/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts
index b8f4f8b2814..68f9460e25a 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts
@@ -1,12 +1,11 @@
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';
-import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
+import { isAiChatCreditsExhaustedError } from '@/ai/utils/isAiChatCreditsExhaustedError';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { hasReachedCurrentBillingPeriodCapSelector } from '@/workspace/states/hasReachedCurrentBillingPeriodCapSelector';
import { isResourceCreditSubscriptionItem } from '@/workspace/utils/isResourceCreditSubscriptionItem';
-import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
// The credits exhausted error renders nothing on its own, so the banner must
// mount whenever the workspace is refused for lack of credits. The resource
@@ -41,8 +40,5 @@ export const useHasReachedAiChatCreditsCap = () => {
return false;
}
- return isGraphqlErrorOfType(
- agentChatError,
- AiChatErrorCode.BILLING_CREDITS_EXHAUSTED,
- );
+ return isAiChatCreditsExhaustedError(agentChatError);
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts b/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts
index acfb8458d95..154ec889bde 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts
@@ -10,14 +10,13 @@ import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';
import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';
-import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
+import { isAiChatCreditsExhaustedError } from '@/ai/utils/isAiChatCreditsExhaustedError';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';
import {
markWorkspaceCreditsAvailable,
markWorkspaceCreditsExhausted,
} from '@/workspace/utils/updateWorkspaceResourceCreditCap';
-import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
export const useRetryChatMessage = () => {
const apolloClient = useApolloClient();
@@ -57,12 +56,7 @@ export const useRetryChatMessage = () => {
// Same ordering guard as useAgentChat: a credits-exhausted event from
// the stream this retry started may already have marked the thread error
// before this response resolves, and that exhaustion is newer truth.
- if (
- !isGraphqlErrorOfType(
- store.get(errorAtom),
- AiChatErrorCode.BILLING_CREDITS_EXHAUSTED,
- )
- ) {
+ if (!isAiChatCreditsExhaustedError(store.get(errorAtom))) {
store.set(currentWorkspaceState.atom, markWorkspaceCreditsAvailable);
}
@@ -74,12 +68,7 @@ export const useRetryChatMessage = () => {
retryError instanceof Error ? retryError : previousError,
);
- if (
- isGraphqlErrorOfType(
- retryError,
- AiChatErrorCode.BILLING_CREDITS_EXHAUSTED,
- )
- ) {
+ if (isAiChatCreditsExhaustedError(retryError)) {
store.set(currentWorkspaceState.atom, markWorkspaceCreditsExhausted);
}
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts b/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts
index 3223033cad5..be58fba7c23 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts
@@ -11,11 +11,15 @@ import { AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME } from '@/ai/constants/AgentChat
import { ANSWER_AGENT_CHAT_QUESTION } from '@/ai/graphql/mutations/answerAgentChatQuestion';
import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
+import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';
import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';
import { agentChatUploadedFilesState } from '@/ai/states/agentChatUploadedFilesState';
import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
+import { isAiChatCreditsExhaustedError } from '@/ai/utils/isAiChatCreditsExhaustedError';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { markWorkspaceCreditsExhausted } from '@/workspace/utils/updateWorkspaceResourceCreditCap';
import { markQuestionAnswered } from '@/ai/utils/markQuestionAnswered';
import { markQuestionPending } from '@/ai/utils/markQuestionPending';
import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';
@@ -65,6 +69,10 @@ export const useSubmitQuestionAnswer = () => {
instanceId: AGENT_CHAT_INSTANCE_ID,
familyKey: { threadId },
});
+ const errorAtom = agentChatErrorComponentFamilyState.atomFamily({
+ instanceId: AGENT_CHAT_INSTANCE_ID,
+ familyKey: { threadId },
+ });
const previousMessages = store.get(messagesAtom);
const uploadedFiles = store.get(agentChatUploadedFilesState.atom);
@@ -102,6 +110,17 @@ export const useSubmitQuestionAnswer = () => {
...currentUploadedFiles,
]);
+ // The banner reads the workspace flag, then the thread error when no resource credit item carries that flag
+ if (isAiChatCreditsExhaustedError(error)) {
+ store.set(currentWorkspaceState.atom, markWorkspaceCreditsExhausted);
+ store.set(
+ errorAtom,
+ CombinedGraphQLErrors.is(error) || error instanceof Error
+ ? error
+ : new Error('An unexpected error occurred'),
+ );
+ }
+
if (isGraphqlErrorOfType(error, AiChatErrorCode.QUESTION_NOT_PENDING)) {
dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);
} else {
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatQuotaExhaustedKind.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatQuotaExhaustedKind.test.ts
new file mode 100644
index 00000000000..a12e63e24ec
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatQuotaExhaustedKind.test.ts
@@ -0,0 +1,38 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+
+import { getAiChatQuotaExhaustedKind } from '@/ai/utils/getAiChatQuotaExhaustedKind';
+
+const buildError = (extensions: Record<string, unknown>) =>
+ new CombinedGraphQLErrors({
+ data: null,
+ errors: [{ message: 'refused', extensions }],
+ });
+
+describe('getAiChatQuotaExhaustedKind', () => {
+ it('tells a spent allowance apart from a configured limit', () => {
+ expect(
+ getAiChatQuotaExhaustedKind(
+ buildError({ code: 'QUOTA_EXHAUSTED', exhaustedKind: 'allowance' }),
+ ),
+ ).toBe('allowance');
+
+ expect(
+ getAiChatQuotaExhaustedKind(
+ buildError({ code: 'QUOTA_EXHAUSTED', exhaustedKind: 'limit' }),
+ ),
+ ).toBe('limit');
+ });
+
+ it('reports an unreadable refusal as a limit, never as spent credits', () => {
+ expect(
+ getAiChatQuotaExhaustedKind(buildError({ code: 'QUOTA_EXHAUSTED' })),
+ ).toBe('limit');
+ });
+
+ it('ignores errors that are not quota refusals', () => {
+ expect(
+ getAiChatQuotaExhaustedKind(buildError({ code: 'RATE_LIMITED' })),
+ ).toBeNull();
+ expect(getAiChatQuotaExhaustedKind(new Error('boom'))).toBeNull();
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatCreditsExhaustedError.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatCreditsExhaustedError.test.ts
new file mode 100644
index 00000000000..dd2c0ad2dbc
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/isAiChatCreditsExhaustedError.test.ts
@@ -0,0 +1,34 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+
+import { isAiChatCreditsExhaustedError } from '@/ai/utils/isAiChatCreditsExhaustedError';
+
+const buildError = (extensions: Record<string, unknown>) =>
+ new CombinedGraphQLErrors({
+ data: null,
+ errors: [{ message: 'refused', extensions }],
+ });
+
+describe('isAiChatCreditsExhaustedError', () => {
+ it('covers both ways the server reports spent credits', () => {
+ expect(
+ isAiChatCreditsExhaustedError(
+ buildError({ code: 'BILLING_CREDITS_EXHAUSTED' }),
+ ),
+ ).toBe(true);
+
+ expect(
+ isAiChatCreditsExhaustedError(
+ buildError({ code: 'QUOTA_EXHAUSTED', exhaustedKind: 'allowance' }),
+ ),
+ ).toBe(true);
+ });
+
+ it('leaves a configured limit out of the credits banner', () => {
+ expect(
+ isAiChatCreditsExhaustedError(
+ buildError({ code: 'QUOTA_EXHAUSTED', exhaustedKind: 'limit' }),
+ ),
+ ).toBe(false);
+ expect(isAiChatCreditsExhaustedError(new Error('boom'))).toBe(false);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts b/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
index e12d2783a39..f57bd4be093 100644
--- a/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
+++ b/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
@@ -4,4 +4,5 @@ export const AiChatErrorCode = {
API_KEY_NOT_CONFIGURED: 'API_KEY_NOT_CONFIGURED',
CONNECTION_LOST: 'CONNECTION_LOST',
QUESTION_NOT_PENDING: 'QUESTION_NOT_PENDING',
+ QUOTA_EXHAUSTED: 'QUOTA_EXHAUSTED',
} as const;
diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatQuotaExhaustedKind.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatQuotaExhaustedKind.ts
new file mode 100644
index 00000000000..36b66da31aa
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatQuotaExhaustedKind.ts
@@ -0,0 +1,17 @@
+import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
+import { getGraphqlErrorExtensionsFromError } from '~/utils/get-graphql-error-extensions-from-error.util';
+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
+
+// An unreadable refusal is reported as a limit: guessing 'allowance' would flip the workspace into the upgrade banner
+export const getAiChatQuotaExhaustedKind = (
+ error: unknown,
+): 'limit' | 'allowance' | null => {
+ if (!isGraphqlErrorOfType(error, AiChatErrorCode.QUOTA_EXHAUSTED)) {
+ return null;
+ }
+
+ return getGraphqlErrorExtensionsFromError(error)?.exhaustedKind ===
+ 'allowance'
+ ? 'allowance'
+ : 'limit';
+};
diff --git a/packages/twenty-front/src/modules/ai/utils/isAiChatCreditsExhaustedError.ts b/packages/twenty-front/src/modules/ai/utils/isAiChatCreditsExhaustedError.ts
new file mode 100644
index 00000000000..12b8b066a77
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/isAiChatCreditsExhaustedError.ts
@@ -0,0 +1,7 @@
+import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
+import { getAiChatQuotaExhaustedKind } from '@/ai/utils/getAiChatQuotaExhaustedKind';
+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
+
+export const isAiChatCreditsExhaustedError = (error: unknown): boolean =>
+ isGraphqlErrorOfType(error, AiChatErrorCode.BILLING_CREDITS_EXHAUSTED) ||
+ getAiChatQuotaExhaustedKind(error) === 'allowance';