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(chat): derive operation token usage from messages, not a parallel accumulation (#15819)

Arvin Xu32cf754ae3d0
diff --git a/src/features/Conversation/ChatInput/OpStatusTray.tsx b/src/features/Conversation/ChatInput/OpStatusTray.tsx
index ad9d013012b..6792dfe1101 100644
--- a/src/features/Conversation/ChatInput/OpStatusTray.tsx
+++ b/src/features/Conversation/ChatInput/OpStatusTray.tsx
@@ -12,12 +12,7 @@ import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
import { shinyTextStyles } from '@/styles';
-import {
- calculateOperationUsageMetrics,
- hasOperationUsageMetrics,
- mergeOperationUsageMetrics,
- type OperationUsageMetrics,
-} from '@/utils/operationUsageMetrics';
+import { calculateOperationUsageMetrics } from '@/utils/operationUsageMetrics';
import { contextSelectors, dataSelectors, useConversationStore } from '../store';
import { type ActivityKey, resolveOperationActivity } from '../utils/operationActivity';
@@ -238,7 +233,6 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ topAttached }) => {
let latestActivityStart = -1;
let statusSeed: string | undefined;
let stepCount = 0;
- let usageMetrics: OperationUsageMetrics | undefined;
const runtimeOperationIds: string[] = [];
for (const op of ops) {
@@ -256,9 +250,6 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ topAttached }) => {
runtimeOperationIds.push(op.id);
stepCount = Math.max(stepCount, normalizeStepCount(op.metadata.stepCount));
- if (hasOperationUsageMetrics(op.metadata.usageMetrics)) {
- usageMetrics = mergeOperationUsageMetrics(usageMetrics, op.metadata.usageMetrics);
- }
if (earliestStart === undefined || op.metadata.startTime < earliestStart) {
earliestStart = op.metadata.startTime;
@@ -271,7 +262,6 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ topAttached }) => {
startTime: earliestStart,
statusSeed,
steps: stepCount,
- usageMetrics,
};
});
const operationsByMessage = useChatStore((s) => s.operationsByMessage);
@@ -289,17 +279,16 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ topAttached }) => {
[operationState.operationIdsKey],
);
- // Fallback for older / reloaded operation state: derive usage from messages
- // produced by this operation when live operation metadata is unavailable.
- const fallbackMetrics = useMemo(() => {
+ // Single source of truth: derive the operation total from the same per-message
+ // usage shown on each bubble, so the tray always equals their sum. (Updates as
+ // messages refresh β€” no separate live accumulation that can drift.)
+ const usageMetrics = useMemo(() => {
return calculateOperationUsageMetrics(dbMessages, operationIds, operationsByMessage);
}, [dbMessages, operationIds, operationsByMessage]);
if (!operationState.startTime) return null;
- const { totalCost, totalTokens } = hasOperationUsageMetrics(operationState.usageMetrics)
- ? operationState.usageMetrics
- : fallbackMetrics;
+ const { totalCost, totalTokens } = usageMetrics;
const elapsed = now - operationState.startTime;
const costLabel = t('chat:opStatusTray.cost');
const stepLabel = t('chat:opStatusTray.steps');
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
index 63a7d111c36..57165aeca10 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
@@ -39,7 +39,7 @@ function createMockStore() {
operations: {
'op-1': {
context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },
- metadata: { startTime: 0, usageMetrics: { totalTokens: 100 } },
+ metadata: { startTime: 0 },
},
} as Record<string, any>,
replaceMessages: vi.fn(),
@@ -663,29 +663,6 @@ describe('createGatewayEventHandler', () => {
expect(store.replaceMessages).not.toHaveBeenCalled();
});
-
- it('should accumulate turn metadata usage onto the operation', async () => {
- const store = createMockStore();
- const handler = createHandler(store);
-
- handler(
- makeEvent('step_complete', {
- phase: 'turn_metadata',
- usage: { cost: 0.2, totalInputTokens: 40, totalOutputTokens: 10, totalTokens: 50 },
- }),
- );
- await flush();
-
- expect(store.updateOperationMetadata).toHaveBeenCalledWith('op-1', {
- usageMetrics: {
- totalCost: 0.2,
- totalInputTokens: 40,
- totalOutputTokens: 10,
- totalTokens: 150,
- },
- });
- expect(store.replaceMessages).not.toHaveBeenCalled();
- });
});
describe('agent_runtime_end', () => {
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 0f85138b3da..e2bd40d5c3d 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -720,7 +720,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
it('should persist per-step usage to each step assistant message, not accumulated', async () => {
// Realistic CC partial-messages flow: message_start primes the turn,
// assistant events echo a stale usage, message_delta carries the final.
- const { store } = await runWithEvents([
+ await runWithEvents([
ccInit(),
ccMessageStart('msg_01'),
ccAssistant('msg_01', [{ text: 'a', type: 'text' }]),
@@ -769,13 +769,6 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// No cache tokens for this turn β€” these fields should be absent
expect(u2.inputCachedTokens).toBeUndefined();
expect(u2.inputWriteCacheTokens).toBeUndefined();
-
- expect(store.operations['op-1'].metadata.usageMetrics).toEqual({
- totalCost: 0,
- totalInputTokens: 650,
- totalOutputTokens: 130,
- totalTokens: 780,
- });
});
it('should ignore stale usage on assistant events (from message_start echo)', async () => {
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index cdb0dc4a7be..855e095612d 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -19,7 +19,6 @@ import { messageService } from '@/services/message';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';
import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
-import { addUsageToOperationMetrics, type OperationUsageLike } from '@/utils/operationUsageMetrics';
// Lazy-loaded to break the import cycle:
// gateway.ts β†’ gatewayEventHandler.ts β†’ executors/index.ts (which pulls in
@@ -56,10 +55,6 @@ interface ToolPayloadIdentity {
toolCallId?: string;
}
-type StepCompleteDataWithUsage = StepCompleteData & {
- usage?: OperationUsageLike | null;
-};
-
/**
* Extract `{ identifier, apiName, params, toolCallId }` from a stream event's
* tool payload. Returns `undefined` when the payload is malformed so the
@@ -512,14 +507,7 @@ export const createGatewayEventHandler = (
}
case 'step_complete': {
- const data = event.data as StepCompleteDataWithUsage | undefined;
-
- if (data?.phase === 'turn_metadata' && data.usage) {
- const operation = get().operations[operationId];
- get().updateOperationMetadata(operationId, {
- usageMetrics: addUsageToOperationMetrics(operation?.metadata?.usageMetrics, data.usage),
- });
- }
+ const data = event.data as StepCompleteData | undefined;
// Refresh on execution_complete to ensure final step state is consistent
if (data?.phase === 'execution_complete') {
diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
index 6d955694b2e..0a25a793d31 100644
--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
@@ -38,7 +38,6 @@ import { threadService } from '@/services/thread';
import { type ChatStore, useChatStore } from '@/store/chat/store';
import { resolveNotificationNavigatePath } from '@/store/chat/utils/desktopNotification';
import { markdownToTxt } from '@/utils/markdownToTxt';
-import { addUsageToOperationMetrics } from '@/utils/operationUsageMetrics';
import { messageMapKey } from '../../../utils/messageMapKey';
import { mergeQueuedMessages } from '../../operation/types';
@@ -1197,19 +1196,11 @@ export const executeHeterogeneousAgent = async (
// ─── step_complete with turn_metadata: per-step usage + model/provider ───
// The reducer writes usage/model/provider onto the current step's
// assistant (main) or the subagent's in-thread assistant (delegated).
- // `result_usage` (grand total) is ignored by the reducer. Main usage also
- // feeds the operation's usage-metrics tray β€” a renderer-only side effect
- // the reducer doesn't model, so it stays here. Not forwarded (bookkeeping).
+ // `result_usage` (grand total) is ignored by the reducer. The operation
+ // usage tray derives its total from these per-message usages directly
+ // (OpStatusTray β†’ calculateOperationUsageMetrics), so there is no separate
+ // accumulation here. Not forwarded (bookkeeping).
if (event.type === 'step_complete' && event.data?.phase === 'turn_metadata') {
- if (!event.data.subagent && event.data.usage) {
- const operation = get().operations[operationId];
- get().updateOperationMetadata(operationId, {
- usageMetrics: addUsageToOperationMetrics(
- operation?.metadata?.usageMetrics,
- event.data.usage,
- ),
- });
- }
persistQueue = persistQueue.then(() => reduceAndApplyMain(event));
return;
}