π€― 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): account for sub-agent spend in the parent's usage (#17116)
Arvin Xuc99fe580c853
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 435fa185b2d..e864d16558f 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -2068,6 +2068,9 @@ export class AgentRuntimeService {model: state?.modelRuntimeConfig?.model,phase: 'subagent_progress',toolMessageId: anchor.toolMessageId,+ totalCost: state?.cost?.total,+ totalInputTokens: state?.usage?.llm?.tokens?.input,+ totalOutputTokens: state?.usage?.llm?.tokens?.output,totalTokens: state?.usage?.llm?.tokens?.total,totalToolCalls: state?.usage?.tools?.totalCalls,},@@ -2157,6 +2160,14 @@ export class AgentRuntimeService {model: finalState?.modelRuntimeConfig?.model,status: failed ? 'error' : 'completed',threadId,+ // The child's spend rides on this anchor row so the parent's usage tray can+ // account for it. The tray sums per-MESSAGE usage, and the child's own+ // assistant messages live in an isolation thread the parent never loads β+ // this row is the only place the child's cost surfaces in the parent's own+ // message list.+ totalCost: finalState?.cost?.total,+ totalInputTokens: finalState?.usage?.llm?.tokens?.input,+ totalOutputTokens: finalState?.usage?.llm?.tokens?.output,totalToolCalls: finalState?.usage?.tools?.totalCalls,totalTokens: finalState?.usage?.llm?.tokens?.total,},@@ -2346,6 +2357,14 @@ export class AgentRuntimeService {model: finalState?.modelRuntimeConfig?.model,status: failed ? 'error' : 'completed',threadId,+ // The child's spend rides on this anchor row so the parent's usage tray can+ // account for it. The tray sums per-MESSAGE usage, and the child's own+ // assistant messages live in an isolation thread the parent never loads β+ // this row is the only place the child's cost surfaces in the parent's own+ // message list.+ totalCost: finalState?.cost?.total,+ totalInputTokens: finalState?.usage?.llm?.tokens?.input,+ totalOutputTokens: finalState?.usage?.llm?.tokens?.output,totalToolCalls: finalState?.usage?.tools?.totalCalls,totalTokens: finalState?.usage?.llm?.tokens?.total,},diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 85934049ba3..e47fa8b35a6 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -5,6 +5,7 @@ import debug from 'debug';import {AgentOperationModel,+ type ChildUsageRollup,type RecordOperationStartParams,} from '@/database/models/agentOperation';import { MessageModel } from '@/database/models/message';@@ -211,6 +212,26 @@ export class CompletionLifecycle {// dispatchHooks call (when the op resumes and truly ends) overwrites both.const completedAt = isParkedStatus(status) ? undefined : new Date();+ // Fold every child operation's spend (callSubAgent children, isolated group+ // members) into the parent's totals, so an op's row accounts for the whole+ // tree it forked rather than only the tokens its own turns burned.+ //+ // Re-derived from the child rows on every write instead of accumulated onto+ // this one: `recordCompletion` is a wholesale SET, and this method runs again+ // each time the op parks and resumes β an additive rollup would multiply. The+ // SUM is exact however often it re-runs.+ //+ // Skipped for sub-agents and group members themselves: nested sub-agents are+ // rejected up front, so a child never has children of its own and the query+ // would always return zero.+ const rollup =+ metadata?.isSubAgent === true ? undefined : await this.sumChildUsage(operationId);++ const add = (own: number | null | undefined, child: number): number | null => {+ if (!child) return own ?? null;+ return (own ?? 0) + child;+ };+try {await this.agentOperationModel.recordCompletion(operationId, {completedAt,@@ -218,7 +239,7 @@ export class CompletionLifecycle {cost: state?.cost ?? null,error: state?.error ?? null,interruption: state?.interruption ?? null,- llmCalls: state?.usage?.llm?.apiCalls ?? null,+ llmCalls: add(state?.usage?.llm?.apiCalls, rollup?.llmCalls ?? 0),// Backfill the executed model/provider when the terminal state carries// them. The in-process runtime sets neither on `state` (the op already// holds them from recordStart) so these stay undefined and recordCompletion@@ -231,12 +252,16 @@ export class CompletionLifecycle {provider: state?.provider,status,stepCount: state?.stepCount ?? null,- toolCalls: state?.usage?.tools?.totalCalls ?? null,- totalCost: state?.cost?.total ?? null,- totalInputTokens: state?.usage?.llm?.tokens?.input ?? null,- totalOutputTokens: state?.usage?.llm?.tokens?.output ?? null,- totalTokens: state?.usage?.llm?.tokens?.total ?? null,+ toolCalls: add(state?.usage?.tools?.totalCalls, rollup?.toolCalls ?? 0),+ totalCost: add(state?.cost?.total, rollup?.totalCost ?? 0),+ totalInputTokens: add(state?.usage?.llm?.tokens?.input, rollup?.totalInputTokens ?? 0),+ totalOutputTokens: add(state?.usage?.llm?.tokens?.output, rollup?.totalOutputTokens ?? 0),+ totalTokens: add(state?.usage?.llm?.tokens?.total, rollup?.totalTokens ?? 0),traceS3Key,+ // The `usage` / `cost` blobs stay the op's OWN accumulator, un-rolled-up:+ // they are the runtime's counter, and the executor reads them back as state+ // (the cost-limit gate compares `state.cost.total` against the budget). Only+ // the scalar columns β the reporting surface β carry the whole tree.usage: state?.usage ?? null,});} catch (error) {@@ -244,6 +269,16 @@ export class CompletionLifecycle {}}+ /** Best-effort child-usage rollup β a DB hiccup must not fail the completion write. */+ private async sumChildUsage(operationId: string): Promise<ChildUsageRollup | undefined> {+ try {+ return await this.agentOperationModel.sumChildUsage(operationId);+ } catch (error) {+ log('[%s] Failed to sum child operation usage (non-fatal): %O', operationId, error);+ return undefined;+ }+ }+/*** Extract a human-readable error message from the agent state error object.* Handles both raw `ChatCompletionErrorPayload` (from runtime.step catch) anddiff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex b39008f3c6d..649fdb67be9 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -149,6 +149,9 @@ export interface SubAgentProgressData extends StepCompleteData {phase: 'subagent_progress';/** The parked parent's placeholder tool message these stats belong to. */toolMessageId: string;+ totalCost?: number;+ totalInputTokens?: number;+ totalOutputTokens?: number;totalTokens?: number;totalToolCalls?: number;}diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts b/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.tsnew file mode 100644index 00000000000..48e06f8af4b--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts@@ -0,0 +1,71 @@+import type { BuiltinToolContext } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { lobeAgentExecutor } from './index';++// The executor module pulls in renderer aliases (`@/services/notebook`,+// `@/store/notebook`) that don't resolve in this package's vitest env β stub them,+// same as `builtin-tool-local-system` does. Nothing here touches the notebook path.+vi.mock('@/services/notebook', () => ({ notebookService: {} }));+vi.mock('@/store/notebook', () => ({ useNotebookStore: { getState: () => ({}) } }));++const params = { description: 'research', instruction: 'go look it up' };++const createContext = (run: ReturnType<typeof vi.fn>) =>+ ({ messageId: 'tool-msg-1', subAgent: { run } }) as unknown as BuiltinToolContext;++describe('lobeAgentExecutor.callSubAgent', () => {+ // A client sub-agent's own messages live in an isolation thread the parent never+ // loads, so this tool row's `state` is the ONLY place its spend reaches the+ // parent's usage tray. Persisting tokens but not cost / the token split makes a+ // client sub-agent read as free β the server path's completion bridge writes all+ // five, and this one has to match.+ it('persists the full spend the runner reports, not just the token total', async () => {+ const run = vi.fn().mockResolvedValue({+ model: 'deepseek-v4-flash',+ result: 'done',+ success: true,+ threadId: 'thd_1',+ totalCost: 0.42,+ totalInputTokens: 4000,+ totalOutputTokens: 1000,+ totalToolCalls: 6,+ totalTokens: 5000,+ });++ const result = await lobeAgentExecutor.callSubAgent(params, createContext(run));++ expect(result.success).toBe(true);+ expect(result.state).toEqual({+ model: 'deepseek-v4-flash',+ threadId: 'thd_1',+ totalCost: 0.42,+ totalInputTokens: 4000,+ totalOutputTokens: 1000,+ totalToolCalls: 6,+ totalTokens: 5000,+ });+ });++ it('surfaces a failed run as a tool error without state', async () => {+ const run = vi.fn().mockResolvedValue({+ error: 'boom',+ result: '',+ success: false,+ threadId: '',+ });++ const result = await lobeAgentExecutor.callSubAgent(params, createContext(run));++ expect(result).toEqual({ content: 'boom', success: false });+ });++ it('fails when the runtime provides no sub-agent runner', async () => {+ const result = await lobeAgentExecutor.callSubAgent(+ params,+ {} as unknown as BuiltinToolContext,+ );++ expect(result.success).toBe(false);+ });+});diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.tsindex 85bdde50d19..5eddd997b53 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts@@ -402,22 +402,45 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {return { content: 'Sub-agent execution is not available in this runtime.', success: false };}- const { result, threadId, success, error, model, totalToolCalls, totalTokens } =- await ctx.subAgent.run({- description,- inheritMessages,- instruction,- timeout,- toolMessageId: ctx.messageId,- });+ const {+ result,+ threadId,+ success,+ error,+ model,+ totalCost,+ totalInputTokens,+ totalOutputTokens,+ totalToolCalls,+ totalTokens,+ } = await ctx.subAgent.run({+ description,+ inheritMessages,+ instruction,+ timeout,+ toolMessageId: ctx.messageId,+ });if (!success) {return { content: error ?? 'Sub-agent execution failed.', success: false };}+ // Cost + the token split are persisted alongside the totals because this row is+ // where the parent's usage tray reads a sub-agent's spend β the child's own+ // messages sit in an isolation thread the parent never loads, so anything left+ // off here is invisible to the parent's ledger. Mirrors the shape the server+ // path's completion bridge backfills.return {content: result,- state: { model, threadId, totalToolCalls, totalTokens },+ state: {+ model,+ threadId,+ totalCost,+ totalInputTokens,+ totalOutputTokens,+ totalToolCalls,+ totalTokens,+ },success: true,};};diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.tsindex 393ee1bacb8..77c88dbb2e6 100644--- a/packages/builtin-tool-lobe-agent/src/types.ts+++ b/packages/builtin-tool-lobe-agent/src/types.ts@@ -64,6 +64,17 @@ export interface CallSubAgentParams {export interface SubAgentRunStats {/** Model the sub-agent ran on */model?: string;+ /**+ * Cost of the sub-agent run. Carried here (rather than only on the child's own+ * messages) because the parent's usage tray sums per-message usage, and the+ * sub-agent's messages live in an isolation thread the parent never loads β+ * this tool message is where the child's spend enters the parent's ledger.+ */+ totalCost?: number;+ /** Input tokens consumed by the sub-agent run */+ totalInputTokens?: number;+ /** Output tokens produced by the sub-agent run */+ totalOutputTokens?: number;/** Total tokens consumed by the sub-agent run */totalTokens?: number;/** Number of tool calls the sub-agent made */diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex ddc7f68ebe6..d435de8afa5 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -210,6 +210,110 @@ describe('AgentOperationModel', () => {});});+ describe('sumChildUsage', () => {+ const seedChild = async (+ model: AgentOperationModel,+ id: string,+ parentOperationId: string,+ usage: { llmCalls: number; toolCalls: number; totalCost: number; totalTokens: number },+ ) => {+ await model.recordStart({ operationId: id, parentOperationId });+ await model.recordCompletion(id, {+ completionReason: 'done',+ llmCalls: usage.llmCalls,+ status: 'done',+ toolCalls: usage.toolCalls,+ totalCost: usage.totalCost,+ totalInputTokens: usage.totalTokens,+ totalOutputTokens: 0,+ totalTokens: usage.totalTokens,+ });+ };++ it('sums every child of the parent', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId: 'parent' });+ await seedChild(model, 'child-a', 'parent', {+ llmCalls: 2,+ toolCalls: 3,+ totalCost: 0.25,+ totalTokens: 1000,+ });+ await seedChild(model, 'child-b', 'parent', {+ llmCalls: 1,+ toolCalls: 4,+ totalCost: 0.75,+ totalTokens: 2000,+ });++ const rollup = await model.sumChildUsage('parent');++ expect(rollup).toEqual({+ llmCalls: 3,+ toolCalls: 7,+ totalCost: 1,+ totalInputTokens: 3000,+ totalOutputTokens: 0,+ totalTokens: 3000,+ });+ });++ // The whole reason this is a read-time SUM: the sub-agent completion bridge is+ // contractually re-deliverable, so an accumulation onto the parent row would+ // double-count. Re-deriving is exact however many times it runs.+ it('is idempotent β re-deriving does not accumulate', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId: 'parent' });+ await seedChild(model, 'child-a', 'parent', {+ llmCalls: 1,+ toolCalls: 1,+ totalCost: 0.5,+ totalTokens: 1234,+ });++ const first = await model.sumChildUsage('parent');+ const second = await model.sumChildUsage('parent');++ expect(second).toEqual(first);+ expect(second.totalTokens).toBe(1234);+ });++ it('returns zeroes for an operation with no children', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId: 'lonely' });++ expect(await model.sumChildUsage('lonely')).toEqual({+ llmCalls: 0,+ toolCalls: 0,+ totalCost: 0,+ totalInputTokens: 0,+ totalOutputTokens: 0,+ totalTokens: 0,+ });+ });++ it("does not sum another user's children", async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const attacker = new AgentOperationModel(serverDB, otherUserId);+ await model.recordStart({ operationId: 'parent' });+ await seedChild(model, 'child-a', 'parent', {+ llmCalls: 1,+ toolCalls: 1,+ totalCost: 0.5,+ totalTokens: 1000,+ });++ expect(await attacker.sumChildUsage('parent')).toEqual({+ llmCalls: 0,+ toolCalls: 0,+ totalCost: 0,+ totalInputTokens: 0,+ totalOutputTokens: 0,+ totalTokens: 0,+ });+ });+ });+describe('getMaxDurationSeconds', () => {it('returns the longest wall-clock duration, ignoring in-flight and other users', async () => {const model = new AgentOperationModel(serverDB, userId);diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex fb8cc36e3ec..fa145fa119d 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -43,6 +43,16 @@ export interface RecordOperationStartParams {trigger?: string;}+/** Terminal usage summed across every child operation of one parent. All-zero when it has none. */+export interface ChildUsageRollup {+ llmCalls: number;+ toolCalls: number;+ totalCost: number;+ totalInputTokens: number;+ totalOutputTokens: number;+ totalTokens: number;+}+export interface RecordOperationCompletionParams {completedAt?: Date;completionReason?:@@ -161,6 +171,50 @@ export class AgentOperationModel {.where(and(eq(agentOperations.id, operationId), this.ownership()));}+ /**+ * Sum the terminal usage of every child operation forked from `parentOperationId`+ * (`callSubAgent` children, isolated group members).+ *+ * A read-time SUM rather than an accumulation on the parent row, because the+ * sub-agent completion bridge is contractually re-deliverable (QStash redelivery,+ * plus the watchdog abandon path synthesizing the same call) and its safety rests+ * on every side effect being overwrite-idempotent or CAS-guarded β an `x += child`+ * is neither, and would double-count on the second delivery. Re-deriving the sum is+ * exact no matter how many times it runs, and self-heals if a child row lands late.+ *+ * Children are already terminal by the time a parent completes: `persistCompletion`+ * writes the child's row *before* dispatching its `onComplete` hooks, and the bridge+ * that unparks the parent IS one of those hooks.+ */+ async sumChildUsage(parentOperationId: string): Promise<ChildUsageRollup> {+ const [row] = await this.db+ .select({+ llmCalls: sql<string | null>`sum(${agentOperations.llmCalls})`,+ toolCalls: sql<string | null>`sum(${agentOperations.toolCalls})`,+ totalCost: sql<string | null>`sum(${agentOperations.totalCost})`,+ totalInputTokens: sql<string | null>`sum(${agentOperations.totalInputTokens})`,+ totalOutputTokens: sql<string | null>`sum(${agentOperations.totalOutputTokens})`,+ totalTokens: sql<string | null>`sum(${agentOperations.totalTokens})`,+ })+ .from(agentOperations)+ .where(and(eq(agentOperations.parentOperationId, parentOperationId), this.ownership()));++ // `sum()` over zero rows is NULL, and numeric sums come back as strings.+ const num = (value: string | null | undefined): number => {+ const parsed = Number(value ?? 0);+ return Number.isFinite(parsed) ? parsed : 0;+ };++ return {+ llmCalls: num(row?.llmCalls),+ toolCalls: num(row?.toolCalls),+ totalCost: num(row?.totalCost),+ totalInputTokens: num(row?.totalInputTokens),+ totalOutputTokens: num(row?.totalOutputTokens),+ totalTokens: num(row?.totalTokens),+ };+ }+async findById(operationId: string) {const [row] = await this.db.select()diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 5a88a074cfa..c7cb3a08b57 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -838,6 +838,17 @@ export interface RunSubAgentResult {success: boolean;/** The isolation thread holding the sub-agent's full message trace */threadId: string;+ /**+ * Cost of the sub-agent run. Lands on the tool message's `pluginState`, which is+ * how the parent's usage tray accounts for a sub-agent at all: the tray sums+ * per-MESSAGE usage, and the child's own messages live in an isolation thread the+ * parent never loads. Omit it and the tray reports the child as free.+ */+ totalCost?: number;+ /** Input tokens consumed by the sub-agent run */+ totalInputTokens?: number;+ /** Output tokens produced by the sub-agent run */+ totalOutputTokens?: number;/** Total tokens consumed by the sub-agent run */totalTokens?: number;/** Number of tool calls the sub-agent made */diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 8b4a53b46db..013af95d082 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -946,13 +946,16 @@ export class StreamingExecutorActionImpl {const resultContent = lastAssistant?.content || 'Task completed';const totalToolCalls = subTaskMessages.filter((m) => m.role === 'tool').length;const { usage, cost, model } = runtimeResult || {};+ const totalCost = cost?.total;+ const totalInputTokens = usage?.llm?.tokens?.input;+ const totalOutputTokens = usage?.llm?.tokens?.output;const totalTokens = usage?.llm?.tokens?.total;// 8. Persist final Thread status + metadataawait aiAgentService.updateClientTaskThreadStatus({completionReason: 'done',metadata: {- totalCost: cost?.total,+ totalCost,totalMessages: subTaskMessages.length,totalTokens,totalToolCalls,@@ -964,7 +967,22 @@ export class StreamingExecutorActionImpl {this.#get().completeOperation(taskOperationId);log('[%s] Completed, result %d chars', logId, resultContent.length);- return { model, result: resultContent, success: true, threadId, totalToolCalls, totalTokens };+ // Cost + the token split ride back to the caller, not just the total: they+ // land on the tool message's pluginState, which is the only place the parent's+ // usage tray can see a sub-agent's spend (its messages are in a thread the+ // parent never loads). Returning tokens alone makes a client sub-agent read as+ // free.+ return {+ model,+ result: resultContent,+ success: true,+ threadId,+ totalCost,+ totalInputTokens,+ totalOutputTokens,+ totalToolCalls,+ totalTokens,+ };} catch (error) {const errorMessage = error instanceof Error ? error.message : 'Unknown error';log('[%s] Error: %O', logId, error);diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex 65eb4f78f0e..79d5d62bb4a 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -813,6 +813,9 @@ export const createGatewayEventHandler = (type: 'updatePluginState',value: {model: progress.model,+ totalCost: progress.totalCost,+ totalInputTokens: progress.totalInputTokens,+ totalOutputTokens: progress.totalOutputTokens,totalTokens: progress.totalTokens,totalToolCalls: progress.totalToolCalls,},diff --git a/src/utils/operationUsageMetrics.test.ts b/src/utils/operationUsageMetrics.test.tsindex 3e5dffada39..a71ca4ed3e2 100644--- a/src/utils/operationUsageMetrics.test.ts+++ b/src/utils/operationUsageMetrics.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import {addUsageToOperationMetrics,calculateOperationUsageMetrics,+ EMPTY_OPERATION_USAGE_METRICS,hasOperationUsageMetrics,} from './operationUsageMetrics';@@ -58,6 +59,120 @@ describe('operationUsageMetrics', () => {});});+ describe('sub-agent spend', () => {+ const subAgentTool = (pluginState: any, parentId = 'assistant') => ({+ id: 'tool-msg',+ parentId,+ plugin: { identifier: 'lobe-agent' },+ pluginState,+ role: 'tool',+ });++ // The sub-agent's own assistant turns live in an isolation thread the parent+ // never loads, so its callSubAgent tool row is the ONLY place its spend can+ // enter the parent's tray.+ it("folds a finished sub-agent's spend in via its callSubAgent tool row", () => {+ const metrics = calculateOperationUsageMetrics(+ [+ { id: 'assistant', role: 'assistant', usage: { cost: 0.01, totalTokens: 100 } },+ subAgentTool({+ status: 'completed',+ totalCost: 0.5,+ totalInputTokens: 4000,+ totalOutputTokens: 1000,+ totalTokens: 5000,+ }),+ ] as any,+ new Set(['op-1']),+ { assistant: ['op-1'] },+ );++ expect(metrics).toEqual({+ totalCost: 0.51,+ totalInputTokens: 4000,+ totalOutputTokens: 1000,+ totalTokens: 5100,+ });+ });++ // A tool row is never a key in operationsByMessage β only assistant messages+ // are registered there β so attribution has to go through parentId.+ it('attributes the tool row through its parent assistant, not its own id', () => {+ const metrics = calculateOperationUsageMetrics(+ [subAgentTool({ totalCost: 0.5, totalTokens: 5000 })] as any,+ new Set(['op-1']),+ { 'tool-msg': ['op-1'] },+ );++ expect(metrics).toEqual(EMPTY_OPERATION_USAGE_METRICS);+ });++ it('ignores a sub-agent belonging to a different operation', () => {+ const metrics = calculateOperationUsageMetrics(+ [subAgentTool({ totalCost: 0.5, totalTokens: 5000 })] as any,+ new Set(['op-1']),+ { assistant: ['op-2'] },+ );++ expect(metrics).toEqual(EMPTY_OPERATION_USAGE_METRICS);+ });++ it('ignores tool rows from other builtins', () => {+ const metrics = calculateOperationUsageMetrics(+ [+ {+ id: 'tool-msg',+ parentId: 'assistant',+ plugin: { identifier: 'lobe-web-browsing' },+ pluginState: { totalCost: 99, totalTokens: 99_999 },+ role: 'tool',+ },+ ] as any,+ new Set(['op-1']),+ { assistant: ['op-1'] },+ );++ expect(metrics).toEqual(EMPTY_OPERATION_USAGE_METRICS);+ });++ it('uses the live progress totals while the sub-agent is still running', () => {+ const metrics = calculateOperationUsageMetrics(+ [+ subAgentTool({ progress: { totalCost: 0.2, totalTokens: 2000 }, status: 'pending' }),+ ] as any,+ new Set(['op-1']),+ { assistant: ['op-1'] },+ );++ expect(metrics).toEqual({+ totalCost: 0.2,+ totalInputTokens: 0,+ totalOutputTokens: 0,+ totalTokens: 2000,+ });+ });++ // Once the bridge backfills the authoritative flat totals, a stale live sample+ // must not win β otherwise the tray would visibly regress at the end of a run.+ it('prefers the backfilled totals over a stale live sample', () => {+ const metrics = calculateOperationUsageMetrics(+ [+ subAgentTool({+ progress: { totalCost: 0.2, totalTokens: 2000 },+ status: 'completed',+ totalCost: 0.5,+ totalTokens: 5000,+ }),+ ] as any,+ new Set(['op-1']),+ { assistant: ['op-1'] },+ );++ expect(metrics.totalCost).toBe(0.5);+ expect(metrics.totalTokens).toBe(5000);+ });+ });+describe('addUsageToOperationMetrics', () => {it('adds a per-step usage delta onto existing operation metrics', () => {const metrics = addUsageToOperationMetrics(diff --git a/src/utils/operationUsageMetrics.ts b/src/utils/operationUsageMetrics.tsindex 5f23dfcd1bd..5986de3a6e2 100644--- a/src/utils/operationUsageMetrics.ts+++ b/src/utils/operationUsageMetrics.ts@@ -14,10 +14,51 @@ export interface OperationUsageMetrics {interface OperationUsageMessage {id: string;+ /** Owning assistant message β how a tool row is attributed to an operation. */+ parentId?: string | null;+ plugin?: { identifier?: string } | null;+ pluginState?: SubAgentSpend | null;role?: string;usage?: OperationUsageLike | null;}+/**+ * A finished sub-agent's spend, as the completion bridge writes it onto the+ * `callSubAgent` tool message β plus the live totals streamed while it runs.+ */+interface SubAgentSpend {+ progress?: SubAgentSpend | null;+ totalCost?: number | null;+ totalInputTokens?: number | null;+ totalOutputTokens?: number | null;+ totalTokens?: number | null;+}++/**+ * The builtin whose tool messages anchor a forked child run.+ *+ * A sub-agent's own assistant messages live in an isolation thread the parent+ * never loads, so they can never reach this sum. Its `callSubAgent` tool message+ * β which DOES sit in the parent's list β is where the child's spend enters the+ * parent's ledger.+ */+const SUB_AGENT_TOOL_IDENTIFIER = 'lobe-agent';++const subAgentSpendToMetrics = (state?: SubAgentSpend | null): OperationUsageMetrics => {+ // The flat fields are the authoritative totals the bridge backfills when the+ // child finishes; `progress` holds the live ones streamed while it runs. Prefer+ // the former so the tray can't regress to a stale sample once the run ends.+ const spend =+ state?.totalTokens === undefined && state?.totalCost === undefined ? state?.progress : state;++ return {+ totalCost: normalizeNumber(spend?.totalCost),+ totalInputTokens: normalizeNumber(spend?.totalInputTokens),+ totalOutputTokens: normalizeNumber(spend?.totalOutputTokens),+ totalTokens: normalizeNumber(spend?.totalTokens),+ };+};+const normalizeNumber = (value: unknown): number => {if (typeof value !== 'number' || !Number.isFinite(value)) return 0;return value;@@ -73,13 +114,28 @@ export const calculateOperationUsageMetrics = (let metrics: OperationUsageMetrics = EMPTY_OPERATION_USAGE_METRICS;+ const belongsToOperation = (messageId?: string | null): boolean =>+ !!messageId && !!operationsByMessage[messageId]?.some((id) => operationIds.has(id));+for (const message of messages) {- if (message.role !== 'assistant') continue;+ if (message.role === 'assistant') {+ if (!belongsToOperation(message.id)) continue;- const messageOperationIds = operationsByMessage[message.id];- if (!messageOperationIds?.some((id) => operationIds.has(id))) continue;+ metrics = addUsageToOperationMetrics(metrics, message.usage);+ continue;+ }- metrics = addUsageToOperationMetrics(metrics, message.usage);+ // A sub-agent's spend, folded in via its `callSubAgent` tool row. Attributed+ // through `parentId` β the assistant turn that made the call β because only+ // assistant messages are registered in `operationsByMessage`; a tool row is+ // never a key there.+ if (+ message.role === 'tool' &&+ message.plugin?.identifier === SUB_AGENT_TOOL_IDENTIFIER &&+ belongsToOperation(message.parentId)+ ) {+ metrics = mergeOperationUsageMetrics(metrics, subAgentSpendToMetrics(message.pluginState));+ }}return metrics;