feat(ai-chat) - Stop ai thinking if credits exhausted (#20526)

Billing is now decremented per-step, not per-turn. The onStepFinish
callback in chat-execution.service.ts calls a new
decrementAndCheckAvailableCredits method on each model step, so Redis is
debited incrementally as the agent runs rather than all at once at the
end.

Credit exhaustion stops the stream mid-run. When a step depletes the
remaining credits, a hasNoMoreAvailableCredits flag is set and passed
into the stopWhen predicate of streamText, causing the agent to halt
before starting the next step.

A new credits-exhausted event is introduced. After the stream drains and
the response is persisted, if credits ran out the job publishes a
dedicated credits-exhausted event to the frontend instead of the normal
message-persisted event.

The frontend handles this new event. useAgentChatSubscription has a new
credits-exhausted case that sets a BILLING_CREDITS_EXHAUSTED-coded error
on the atom, closes the writer, and stops the streaming state —
triggering the existing AiChatCreditsExhaustedMessage UI.
This commit is contained in:
Etienne
2026-05-13 17:09:08 +02:00
committed by GitHub
parent 068fc9363d
commit aecfe699f4
14 changed files with 212 additions and 52 deletions
@@ -76,18 +76,25 @@ export class AiAgentWorkflowAction implements WorkflowAction {
? executionContext.authContext.userWorkspaceId
: null;
const { result } = await this.aiAgentExecutionService.executeAgent({
agent,
userPrompt: resolveInput(prompt, context) as string,
actorContext: executionContext.isActingOnBehalfOfUser
? executionContext.initiator
: undefined,
rolePermissionConfig: executionContext.rolePermissionConfig,
authContext: executionContext.authContext,
workspaceId,
userWorkspaceId,
operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
});
const { result, hasNoMoreAvailableCredits } =
await this.aiAgentExecutionService.executeAgent({
agent,
userPrompt: resolveInput(prompt, context) as string,
actorContext: executionContext.isActingOnBehalfOfUser
? executionContext.initiator
: undefined,
rolePermissionConfig: executionContext.rolePermissionConfig,
authContext: executionContext.authContext,
workspaceId,
userWorkspaceId,
operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
});
if (hasNoMoreAvailableCredits) {
return {
error: 'AI agent stopped: no more available credits.',
};
}
return {
result,
@@ -78,7 +78,7 @@ describe('WorkflowExecutorWorkspaceService', () => {
const mockBillingUsageService = {
hasAvailableCredits: jest.fn().mockResolvedValue(true),
decrementAvailableCredits: jest.fn().mockResolvedValue(undefined),
decrementAvailableCreditsInCache: jest.fn().mockResolvedValue(undefined),
};
const mockExceptionHandlerService = {
@@ -375,7 +375,7 @@ export class WorkflowExecutorWorkspaceService {
periodStart = currentPeriodStart;
await this.billingUsageService.decrementAvailableCredits({
await this.billingUsageService.decrementAvailableCreditsInCache({
workspaceId,
usedCredits: 100,
});