🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-run): charge the run fee for locally run external agents (#22757)
YuTengjing7332c2a2396c
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.localHeteroRunFee.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.localHeteroRunFee.test.tsnew file mode 100644index 00000000000..96475cf50b4--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.localHeteroRunFee.test.ts@@ -0,0 +1,128 @@+// @vitest-environment node+import type { LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import { ChatErrorType } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentRouter } from '../aiAgent';+import { cleanupTestUser, createTestTopic, createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;++const { holdAgentRunFee, settleAgentRunFee } = vi.hoisted(() => ({+ holdAgentRunFee: vi.fn(),+ settleAgentRunFee: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return testDB;+ }),+}));++vi.mock('@/business/server/agent-run/runFee', () => ({ holdAgentRunFee, settleAgentRunFee }));++describe('local heterogeneous run fee', () => {+ let topicId: string;+ let userId: string;++ const caller = (workspaceId?: string) =>+ aiAgentRouter.createCaller({ jwtPayload: { userId }, userId, workspaceId } as any);++ beforeEach(async () => {+ testDB = await getTestDB();+ userId = await createTestUser(testDB);+ topicId = await createTestTopic(testDB, userId);+ holdAgentRunFee.mockResolvedValue(undefined);+ settleAgentRunFee.mockResolvedValue(undefined);+ });++ afterEach(async () => {+ await cleanupTestUser(testDB, userId);+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ it('holds the fee of a personal run under a minted fee id', async () => {+ const { feeId } = await caller().beginLocalHeteroRunFee({ topicId });++ expect(feeId).toMatch(/^local_hetero_\d+_/);+ expect(holdAgentRunFee).toHaveBeenCalledWith({ holderId: feeId, userId });+ });++ it('refuses the run when the deployment refuses an unfunded fee', async () => {+ holdAgentRunFee.mockRejectedValue(+ new TRPCError({+ code: 'PAYMENT_REQUIRED',+ message: ChatErrorType.InsufficientBudgetForAgentRunFee,+ }),+ );++ await expect(caller().beginLocalHeteroRunFee({ topicId })).rejects.toMatchObject({+ message: ChatErrorType.InsufficientBudgetForAgentRunFee,+ });+ });++ it('exempts a Workspace run', async () => {+ await expect(caller('ws_1').beginLocalHeteroRunFee({})).resolves.toEqual({ feeId: null });+ expect(holdAgentRunFee).not.toHaveBeenCalled();+ });++ it("rejects another user's topic without holding", async () => {+ const otherUserId = await createTestUser(testDB);+ const otherTopicId = await createTestTopic(testDB, otherUserId);++ try {+ await expect(+ caller().beginLocalHeteroRunFee({ topicId: otherTopicId }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(holdAgentRunFee).not.toHaveBeenCalled();+ } finally {+ await cleanupTestUser(testDB, otherUserId);+ }+ });++ it('settles with the duration measured from the fee id, not the client', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-11-10T00:00:00Z'));+ const { feeId } = await caller().beginLocalHeteroRunFee({ topicId });+ vi.setSystemTime(new Date('2026-11-10T00:00:45Z'));++ await caller().finishLocalHeteroRunFee({ feeId: feeId!, reason: 'interrupted' });++ expect(settleAgentRunFee).toHaveBeenCalledWith({+ durationMs: 45_000,+ operationId: feeId,+ reason: 'interrupted',+ userId,+ });+ });++ it('takes a shorter duration Desktop reports, never a longer one', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-11-10T00:00:00Z'));+ const { feeId } = await caller().beginLocalHeteroRunFee({ topicId });+ vi.setSystemTime(new Date('2026-11-10T00:00:35Z'));++ await caller().finishLocalHeteroRunFee({+ durationMs: 28_000,+ feeId: feeId!,+ reason: 'interrupted',+ });+ await caller().finishLocalHeteroRunFee({+ durationMs: 90_000,+ feeId: feeId!,+ reason: 'interrupted',+ });++ expect(settleAgentRunFee.mock.calls.map(([args]) => args.durationMs)).toEqual([28_000, 35_000]);+ });++ it('will not settle a fee id it did not mint', async () => {+ await expect(+ caller().finishLocalHeteroRunFee({ feeId: 'op_server_run', reason: 'error' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(settleAgentRunFee).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.tsindex abbc667cd88..e5f69cc40db 100644--- a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts@@ -20,6 +20,7 @@ describe('aiAgentRouter procedures', () => {function expected(): Array<[name: string, type: 'mutation' | 'query']> {return [+ ['beginLocalHeteroRunFee', 'mutation'],['beginServerDefaultHeterogeneousOperation', 'mutation'],['cancelServerDefaultHeterogeneousOperation', 'mutation'],['createClientGroupAgentTaskThread', 'mutation'],@@ -29,6 +30,7 @@ function expected(): Array<[name: string, type: 'mutation' | 'query']> {['execAgents', 'mutation'],['execGroupAgent', 'mutation'],['execSubAgentTask', 'mutation'],+ ['finishLocalHeteroRunFee', 'mutation'],['finishServerDefaultHeterogeneousOperation', 'mutation'],['getAgentInterventionReview', 'mutation'],['getAgentInterventionReviewBySource', 'mutation'],diff --git a/apps/server/src/routers/lambda/aiAgent/index.ts b/apps/server/src/routers/lambda/aiAgent/index.tsindex f7ec54d1df5..ab204db7bad 100644--- a/apps/server/src/routers/lambda/aiAgent/index.ts+++ b/apps/server/src/routers/lambda/aiAgent/index.ts@@ -5,6 +5,7 @@ import { execRouter } from './exec';import { gatewayRelayRouter } from './gatewayRelay';import { heteroRouter } from './hetero';import { interventionRouter } from './intervention';+import { localHeteroRunFeeRouter } from './localHeteroRunFee';import { operationStatusRouter } from './operationStatus';import { runControlRouter } from './runControl';import { serverDefaultHeteroRouter } from './serverDefaultHetero';@@ -28,4 +29,5 @@ export const aiAgentRouter = mergeRouters(gatewayRelayRouter,runControlRouter,heteroRouter,+ localHeteroRunFeeRouter,);diff --git a/apps/server/src/routers/lambda/aiAgent/localHeteroRunFee.ts b/apps/server/src/routers/lambda/aiAgent/localHeteroRunFee.tsnew file mode 100644index 00000000000..77cd4d5876e--- /dev/null+++ b/apps/server/src/routers/lambda/aiAgent/localHeteroRunFee.ts@@ -0,0 +1,80 @@+import { nanoid } from '@lobechat/utils';+import { z } from 'zod';++import { holdAgentRunFee, settleAgentRunFee } from '@/business/server/agent-run/runFee';+import { router } from '@/libs/trpc/lambda';++import { resolveHeteroTopicWorkspace } from './guards';+import { aiAgentBaseProcedure } from './procedures';++/**+ * Fee ids this router mints. The start time is part of the id, so `finish`+ * measures the run's duration on the server instead of trusting the client,+ * and the prefix keeps `finish` from settling the fee of a server-dispatched+ * run (whose holder is its operation id).+ */+const LOCAL_HETERO_RUN_FEE_ID = /^local_hetero_(\d+)_[\w-]+$/;++const mintLocalHeteroRunFeeId = () => `local_hetero_${Date.now()}_${nanoid()}`;++/**+ * Run fee for an external agent (Claude Code, Codex, …) Desktop spawns on the+ * user's own machine. That run never passes through `execAgent`, so Desktop+ * reports it here: `begin` before spawning the CLI, `finish` once it ends.+ *+ * The caller decides which runs report (the same exemptions as+ * `shouldHoldRunFee`: continuations and sub-agents do not); Workspace runs are+ * exempt here, resolved from the topic rather than taken from the client.+ * A client that never calls `finish` leaves the hold to expire on its own.+ */+export const localHeteroRunFeeRouter = router({+ /**+ * Holds the fee. A deployment that refuses an unfunded fee throws, and+ * Desktop then does not start the CLI. Returns `feeId: null` when the run+ * carries no fee.+ */+ beginLocalHeteroRunFee: aiAgentBaseProcedure+ .input(z.object({ topicId: z.string().min(1).optional() }))+ .mutation(async ({ input, ctx }) => {+ const workspaceId = input.topicId+ ? await resolveHeteroTopicWorkspace({+ db: ctx.serverDB,+ requestedWorkspaceId: ctx.workspaceId,+ topicId: input.topicId,+ userId: ctx.userId,+ })+ : ctx.workspaceId;+ if (workspaceId) return { feeId: null };++ const feeId = mintLocalHeteroRunFeeId();+ await holdAgentRunFee({ holderId: feeId, userId: ctx.userId });+ return { feeId };+ }),++ /** Charges or gives back the fee by the run's end reason, as `settleAgentRunFee` rules. */+ finishLocalHeteroRunFee: aiAgentBaseProcedure+ .input(+ z.object({+ /**+ * How long the run lasted when it ended, as Desktop saw it. Cleanup after a+ * stop (persisting, closing the CLI) can take seconds, so the time of this+ * call overstates a stopped run. It can only shorten the duration the+ * server measures.+ */+ durationMs: z.number().int().nonnegative().optional(),+ feeId: z.string().regex(LOCAL_HETERO_RUN_FEE_ID),+ reason: z.enum(['done', 'error', 'interrupted']),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const startedAt = Number(LOCAL_HETERO_RUN_FEE_ID.exec(input.feeId)![1]);+ const elapsedMs = Math.max(0, Date.now() - startedAt);+ await settleAgentRunFee({+ durationMs: Math.min(elapsedMs, input.durationMs ?? elapsedMs),+ operationId: input.feeId,+ reason: input.reason,+ userId: ctx.userId,+ });+ return { success: true as const };+ }),+});diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex 4312d4e3cfb..e25bbd67ad4 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -91,6 +91,7 @@"response.GoogleAIBlockReason.SAFETY": "The content was blocked for safety reasons. Please adjust it and try again.","response.GoogleAIBlockReason.SPII": "The content may include sensitive personal information (SPII). Please remove sensitive details and try again.","response.GoogleAIBlockReason.default": "The content was blocked ({{blockReason}}). Please adjust it and try again.",+ "response.InsufficientBudgetForAgentRunFee": "Not enough credits to pay the agent run fee. Each agent run carries a fee, even on your own CLI account. Top up or upgrade your plan, then try again.","response.InsufficientBudgetForModel": "Your remaining balance is insufficient for this model. Please top up, upgrade your plan, or try a less expensive model.","response.InvalidAccessCode": "Invalid access code or empty. Please enter the correct access code or add a custom API Key.","response.LobeHubModelDeprecated": "The model \"{{model}}\" is no longer available. Please pick a current model from the model selector.",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex 716ae4af4c7..ef34b13c2d5 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -91,6 +91,7 @@"response.GoogleAIBlockReason.SAFETY": "内容因安全原因被屏蔽。请调整后再试。","response.GoogleAIBlockReason.SPII": "内容可能包含敏感个人信息(SPII)。请移除敏感信息后再试。","response.GoogleAIBlockReason.default": "内容被屏蔽({{blockReason}})。请调整后再试。",+ "response.InsufficientBudgetForAgentRunFee": "额度不足以支付助理运行费。每次助理运行都会收取运行费,使用自己的 CLI 账号也不例外。充值或升级套餐后再试。","response.InsufficientBudgetForModel": "你的余额不足以使用此模型。请充值、升级订阅套餐,或尝试使用费用更低的模型。","response.InvalidAccessCode": "访问密码为空或不正确。请重新输入,或改用自定义 API Key","response.LobeHubModelDeprecated": "模型「{{model}}」已下架,请到模型选择器中重新选择可用模型。",diff --git a/packages/business-server/src/agent-run/runFee.ts b/packages/business-server/src/agent-run/runFee.tsindex 0e82bbae131..6d28d5d3fe3 100644--- a/packages/business-server/src/agent-run/runFee.ts+++ b/packages/business-server/src/agent-run/runFee.ts@@ -18,10 +18,12 @@ 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. 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.+ * Hold runs before the turn writes any row, and before Desktop spawns an+ * external agent it runs locally. A deployment that refuses a run the user+ * cannot pay for throws a `TRPCError` whose message is+ * `ChatErrorType.InsufficientBudgetForAgentRunFee`, holding nothing: a server+ * turn then writes nothing and the message stays in the composer under a+ * notice that says why, and Desktop does not start the CLI.*/export const holdAgentRunFee = async (_params: HoldAgentRunFeeParams): Promise<void> => {};diff --git a/packages/const/src/apiKeyScope.test.ts b/packages/const/src/apiKeyScope.test.tsindex 071a5b58c4a..f6df6415934 100644--- a/packages/const/src/apiKeyScope.test.ts+++ b/packages/const/src/apiKeyScope.test.ts@@ -118,6 +118,12 @@ describe('requiredApiKeyScopeForTrpc', () => {expect(requiredApiKeyScopeForTrpc('aiAgent.execAgent', 'mutation')).toEqual({scopes: ['agent:write', 'chat:write', 'model:invoke'],});+ // a desktop-local run fee spends real balance, like the run entries+ for (const path of ['aiAgent.beginLocalHeteroRunFee', 'aiAgent.finishLocalHeteroRunFee']) {+ expect(requiredApiKeyScopeForTrpc(path, 'mutation')).toEqual({+ scopes: ['agent:write', 'chat:write', 'model:invoke'],+ });+ }// listing the queue reads conversation contentexpect(requiredApiKeyScopeForTrpc('agentSteerQueue.list', 'query')).toEqual({scopes: ['agent:read', 'chat:read'],diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 39e7a90dad1..9b7a88a29b5 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -387,6 +387,9 @@ export const TRPC_PROCEDURE_EXTRA_SCOPES: Record<string, ApiKeyScope[]> = {'aiAgent.execAgents': AGENT_RUN_SCOPES,'aiAgent.execGroupAgent': AGENT_RUN_SCOPES,'aiAgent.execSubAgentTask': AGENT_RUN_SCOPES,+ // a desktop-local external agent run holds and settles a real run fee+ 'aiAgent.beginLocalHeteroRunFee': AGENT_RUN_SCOPES,+ 'aiAgent.finishLocalHeteroRunFee': AGENT_RUN_SCOPES,'aiAgent.scheduleAgentRun': AGENT_RUN_SCOPES,'aiAgent.startExecution': AGENT_RUN_SCOPES,// a queued follow-up is a deferred composer send: the run that drains itdiff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex 618820afda0..36f5ddf461d 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -131,6 +131,8 @@ export default {'The model service is currently under heavy load. Please try again later or switch to another model.','response.FreePlanLimit':'You are currently a free user and cannot use this feature. Please upgrade to a paid plan to continue using it.',+ 'response.InsufficientBudgetForAgentRunFee':+ 'Not enough credits to pay the agent run fee. Each agent run carries a fee, even on your own CLI account. Top up or upgrade your plan, then try again.','response.InsufficientBudgetForModel':'Your remaining balance is insufficient for this model. Please top up, upgrade your plan, or try a less expensive model.','response.GoogleAIBlockReason.BLOCKLIST':diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.tsindex 9b9104f14bf..2b68522aa4e 100644--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.ts+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.ts@@ -123,6 +123,7 @@ export const continueHeteroAfterError = async (await runHeterogeneousFromExistingMessage(chatStore, {context,+ continuesRun: true,heterogeneousProvider,parentMessageId: continueParentId,parentOperationId: operationId,diff --git a/src/features/Conversation/store/slices/generation/heteroRun.ts b/src/features/Conversation/store/slices/generation/heteroRun.tsindex 397d1603c29..a16a91cebe0 100644--- a/src/features/Conversation/store/slices/generation/heteroRun.ts+++ b/src/features/Conversation/store/slices/generation/heteroRun.ts@@ -205,6 +205,8 @@ export const runHeterogeneousFromExistingMessage = async (/** Non-image attachments from the original user message — forwarded to the CLI as download links */attachedFiles?: HeteroAttachedFileRef[];context: ConversationContext;+ /** Continues a run that already paid its agent fee, so this one holds none. */+ continuesRun?: boolean;heterogeneousProvider: HeterogeneousProviderConfig;/** Image attachments from the original user message — forwarded to the CLI for vision support */imageList?: ChatImageItem[];@@ -302,6 +304,7 @@ export const runHeterogeneousFromExistingMessage = async (assistantMessageId: assistantMsg.id,attachedFiles: attachedFiles?.length ? attachedFiles : undefined,context,+ continuesRun: params.continuesRun,heterogeneousProvider: effectiveHeterogeneousProvider,imageList: imageList?.length ? imageList : undefined,message: prompt,diff --git a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.tsindex e07cf1637c8..9ca532b89a6 100644--- a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts+++ b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts@@ -393,6 +393,8 @@ const recoverRun = async ();const continuation = await runHeterogeneousFromExistingMessage(chatStore, {context,+ // Finishes the interrupted run, which already held its fee.+ continuesRun: true,heterogeneousProvider,parentMessageId: tail?.id ?? userTurn.id,parentOperationId: operationId,diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 29d9e2274db..1074fe92560 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -17,7 +17,7 @@ import type {} from '@lobechat/types';import { canUseGatewayProtocolV2 } from '@/helpers/gatewayProtocol';-import { lambdaClient } from '@/libs/trpc/client';+import { createWorkspaceLambdaClient, lambdaClient } from '@/libs/trpc/client';import { buildLlmExecutorDeclaration } from '@/services/llmRelay';export type { ExecAgentResult, ScheduleAgentRunParams, ScheduleAgentRunResult };@@ -311,6 +311,26 @@ class AiAgentService {return await lambdaClient.aiAgent.getServerDefaultHeterogeneousCapability.query();}+ /** Holds the run fee of an external agent this desktop spawns itself. */+ async beginLocalHeteroRunFee(+ params: { topicId?: string },+ options: { signal?: AbortSignal; workspaceId: string | null },+ ) {+ return await createWorkspaceLambdaClient(+ options.workspaceId,+ ).aiAgent.beginLocalHeteroRunFee.mutate(params, { signal: options.signal });+ }++ /** Charges or gives back that fee once the run ends, in the scope it was held in. */+ async finishLocalHeteroRunFee(+ params: { durationMs?: number; feeId: string; reason: 'done' | 'error' | 'interrupted' },+ options: { signal?: AbortSignal; workspaceId: string | null },+ ) {+ return await createWorkspaceLambdaClient(+ options.workspaceId,+ ).aiAgent.finishLocalHeteroRunFee.mutate(params, { signal: options.signal });+ }+/*** Execute a single Agent task.* Returns the operationId needed to connect to the Agent Gateway.diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.runFee.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.runFee.test.tsnew file mode 100644index 00000000000..601ecf7a5c0--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.runFee.test.ts@@ -0,0 +1,304 @@+/** The agent run fee of an external agent this desktop spawns itself. */++import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import { ChatErrorType } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { executeHeterogeneousAgent } from '../transports/hetero/heterogeneousAgentExecutor';+import {+ ccInit,+ ccResult,+ ccText,+ createMockStore,+ defaultParams,+ setupIpcCapture,+} from './heterogeneousAgentExecutor.testUtils';++const mockBeginFee = vi.fn();+const mockFinishFee = vi.fn();+const mockSendPrompt = vi.fn();+const mockStartSession = vi.fn();+const mockUpdateMessageError = vi.fn();++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast: { info: vi.fn() },+}));++vi.mock('@/services/aiAgent', () => ({+ aiAgentService: {+ beginLocalHeteroRunFee: (...args: any[]) => mockBeginFee(...args),+ finishLocalHeteroRunFee: (...args: any[]) => mockFinishFee(...args),+ },+}));++vi.mock('@/services/message', () => ({+ messageService: {+ batchMutate: vi.fn(async (operations: any[]) => ({+ results: operations.map((operation, index) => ({ index, success: true, ...operation })),+ success: true,+ })),+ createMessage: vi.fn(async (params: any) => ({ id: params.id })),+ getMessages: vi.fn(async () => []),+ updateMessage: vi.fn(async () => undefined),+ updateMessageError: (...args: any[]) => mockUpdateMessageError(...args),+ updateToolMessage: vi.fn(async () => undefined),+ },+}));++vi.mock('@/services/electron/heterogeneousAgent', () => ({+ heterogeneousAgentService: {+ cancelSession: vi.fn(async () => undefined),+ getClaudeCodeIdentity: vi.fn(async () => null),+ getCodexQuota: vi.fn(async () => null),+ getSessionInfo: vi.fn(async () => ({})),+ sendPrompt: (...args: any[]) => mockSendPrompt(...args),+ startSession: (...args: any[]) => mockStartSession(...args),+ stopSession: vi.fn(async () => undefined),+ },+}));++vi.mock('@/services/agentQuota', () => ({+ agentQuotaService: {+ recordUsage: vi.fn(async () => undefined),+ selectAccountForAgent: vi.fn(async () => null),+ },+}));++vi.mock('../transports/gateway/gatewayEventHandler', () => ({+ createGatewayEventHandler: vi.fn(() => vi.fn()),+}));++describe('heterogeneousAgentExecutor run fee', () => {+ let ipc: ReturnType<typeof setupIpcCapture>;++ /** The CLI streams one answer and exits cleanly. */+ const answerCleanly = async (params: any) => {+ ipc.emitRawLine(params.sessionId, ccInit());+ ipc.emitRawLine(params.sessionId, ccText('msg-1', 'answer'));+ ipc.emitRawLine(params.sessionId, ccResult());+ ipc.emitComplete(params.sessionId);+ };++ beforeEach(() => {+ vi.clearAllMocks();+ ipc = setupIpcCapture();+ let session = 0;+ mockStartSession.mockImplementation(async (params: any) => {+ session += 1;+ const sessionId = `ipc-sess-${session}`;+ ipc.setAgentType(sessionId, params.agentType ?? 'claude-code');+ return { sessionId };+ });+ mockSendPrompt.mockImplementation(answerCleanly);+ mockBeginFee.mockResolvedValue({ feeId: 'local_hetero_1_fee' });+ mockFinishFee.mockResolvedValue({ success: true });+ mockUpdateMessageError.mockResolvedValue({ success: false });+ });++ it('holds the fee before spawning the CLI and charges it after a finished run', async () => {+ await executeHeterogeneousAgent(() => createMockStore(), defaultParams);++ expect(mockBeginFee).toHaveBeenCalledWith(+ { topicId: 'topic-1' },+ { signal: expect.any(AbortSignal), workspaceId: null },+ );+ expect(mockBeginFee.mock.invocationCallOrder[0]).toBeLessThan(+ mockStartSession.mock.invocationCallOrder[0],+ );+ expect(mockFinishFee).toHaveBeenCalledTimes(1);+ expect(mockFinishFee).toHaveBeenCalledWith(+ { durationMs: expect.any(Number), feeId: 'local_hetero_1_fee', reason: 'done' },+ { signal: expect.any(AbortSignal), workspaceId: null },+ );+ });++ it('holds and settles in the scope the run started in', async () => {+ await executeHeterogeneousAgent(() => createMockStore(), {+ ...defaultParams,+ workspaceId: null,+ });++ expect(mockBeginFee.mock.calls[0][1]).toMatchObject({ workspaceId: null });+ expect(mockFinishFee.mock.calls[0][1]).toMatchObject({ workspaceId: null });+ });++ /**+ * @example The user clicks Stop right after sending, while the fee hold is still pending.+ */+ it('does not start the CLI when the user stops during the fee hold', async () => {+ // Before: the executor spawned the CLI once the hold returned, though the+ // run had been stopped; the native cancel was registered only after spawn.+ const abortController = new AbortController();+ const updateTopicStatus = vi.fn();+ const store = createMockStore({+ activeTopicId: 'topic-1',+ onOperationCancel: vi.fn(),+ operations: {+ 'op-1': {+ abortController,+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ metadata: { startTime: 0 },+ },+ },+ updateTopicStatus,+ });+ mockBeginFee.mockImplementation(async () => {+ abortController.abort();+ return { feeId: 'local_hetero_1_fee' };+ });++ await executeHeterogeneousAgent(() => store, defaultParams);++ expect(mockStartSession).not.toHaveBeenCalled();+ expect(mockFinishFee).toHaveBeenCalledWith(+ expect.objectContaining({ feeId: 'local_hetero_1_fee', reason: 'interrupted' }),+ expect.anything(),+ );+ // The topic leaves the running state as any other stopped run does.+ expect(updateTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),+ );+ });++ /**+ * @example A user whose balance cannot cover the fee sends to Claude Code on Desktop.+ */+ it('does not start the CLI when the server refuses an unfunded fee', async () => {+ // Before: desktop-local runs never reported to the server, so a user with+ // no balance ran Claude Code / Codex without paying the agent run fee.+ // After: the refused hold ends the run with the fee error and no CLI.+ mockBeginFee.mockRejectedValue(new Error(ChatErrorType.InsufficientBudgetForAgentRunFee));++ await executeHeterogeneousAgent(() => createMockStore(), defaultParams);++ expect(mockStartSession).not.toHaveBeenCalled();+ expect(mockSendPrompt).not.toHaveBeenCalled();+ expect(mockUpdateMessageError).toHaveBeenCalledWith(+ 'ast-initial',+ expect.objectContaining({ type: ChatErrorType.InsufficientBudgetForAgentRunFee }),+ expect.anything(),+ );+ expect(mockFinishFee).not.toHaveBeenCalled();+ });++ it('still runs when the fee hold fails for another reason', async () => {+ mockBeginFee.mockRejectedValue(new Error('No "mutation"-procedure on path'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await executeHeterogeneousAgent(() => createMockStore(), defaultParams);++ expect(mockStartSession).toHaveBeenCalledTimes(1);+ expect(mockFinishFee).not.toHaveBeenCalled();+ consoleError.mockRestore();+ });++ it('gives the fee back when the CLI fails', async () => {+ mockSendPrompt.mockRejectedValue(new Error('Agent exited with code 1'));++ await executeHeterogeneousAgent(() => createMockStore(), defaultParams);++ expect(mockFinishFee).toHaveBeenCalledWith(+ expect.objectContaining({ feeId: 'local_hetero_1_fee', reason: 'error' }),+ expect.anything(),+ );+ });++ it('settles a stopped run as interrupted', async () => {+ const abortController = new AbortController();+ const store = createMockStore({+ onOperationCancel: vi.fn(),+ operations: {+ 'op-1': {+ abortController,+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ metadata: { startTime: 0 },+ },+ },+ });+ mockSendPrompt.mockImplementation(async (params: any) => {+ ipc.emitRawLine(params.sessionId, ccInit());+ abortController.abort();+ ipc.emitComplete(params.sessionId);+ });++ await executeHeterogeneousAgent(() => store, defaultParams);++ expect(mockFinishFee).toHaveBeenCalledWith(+ expect.objectContaining({ feeId: 'local_hetero_1_fee', reason: 'interrupted' }),+ expect.anything(),+ );+ });++ /**+ * @example The user stops a run and the cancel cleanup takes several more seconds.+ */+ it('reports the duration up to the Stop, not up to the end of cleanup', async () => {+ // Before: the server measured until `finish` arrived, after cleanup, so the+ // cleanup counted toward the stopped run's duration.+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(0);+ const abortController = new AbortController();+ const store = createMockStore({+ onOperationCancel: vi.fn(),+ operations: {+ 'op-1': {+ abortController,+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ metadata: { startTime: 0 },+ },+ },+ });+ mockSendPrompt.mockImplementation(async (params: any) => {+ ipc.emitRawLine(params.sessionId, ccInit());+ vi.setSystemTime(28_000);+ abortController.abort();+ vi.setSystemTime(40_000);+ ipc.emitComplete(params.sessionId);+ });++ try {+ await executeHeterogeneousAgent(() => store, defaultParams);+ } finally {+ vi.useRealTimers();+ }++ expect(mockFinishFee.mock.calls[0][0]).toMatchObject({ durationMs: 28_000 });+ });++ it('holds one fee across a resume fallback retry', async () => {+ mockSendPrompt.mockRejectedValueOnce({+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ message: 'No conversation found with session ID',+ });++ await executeHeterogeneousAgent(() => createMockStore(), {+ ...defaultParams,+ resumeSessionId: 'cc-stale',+ });++ expect(mockStartSession).toHaveBeenCalledTimes(2);+ expect(mockBeginFee).toHaveBeenCalledTimes(1);+ expect(mockFinishFee).toHaveBeenCalledTimes(1);+ expect(mockFinishFee).toHaveBeenCalledWith(+ expect.objectContaining({ feeId: 'local_hetero_1_fee', reason: 'done' }),+ expect.anything(),+ );+ });++ it.each([+ ['a continuation', { continuesRun: true }],+ ['a transcript replay', { replayTranscript: true, resumeSessionId: 'cc-sess-1' }],+ ['a sub-agent', { context: { ...defaultParams.context, scope: 'sub_agent' as const } }],+ [+ 'a group member',+ { context: { ...defaultParams.context, orchestrationRole: 'member' as const } },+ ],+ ])('holds no fee for %s', async (_name, overrides) => {+ await executeHeterogeneousAgent(() => createMockStore(), { ...defaultParams, ...overrides });++ expect(mockBeginFee).not.toHaveBeenCalled();+ expect(mockFinishFee).not.toHaveBeenCalled();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex d771b364094..268354e74be 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -53,7 +53,6 @@ const mockUpdateMessage = vi.fn();const mockUpdateMessageError = vi.fn();const mockUpdateToolMessage = vi.fn();const mockGetMessages = vi.fn();-const mockToastInfo = vi.fn();vi.mock('@lobehub/ui', async (importOriginal) => ({...(await importOriginal<object>()),@@ -70,7 +69,6 @@ vi.mock('@/services/message', () => ({updateToolMessage: (...args: any[]) => mockUpdateToolMessage(...args),},}));-// threadService — subagent Thread creation (CC `Task` tool_use)const mockCreateThread = vi.fn();const mockGetThreads = vi.fn();@@ -82,7 +80,6 @@ vi.mock('@/services/thread', () => ({updateThread: (...args: unknown[]) => mockUpdateThread(...args),},}));-// heterogeneousAgentService — IPC to Electron mainconst mockStartSession = vi.fn();const mockSendPrompt = vi.fn();@@ -91,7 +88,6 @@ const mockCancelSession = vi.fn();const mockGetSessionInfo = vi.fn();const mockGetClaudeCodeIdentity = vi.fn(async (..._args: any[]) => null);const mockGetCodexQuota = vi.fn(async (..._args: any[]): Promise<unknown> => null);-vi.mock('@/services/electron/heterogeneousAgent', () => ({heterogeneousAgentService: {cancelSession: (...args: unknown[]) => mockCancelSession(...args),@@ -104,8 +100,12 @@ vi.mock('@/services/electron/heterogeneousAgent', () => ({},}));-// agentQuotaService — account routing (pre-spawn) + usage ledger (per turn).-// Unmocked, both fire REAL trpc fetches from inside the executor.+// agentQuotaService (account routing + usage ledger) and the local run fee would+// fire REAL trpc fetches from inside the executor; the fee has its own test file.+vi.mock('../transports/hetero/localRunFee', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ claimLocalRunFee: async () => undefined,+}));const mockSelectAccountForAgent = vi.fn(async (..._args: any[]): Promise<unknown> => null);const mockRecordQuotaUsage = vi.fn(async (..._args: any[]) => undefined);vi.mock('@/services/agentQuota', () => ({diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 03aa86af63f..4270a93a13a 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -26,7 +26,6 @@ import {isEchoedErrorText,normalizeHeterogeneousMessageError,} from '@lobechat/heterogeneous-agents/errors';-import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';import type {ChatMessageError,ChatToolPayload,@@ -95,6 +94,8 @@ import { withHeteroContext } from '../viewedTaskPrompt';import { markUnfinishedToolsCancelled } from './cancelledTools';import { getNativeHeteroSessionBindingKey, isRecoverableResumeError } from './heteroResume';import { preserveSkippedIntervention } from './interventionAck';+import { claimLocalRunFee, type LocalRunFeeClaim, settleLocalRunFee } from './localRunFee';+import { buildLocalHeterogeneousSystemContext } from './localSystemContext';import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';import { createPendingCreateLedger } from './pendingCreateLedger';import { waitForPersistQueue } from './persistQueue';@@ -232,6 +233,8 @@ export interface HeterogeneousAgentExecutorParams {attachedFiles?: HeteroAttachedFileRef[];context: ConversationContext;contextSelections?: ContextSelection[];+ /** Continues a run that already paid its fee (restart recovery, continue-after-error). */+ continuesRun?: boolean;heterogeneousProvider: HeterogeneousProviderConfig;/** Image attachments from user message — passed to Main for vision support */imageList?: Array<{ id: string; url: string }>;@@ -250,6 +253,8 @@ export interface HeterogeneousAgentExecutorParams {/** CC session ID from previous execution in this topic (for --resume) */resumeBindingKey?: string;resumeSessionId?: string;+ /** Internal: the fee claim a resume-fallback retry inherits from its run. */+ runFee?: LocalRunFeeClaim;workingDirectory?: string;workingDirectoryConfig?: WorkingDirConfig;workspaceId?: string | null; // workspace the run started in (null = personal)@@ -270,34 +275,6 @@ export interface HeterogeneousAgentExecutionOutcome {terminalError?: boolean;}-const buildLocalHeterogeneousSystemContext = ({- agentSystemContext,- contextSelections,- pageSelections,- previousConversation,-}: {- agentSystemContext?: string;- contextSelections?: ContextSelection[];- pageSelections?: PageSelection[];- previousConversation?: string;-}): string | undefined => {- const parts: string[] = [];-- if (agentSystemContext?.trim()) parts.push(agentSystemContext.trim());- if (previousConversation) parts.push(previousConversation);-- const selectionContext =- contextSelections && contextSelections.length > 0- ? formatContextSelections(contextSelections)- : pageSelections && pageSelections.length > 0- ? formatPageSelections(pageSelections)- : '';-- if (selectionContext) parts.push(selectionContext);-- return parts.length > 0 ? parts.join('\n\n') : undefined;-};-const getTopicMetadataById = (store: ChatStore,topicId: string | undefined,@@ -635,6 +612,7 @@ export const executeHeterogeneousAgent = async (let ipcRunSessionId: string | undefined;let unsubscribe: (() => void) | undefined;let completed = false;+ const runFee: LocalRunFeeClaim = params.runFee ?? {};let fallbackPromise: Promise<void> | undefined;let resumeFallbackTriggered = false;@@ -1031,7 +1009,12 @@ export const executeHeterogeneousAgent = async ({ ns: 'chat' },),);- await executeHeterogeneousAgent(get, { ...params, resumeSessionId: undefined, workspaceId });+ await executeHeterogeneousAgent(get, {+ ...params,+ resumeSessionId: undefined,+ runFee,+ workspaceId,+ });})();return true;@@ -1865,6 +1848,14 @@ export const executeHeterogeneousAgent = async (return;}+ // A run this desktop spawns never reaches `execAgent`: it reports its fee here,+ // and a refused fee, or a Stop while the hold was pending, ends it before the CLI starts.+ const feeStop = params.runFee+ ? undefined+ : await claimLocalRunFee(runFee, { ...params, workspaceId }, abortSignal);+ if (feeStop === 'stopped') return void writeTopicStatus('active');+ if (feeStop) return void (await persistTerminalError(feeStop));+try {// Account routing: realize the pinned/balanced account choice as spawn env// (CLAUDE_CONFIG_DIR profile). Unbound agents get {} and spawn exactly as@@ -2672,6 +2663,15 @@ export const executeHeterogeneousAgent = async (console.error('[HeterogeneousAgent] status reconcile backstop failed:', err);}}+ // The resume-fallback retry inherited the claim and settles it.+ if (!resumeFallbackTriggered) {+ const terminal = deferredTerminalEvent as AgentStreamEvent | null;+ await settleLocalRunFee(runFee, {+ aborted: isAborted(),+ failed: terminalErrorPersisted,+ terminal,+ });+ }}if (fallbackPromise) {diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/localRunFee.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/localRunFee.tsnew file mode 100644index 00000000000..83816fa8cd9--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/localRunFee.ts@@ -0,0 +1,172 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type { ChatMessageError, ConversationContext } from '@lobechat/types';+import { ChatErrorType } from '@lobechat/types';++import { aiAgentService } from '@/services/aiAgent';++/**+ * The run fee of an external agent this desktop spawns itself. Such a run+ * never passes through the server's `execAgent`, so the executor reports it:+ * {@link claimLocalRunFee} before spawning the CLI, {@link settleLocalRunFee}+ * once it ends.+ */+export interface LocalRunFeeClaim {+ /** Set while a fee is held; cleared once it is settled. */+ feeId?: string | null;+ /** When the hold was requested, the start of the duration Desktop reports. */+ startedAt?: number;+ /** When the user stopped the run; cleanup after it does not count toward its duration. */+ stoppedAt?: number;+ /** Scope the run started in; the fee is held and settled there, whatever the UI switches to. */+ workspaceId?: string | null;+}++export type LocalRunEndReason = 'done' | 'error' | 'interrupted';++/** A hold slower than this lets the run start without a fee rather than stall the CLI. */+export const LOCAL_RUN_FEE_HOLD_TIMEOUT_MS = 5000;++/** A settle slower than this is dropped so the run can finish; the hold then expires by itself. */+export const LOCAL_RUN_FEE_SETTLE_TIMEOUT_MS = 10_000;++/**+ * Whether this run reports its fee, with the exemptions of the server's+ * `shouldHoldRunFee`: a continuation of a run that already held one (restart+ * recovery, continue-after-error, transcript replay) and a sub-agent or group+ * member, which are steps of their root run. Workspace runs are exempted by the+ * server.+ */+export const shouldClaimLocalRunFee = ({+ context,+ continuesRun,+ replayTranscript,+}: {+ context: ConversationContext;+ continuesRun?: boolean;+ replayTranscript?: boolean;+}): boolean =>+ !continuesRun &&+ !replayTranscript &&+ context.scope !== 'sub_agent' &&+ !context.isSubAgent &&+ context.orchestrationRole !== 'member';++const unfundedRunFeeError = (): ChatMessageError => ({+ body: {},+ message: `response.${ChatErrorType.InsufficientBudgetForAgentRunFee}`,+ type: ChatErrorType.InsufficientBudgetForAgentRunFee,+});++/**+ * Holds the fee, or returns the error to show when the server refuses it+ * because the balance cannot cover it; the CLI must not start then.+ *+ * Any other failure (a server without this endpoint, a network blip, a hold+ * slower than {@link LOCAL_RUN_FEE_HOLD_TIMEOUT_MS}) lets the run go ahead+ * without a fee, as the server's own hold does on failures that are not a+ * refusal: a run fee is not worth failing a run the user started.+ *+ * Returns `'stopped'`, with any held fee already given back as interrupted,+ * when the user stopped the run before or during the hold: the CLI must not+ * start then either.+ */+export const claimLocalRunFee = async (+ claim: LocalRunFeeClaim,+ run: {+ context: ConversationContext;+ continuesRun?: boolean;+ replayTranscript?: boolean;+ workspaceId?: string | null;+ },+ /** The operation's Stop signal: it ends a pending hold and marks when the run stopped. */+ abortSignal?: AbortSignal,+): Promise<ChatMessageError | 'stopped' | undefined> => {+ if (abortSignal?.aborted) return 'stopped';+ if (!shouldClaimLocalRunFee(run)) return;+ claim.startedAt = Date.now();+ claim.workspaceId = run.workspaceId ?? null;+ abortSignal?.addEventListener('abort', () => (claim.stoppedAt ??= Date.now()), { once: true });+ const timeout = AbortSignal.timeout(LOCAL_RUN_FEE_HOLD_TIMEOUT_MS);+ try {+ const { feeId } = await aiAgentService.beginLocalHeteroRunFee(+ { topicId: run.context.topicId ?? undefined },+ {+ signal: abortSignal ? AbortSignal.any([timeout, abortSignal]) : timeout,+ workspaceId: claim.workspaceId,+ },+ );+ claim.feeId = feeId;+ } catch (error) {+ if ((error as Error)?.message === ChatErrorType.InsufficientBudgetForAgentRunFee)+ return unfundedRunFeeError();+ if (!abortSignal?.aborted)+ console.error('[HeterogeneousAgent] run fee hold failed; running without it:', error);+ }+ if (!abortSignal?.aborted) return;+ await settleLocalRunFee(claim, { aborted: true, failed: false });+ return 'stopped';+};++/**+ * Charges or gives back the held fee. Runs at most once per claim, and never+ * throws or hangs: an unsettled hold expires on the server by itself.+ */+export const settleLocalRunFee = async (+ claim: LocalRunFeeClaim,+ ending: {+ aborted: boolean;+ /** The executor persisted a terminal error. */+ failed: boolean;+ /** The deferred terminal stream event, when the CLI sent one. */+ terminal?: AgentStreamEvent | null;+ },+) => {+ const feeId = claim.feeId;+ if (!feeId) return;+ claim.feeId = undefined;+ const reason = resolveLocalRunEndReason({+ aborted: ending.aborted,+ failed: ending.failed || ending.terminal?.type === 'error',+ runtimeEndReason: (ending.terminal?.data as { reason?: string } | undefined)?.reason,+ });+ const endedAt = claim.stoppedAt ?? Date.now();+ try {+ await aiAgentService.finishLocalHeteroRunFee(+ {+ durationMs:+ claim.startedAt === undefined ? undefined : Math.max(0, endedAt - claim.startedAt),+ feeId,+ reason,+ },+ {+ signal: AbortSignal.timeout(LOCAL_RUN_FEE_SETTLE_TIMEOUT_MS),+ workspaceId: claim.workspaceId ?? null,+ },+ );+ } catch (error) {+ console.error('[HeterogeneousAgent] run fee settle failed:', error);+ }+};++/**+ * The end reason the server's fee rules read, from how the executor saw the run+ * end. A stop counts as `interrupted`, which the deployment's rules settle; a failure+ * gives the fee back; any other ending, including a run that exits cleanly+ * without an explicit reason, is a finished run.+ */+export const resolveLocalRunEndReason = ({+ aborted,+ failed,+ runtimeEndReason,+}: {+ aborted: boolean;+ /** The executor persisted a terminal error, or the stream ended on one. */+ failed: boolean;+ /** `agent_runtime_end` reason, when the CLI reported one. */+ runtimeEndReason?: string;+}): LocalRunEndReason => {+ if (aborted || runtimeEndReason === 'interrupted' || runtimeEndReason === 'cancelled')+ return 'interrupted';+ if (failed || runtimeEndReason === 'error') return 'error';+ return 'done';+};diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/localSystemContext.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/localSystemContext.tsnew file mode 100644index 00000000000..8a800f4544e--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/localSystemContext.ts@@ -0,0 +1,31 @@+import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';+import type { ContextSelection, PageSelection } from '@lobechat/types';++/** System context a locally spawned CLI receives with the prompt. */+export const buildLocalHeterogeneousSystemContext = ({+ agentSystemContext,+ contextSelections,+ pageSelections,+ previousConversation,+}: {+ agentSystemContext?: string;+ contextSelections?: ContextSelection[];+ pageSelections?: PageSelection[];+ previousConversation?: string;+}): string | undefined => {+ const parts: string[] = [];++ if (agentSystemContext?.trim()) parts.push(agentSystemContext.trim());+ if (previousConversation) parts.push(previousConversation);++ const selectionContext =+ contextSelections && contextSelections.length > 0+ ? formatContextSelections(contextSelections)+ : pageSelections && pageSelections.length > 0+ ? formatPageSelections(pageSelections)+ : '';++ if (selectionContext) parts.push(selectionContext);++ return parts.length > 0 ? parts.join('\n\n') : undefined;+};