Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(agent-runtime): explain a run refused for its unpaid run fee (#22758)

YuTengjing207efd5e4e34
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
index ce4149edac9..e4f61080e27 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
@@ -1,3 +1,5 @@
+import { ChatErrorType } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
import { AgentOperationModel } from '@/database/models/agentOperation';
@@ -319,4 +321,25 @@ describe('AiAgentService.execAgent - external agent run fee', () => {
const [, , operationId] = fees.rebindAgentRunFee.mock.calls[0];
expect(fees.releaseAgentRunFee).toHaveBeenCalledWith('test-user-id', operationId);
});
+
+ it('refuses a run the user cannot pay the fee for before writing anything', async () => {
+ fees.holdAgentRunFee.mockRejectedValue(
+ new TRPCError({
+ code: 'PAYMENT_REQUIRED',
+ message: ChatErrorType.InsufficientBudgetForAgentRunFee,
+ }),
+ );
+
+ await expect(
+ service.execAgent({ agentId: 'agent-1', prompt: 'Fix the bug' }),
+ ).rejects.toMatchObject({
+ code: 'PAYMENT_REQUIRED',
+ message: ChatErrorType.InsufficientBudgetForAgentRunFee,
+ });
+
+ expect(mockMessageCreate).not.toHaveBeenCalled();
+ expect(mockDispatchAgentRun).not.toHaveBeenCalled();
+ expect(fees.rebindAgentRunFee).not.toHaveBeenCalled();
+ expect(fees.releaseAgentRunFee).not.toHaveBeenCalled();
+ });
});
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index c221cbd5b30..90ab0b512f8 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1649,6 +1649,11 @@
"input.addAiPrefillUnsupported": "The current model doesn’t support ending the conversation with an assistant message. Follow it with a user message before sending.",
"input.addUser": "Add a user message",
"input.agentModeUnsupportedModel": "The current model doesn’t support agentic tool calling. Switch to a model with agent capability for the best experience.",
+ "input.agentRunFeeUnfunded.desc": "Each agent run carries a fee, even on your own API key. Top up or upgrade your plan, then send again.",
+ "input.agentRunFeeUnfunded.descOverflow": "Each agent run carries a fee, even on your own API key. Your balance covers it: use your balance, then send again.",
+ "input.agentRunFeeUnfunded.descSubscribe": "Each agent run carries a fee, even on your own API key. Subscribe to a plan, then send again.",
+ "input.agentRunFeeUnfunded.descTopUp": "Each agent run carries a fee, even on your own API key. Top up, then send again.",
+ "input.agentRunFeeUnfunded.title": "Not enough credits to pay the agent run fee",
"input.agentSlugMoved": "This link now opens a different agent. Switching to it — try again once it opens. Your draft is kept.",
"input.agentSlugUnconfirmed": "Couldn’t confirm which agent this link opens. Check your connection, then try again.",
"input.concurrencyLimit.desc": "Send again when one finishes.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 533efe7f25b..8bd759ac977 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1649,6 +1649,11 @@
"input.addAiPrefillUnsupported": "当前模型不支持以助理消息结尾发送,请在其后继续添加一条用户消息再发送。",
"input.addUser": "添加一条用户消息",
"input.agentModeUnsupportedModel": "当前模型不支持 Agentic 工具调用,建议切换为具备 Agent 能力的模型以获得最佳体验。",
+ "input.agentRunFeeUnfunded.desc": "每次助理运行都会收取运行费,使用自己的 API Key 也不例外。充值或升级套餐后再发送。",
+ "input.agentRunFeeUnfunded.descOverflow": "每次助理运行都会收取运行费,使用自己的 API Key 也不例外。你的余额足够支付,使用余额后再发送。",
+ "input.agentRunFeeUnfunded.descSubscribe": "每次助理运行都会收取运行费,使用自己的 API Key 也不例外。订阅套餐后再发送。",
+ "input.agentRunFeeUnfunded.descTopUp": "每次助理运行都会收取运行费,使用自己的 API Key 也不例外。充值后再发送。",
+ "input.agentRunFeeUnfunded.title": "额度不足以支付助理运行费",
"input.agentSlugMoved": "该链接现在指向另一个助理,正在切换,打开后请重试。输入框中的草稿会保留。",
"input.agentSlugUnconfirmed": "暂时无法确认该链接对应的助理,请检查网络后重试。",
"input.concurrencyLimit.desc": "等其中一个结束后再发送。",
diff --git a/packages/business-server/src/agent-run/runFee.ts b/packages/business-server/src/agent-run/runFee.ts
index 1bd39ef98e9..0e82bbae131 100644
--- a/packages/business-server/src/agent-run/runFee.ts
+++ b/packages/business-server/src/agent-run/runFee.ts
@@ -18,8 +18,10 @@ export interface SettleAgentRunFeeParams {
* settled when it ends. The default never charges; a deployment that bills
* runs overrides these four functions.
*
- * Hold runs before the turn writes any row. It should not refuse the run: a
- * deployment that does throws, and the message then stays in the composer.
+ * Hold runs before the turn writes any row. A deployment that refuses a run
+ * the user cannot pay for throws a `TRPCError` whose message is
+ * `ChatErrorType.InsufficientBudgetForAgentRunFee`; the turn then writes
+ * nothing, and the message stays in the composer under a notice that says why.
*/
export const holdAgentRunFee = async (_params: HoldAgentRunFeeParams): Promise<void> => {};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 3bb4304e5ad..14a2908049b 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -982,6 +982,15 @@ export default {
'input.addUser': 'Add a user message',
'input.agentModeUnsupportedModel':
'The current model doesn’t support agentic tool calling. Switch to a model with agent capability for the best experience.',
+ 'input.agentRunFeeUnfunded.desc':
+ 'Each agent run carries a fee, even on your own API key. Top up or upgrade your plan, then send again.',
+ 'input.agentRunFeeUnfunded.descOverflow':
+ 'Each agent run carries a fee, even on your own API key. Your balance covers it: use your balance, then send again.',
+ 'input.agentRunFeeUnfunded.descSubscribe':
+ 'Each agent run carries a fee, even on your own API key. Subscribe to a plan, then send again.',
+ 'input.agentRunFeeUnfunded.descTopUp':
+ 'Each agent run carries a fee, even on your own API key. Top up, then send again.',
+ 'input.agentRunFeeUnfunded.title': 'Not enough credits to pay the agent run fee',
'input.agentSlugMoved':
'This link now opens a different agent. Switching to it — try again once it opens. Your draft is kept.',
'input.agentSlugUnconfirmed':
diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.ts
index 1a7522c80bb..b94bde508cd 100644
--- a/packages/types/src/fetch.ts
+++ b/packages/types/src/fetch.ts
@@ -17,6 +17,7 @@ export const ChatErrorType = {
AgentShareProviderNotSupported: 'AgentShareProviderNotSupported', // This shared agent uses a provider that is not supported for shared visitors
SupervisorDecisionFailed: 'SupervisorDecisionFailed', // Supervisor decision failed
AgentConcurrencyLimitExceeded: 'AgentConcurrencyLimitExceeded', // The user already has as many agent runs in flight as allowed — recovers when one finishes
+ InsufficientBudgetForAgentRunFee: 'InsufficientBudgetForAgentRunFee', // The user's credits cannot pay the per-run agent fee — refused before the run starts, also on the user's own provider key
InvalidUserKey: 'InvalidUserKey', // is not valid User key
CreateMessageError: 'CreateMessageError',
diff --git a/src/business/client/hooks/useBusinessSendErrorAlert.ts b/src/business/client/hooks/useBusinessSendErrorAlert.ts
index b653a49a63e..5b21ed45b64 100644
--- a/src/business/client/hooks/useBusinessSendErrorAlert.ts
+++ b/src/business/client/hooks/useBusinessSendErrorAlert.ts
@@ -3,12 +3,18 @@ import type { ReactNode } from 'react';
export interface BusinessSendErrorAlert {
/** Button shown beside the notice, such as an upgrade entry. */
action?: ReactNode;
+ /** Replaces the line under the title, so it names only the actions offered. */
+ description?: string;
/** Replaces the default notice text. */
title?: string;
}
/**
* Lets a deployment enrich the composer notice for a refused send, keyed by the
- * error type the server returned as the message.
+ * error type the server returned as the message. `onClose` dismisses the notice,
+ * for an action that already resolved the refusal.
*/
-export const useBusinessSendErrorAlert = (_errorMessage?: string): BusinessSendErrorAlert => ({});
+export const useBusinessSendErrorAlert = (
+ _errorMessage?: string,
+ _onClose?: () => void,
+): BusinessSendErrorAlert => ({});
diff --git a/src/features/Conversation/ChatInput/SendErrorAlert.tsx b/src/features/Conversation/ChatInput/SendErrorAlert.tsx
index a59f03cf60c..f5461afdc7e 100644
--- a/src/features/Conversation/ChatInput/SendErrorAlert.tsx
+++ b/src/features/Conversation/ChatInput/SendErrorAlert.tsx
@@ -20,9 +20,10 @@ interface SendErrorAlertProps {
*/
const SendErrorAlert = memo<SendErrorAlertProps>(({ errorMessage, onClose }) => {
const { t } = useTranslation(['chat', 'common']);
- const business = useBusinessSendErrorAlert(errorMessage);
+ const business = useBusinessSendErrorAlert(errorMessage, onClose);
const isConcurrencyLimit = errorMessage === ChatErrorType.AgentConcurrencyLimitExceeded;
+ const isRunFeeUnfunded = errorMessage === ChatErrorType.InsufficientBudgetForAgentRunFee;
// `errorMessage` can still be a raw database dump on servers predating the
// databaseError middleware. That text is SQL plus every bound parameter —
@@ -32,15 +33,23 @@ const SendErrorAlert = memo<SendErrorAlertProps>(({ errorMessage, onClose }) =>
business.title ??
(isConcurrencyLimit
? t('input.concurrencyLimit.title')
- : t('input.errorMsg', {
- errorMsg:
- toDisplayableSendErrorMessage(errorMessage) ?? t('unknownError', { ns: 'common' }),
- }));
+ : isRunFeeUnfunded
+ ? t('input.agentRunFeeUnfunded.title')
+ : t('input.errorMsg', {
+ errorMsg:
+ toDisplayableSendErrorMessage(errorMessage) ?? t('unknownError', { ns: 'common' }),
+ }));
// The title says what stopped the send; the line under it says what to do.
// As a single sentence the two overflowed the row and stranded a word on the
// second line.
- const description = isConcurrencyLimit ? t('input.concurrencyLimit.desc') : undefined;
+ const description =
+ business.description ??
+ (isConcurrencyLimit
+ ? t('input.concurrencyLimit.desc')
+ : isRunFeeUnfunded
+ ? t('input.agentRunFeeUnfunded.desc')
+ : undefined);
// Same bottom gap and edges as the other notices above the composer, so two
// of them stack at an even rhythm and line up with the input.