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): count LLM calls instead of execution steps in step metric (#21057)

Arvin Xuc52ddde4082a
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index 27d06783aed..e8599508a29 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -2,6 +2,7 @@ import {
type AgentEvent,
type AgentRuntimeContext,
type AgentState,
+ getLlmCallCount,
normalizeAgentState,
} from '@lobechat/agent-runtime';
import debug from 'debug';
@@ -165,7 +166,7 @@ export class AgentStateManager {
lastActiveAt: new Date().toISOString(),
status: state.status,
totalCost: state.cost?.total || 0,
- totalSteps: state.stepCount,
+ totalSteps: getLlmCallCount(state),
});
// State change events are recorded through the events array in saveStepResult
@@ -277,7 +278,7 @@ export class AgentStateManager {
lastActiveAt: new Date().toISOString(),
status: stepResult.newState.status,
totalCost: stepResult.newState.cost?.total || 0,
- totalSteps: stepResult.newState.stepCount,
+ totalSteps: getLlmCallCount(stepResult.newState),
};
pipeline.hmset(metaKey, metadata as any);
pipeline.expire(metaKey, this.DEFAULT_TTL);
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
index d72f70e6990..8468743a28a 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
@@ -1,4 +1,4 @@
-import { type AgentState, normalizeAgentState } from '@lobechat/agent-runtime';
+import { type AgentState, getLlmCallCount, normalizeAgentState } from '@lobechat/agent-runtime';
import debug from 'debug';
import { type AgentOperationMetadata, type StepResult } from './AgentStateManager';
@@ -33,7 +33,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
existingMeta.lastActiveAt = new Date().toISOString();
existingMeta.status = state.status;
existingMeta.totalCost = state.cost?.total || 0;
- existingMeta.totalSteps = state.stepCount;
+ existingMeta.totalSteps = getLlmCallCount(state);
}
log('[%s] Saved state for step %d', operationId, state.stepCount);
@@ -85,7 +85,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
existingMeta.lastActiveAt = new Date().toISOString();
existingMeta.status = stepResult.newState.status;
existingMeta.totalCost = stepResult.newState.cost?.total || 0;
- existingMeta.totalSteps = stepResult.newState.stepCount;
+ existingMeta.totalSteps = getLlmCallCount(stepResult.newState);
}
log('[%s:%d] Saved step result', operationId, stepResult.stepIndex);
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
index b52b5950b9e..976c175fefd 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
@@ -125,7 +125,7 @@ describe('InMemoryAgentStateManager', () => {
it('should update metadata.status and totalCost when state is saved (with existing metadata)', async () => {
await manager.createOperationMetadata('op-c', {});
- const state = makeState({ status: 'done', stepCount: 5, cost: { total: 200 } });
+ const state = makeState({ status: 'done', stepCount: 5, llmCalls: 5, cost: { total: 200 } });
await manager.saveAgentState('op-c', state);
const meta = await manager.getOperationMetadata('op-c');
@@ -202,7 +202,7 @@ describe('InMemoryAgentStateManager', () => {
it('should update metadata after saving step result', async () => {
await manager.createOperationMetadata('op-meta-update', {});
const stepResult = makeStepResult({
- newState: makeState({ status: 'done', stepCount: 7, cost: { total: 300 } }),
+ newState: makeState({ status: 'done', stepCount: 7, llmCalls: 7, cost: { total: 300 } }),
stepIndex: 7,
});
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
index 4c3f7e4dcc2..ca7be477bdf 100644
--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
@@ -505,6 +505,7 @@ describe('runStep handler', () => {
pendingHumanSelect: undefined,
pendingToolsCalling: ['t1'],
status: 'waiting_for_human',
+ llmCalls: 5,
stepCount: 5,
},
success: true,
diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.ts
index cbd2a50ef9f..191a2a25a65 100644
--- a/apps/server/src/router-hono/agent/handlers/runStep.ts
+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts
@@ -1,3 +1,4 @@
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import debug from 'debug';
import { eq } from 'drizzle-orm';
import type { Context } from 'hono';
@@ -508,7 +509,7 @@ export async function runStep(c: Context): Promise<Response> {
stepIndex: currentStepIndex,
success: result.success,
totalCost: result.state.cost?.total || 0,
- totalSteps: result.state.stepCount,
+ totalSteps: getLlmCallCount(result.state),
waitingForHuman: result.state.status === 'waiting_for_human',
};
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts
index 728f01f0dcb..79058244962 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts
@@ -242,6 +242,73 @@ describe('aiAgentRouter.getSubAgentTaskStatus', () => {
});
});
+ it('accumulates LLM calls against the persisted versioned baseline', async () => {
+ await serverDB
+ .update(threads)
+ .set({
+ metadata: { operationId: 'op-test-123', totalLlmCalls: 4, totalSteps: 4 },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ llmCalls: 3,
+ status: 'done',
+ stepCount: 9,
+ usage: { llm: { apiCalls: 3, tokens: { total: 100 } } },
+ },
+ isCompleted: true,
+ hasError: false,
+ metadata: {},
+ stats: { totalMessages: 2 },
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+ const result = await caller.getSubAgentTaskStatus({ threadId: testThreadId });
+
+ expect(result.status).toBe('completed');
+ // 4 previous + 3 in this operation β€” not the operation's own 3.
+ expect(result.taskDetail?.totalSteps).toBe(7);
+
+ const [row] = await serverDB.select().from(threads).where(eq(threads.id, testThreadId));
+ expect((row.metadata as any)?.totalLlmCalls).toBe(7);
+ expect((row.metadata as any)?.totalSteps).toBe(7);
+ });
+
+ it('keeps the LLM-call total stable when the same operation is polled again', async () => {
+ await serverDB
+ .update(threads)
+ .set({ metadata: { operationId: 'op-test-123', totalLlmCalls: 4, totalSteps: 4 } })
+ .where(eq(threads.id, testThreadId));
+
+ // The operation keeps reporting the same cumulative count on every poll.
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ llmCalls: 3,
+ status: 'running',
+ stepCount: 6,
+ usage: { llm: { apiCalls: 3, tokens: { total: 100 } } },
+ },
+ isCompleted: false,
+ hasError: false,
+ metadata: {},
+ stats: { totalMessages: 2 },
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+ const first = await caller.getSubAgentTaskStatus({ threadId: testThreadId });
+ expect(first.taskDetail?.totalSteps).toBe(7);
+
+ // A second poll must not add the operation's cumulative count again.
+ const second = await caller.getSubAgentTaskStatus({ threadId: testThreadId });
+ expect(second.taskDetail?.totalSteps).toBe(7);
+
+ const [row] = await serverDB.select().from(threads).where(eq(threads.id, testThreadId));
+ expect((row.metadata as any)?.totalLlmCalls).toBe(7);
+ expect((row.metadata as any)?.totalSteps).toBe(7);
+ expect((row.metadata as any)?.llmCallsBaseline).toBe(4);
+ });
+
it('should extract totalToolCalls from usage.tools.totalCalls', async () => {
mockGetOperationStatus.mockResolvedValue({
currentState: {
diff --git a/apps/server/src/routers/lambda/aiAgent/operationStatus.ts b/apps/server/src/routers/lambda/aiAgent/operationStatus.ts
index 44fd3770974..04a9c59cbe2 100644
--- a/apps/server/src/routers/lambda/aiAgent/operationStatus.ts
+++ b/apps/server/src/routers/lambda/aiAgent/operationStatus.ts
@@ -1,3 +1,4 @@
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import { parse } from '@lobechat/conversation-flow';
import type { TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';
import { ThreadStatus } from '@lobechat/types';
@@ -261,9 +262,28 @@ export const operationStatusRouter = router({
updatedMetadata.totalMessages = stats.totalMessages;
}
- // Store totalSteps from stepCount
- if (redisState.stepCount) {
- updatedMetadata.totalSteps = redisState.stepCount;
+ // User-facing step metric: completed LLM calls. In QStash mode this
+ // poller is the only writer of thread metadata, so keep both fields in
+ // LLM-call units (`totalSteps` is what the UI reads).
+ //
+ // `operationLlmCalls` is cumulative for the operation, so it must be
+ // added to an immutable pre-operation baseline instead of the value a
+ // previous poll wrote: polls are frequent and each one used to add the
+ // operation's running total again.
+ const operationLlmCalls = getLlmCallCount(redisState);
+ if (operationLlmCalls) {
+ const baselineIsCurrent =
+ metadata?.llmCallsBaselineOperationId === resolvedOperationId &&
+ typeof metadata?.llmCallsBaseline === 'number';
+ const baselineLlmCalls = baselineIsCurrent
+ ? (metadata.llmCallsBaseline as number)
+ : (metadata?.totalLlmCalls ?? 0);
+
+ const totalLlmCalls = baselineLlmCalls + operationLlmCalls;
+ updatedMetadata.llmCallsBaseline = baselineLlmCalls;
+ updatedMetadata.llmCallsBaselineOperationId = resolvedOperationId;
+ updatedMetadata.totalLlmCalls = totalLlmCalls;
+ updatedMetadata.totalSteps = totalLlmCalls;
}
// Check if operation is completed
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts
index 2e77c2744bd..0b5bef621c5 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts
@@ -536,6 +536,53 @@ describe('AgentEvalRunService', () => {
});
});
+ it('does not double-count LLM calls when the completion hook runs locally', async () => {
+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+
+ await new AgentEvalRunModel(serverDB, userId).update(run.id, { status: 'failed' });
+ await runTopicModel.updateByRunAndTopic(run.id, topic.id, {
+ evalResult: {
+ completionReason: 'timeout',
+ duration: 1000,
+ llmCalls: 3,
+ rubricScores: [],
+ },
+ passed: false,
+ score: 0,
+ status: 'timeout',
+ });
+
+ let capturedHooks: any[] = [];
+ mockExecAgent.mockImplementation(async (params: any) => {
+ capturedHooks = params.hooks ?? [];
+ return { operationId: 'op-resume-2' };
+ });
+
+ await new AgentEvalRunService(serverDB, userId).executeResumedTrajectory({
+ appContext: { topicId: topic.id },
+ parentMessageId: 'parent-message-id',
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ userId,
+ });
+
+ // The operation is seeded with the previous total, so the completion
+ // event is already cumulative and must not have `prevLlmCalls` added again.
+ expect(mockExecAgent).toHaveBeenCalledWith(expect.objectContaining({ initialLlmCalls: 3 }));
+
+ await capturedHooks[0].handler({
+ llmCalls: 7,
+ reason: 'done',
+ status: 'done',
+ steps: 9,
+ });
+
+ const refreshed = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);
+ expect((refreshed?.evalResult as any)?.llmCalls).toBe(7);
+ });
+
it('should cancel when the trajectory is not resumable', async () => {
const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
@@ -630,6 +677,7 @@ describe('AgentEvalRunService', () => {
expect(mockExecAgent).toHaveBeenCalledWith(
expect.objectContaining({
appContext: { threadId: thread!.id, topicId: topic.id },
+ initialLlmCalls: 3,
initialStepCount: 7,
parentMessageId: 'parent-message-id',
prompt: '',
diff --git a/apps/server/src/services/agentEvalRun/resumeExecution.ts b/apps/server/src/services/agentEvalRun/resumeExecution.ts
index 53e7d897ec4..89243bb625e 100644
--- a/apps/server/src/services/agentEvalRun/resumeExecution.ts
+++ b/apps/server/src/services/agentEvalRun/resumeExecution.ts
@@ -104,7 +104,9 @@ export async function executeResumedTrajectory(
duration: event.duration,
errorDetail: event.errorDetail,
errorMessage: event.errorMessage,
- llmCalls: (event.llmCalls ?? 0) + prevLlmCalls,
+ // `event.llmCalls` is already cumulative: the operation is seeded with
+ // `initialLlmCalls: prevLlmCalls`.
+ llmCalls: event.llmCalls ?? 0,
steps: (event.steps ?? 0) + prevSteps,
toolCalls: (event.toolCalls ?? 0) + prevToolCalls,
totalTokens: (event.totalTokens ?? 0) + prevTokens,
@@ -122,6 +124,7 @@ export async function executeResumedTrajectory(
},
],
...getEvalContextParams(envPrompt, environment, params.caseId),
+ initialLlmCalls: prevLlmCalls,
initialStepCount: prevSteps,
maxSteps,
parentMessageId,
@@ -250,7 +253,9 @@ export async function executeResumedThreadTrajectory(
cost: (event.cost ?? 0) + prevCost,
duration: event.duration,
errorMessage: event.errorMessage,
- llmCalls: (event.llmCalls ?? 0) + prevLlmCalls,
+ // `event.llmCalls` is already cumulative: the operation is seeded with
+ // `initialLlmCalls: prevLlmCalls`.
+ llmCalls: event.llmCalls ?? 0,
steps: (event.steps ?? 0) + prevSteps,
toolCalls: (event.toolCalls ?? 0) + prevToolCalls,
totalTokens: (event.totalTokens ?? 0) + prevTokens,
@@ -270,6 +275,7 @@ export async function executeResumedThreadTrajectory(
},
],
...getEvalContextParams(envPrompt, environment, caseId),
+ initialLlmCalls: prevLlmCalls,
initialStepCount: prevSteps,
maxSteps,
parentMessageId,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
index aa2444c12fd..26d719df657 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
@@ -175,6 +175,23 @@ describe('AgentRuntimeService', () => {
},
);
+ it('mirrors a resumed LLM-call baseline into the usage counter old workers report', async () => {
+ await service.createOperation({ ...mockParams, autoStart: false, initialLlmCalls: 7 });
+
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.llmCalls).toBe(7);
+ // A pre-`llmCalls` worker finalizes the operation from this field alone.
+ expect(savedState.usage.llm.apiCalls).toBe(7);
+ });
+
+ it('leaves usage absent when the run carries no baseline', async () => {
+ await service.createOperation({ ...mockParams, autoStart: false });
+
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.llmCalls).toBe(0);
+ expect(savedState).not.toHaveProperty('usage');
+ });
+
describe('file Works declaration (host.acceptsFileWorks)', () => {
it('stores the declaration the client made', async () => {
await service.createOperation({ ...mockParams, acceptsFileWorks: true, autoStart: false });
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts
index 029d3621fdb..a72c940862e 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts
@@ -478,7 +478,7 @@ describe('AgentRuntimeService', () => {
expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {
type: 'step_start',
stepIndex: 1,
- data: {},
+ data: { llmCalls: 0 },
});
expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {
@@ -486,6 +486,7 @@ describe('AgentRuntimeService', () => {
stepIndex: 1,
data: {
stepIndex: 1,
+ llmCalls: 0,
nextStepScheduled: false, // Published before nextStepScheduled is updated
},
});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/operationQueries.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/operationQueries.test.ts
index 9f389306adf..83a6704f37b 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/operationQueries.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/operationQueries.test.ts
@@ -127,6 +127,7 @@ describe('AgentRuntimeService', () => {
operationId: 'test-operation-1',
status: 'running',
stepCount: 5,
+ llmCalls: 5,
messages: [{ content: 'msg1' }, { content: 'msg2' }],
cost: { total: 0.1 },
usage: { tokens: 100 },
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
index 7c4f05a1420..1a32420202e 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
@@ -1,5 +1,5 @@
import type { AgentState } from '@lobechat/agent-runtime';
-import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';
+import { extractActivatedToolIdsFromMessages, UsageCounter } from '@lobechat/agent-runtime';
import debug from 'debug';
import {
@@ -85,6 +85,7 @@ export async function createOperation(
parentOperationId,
signal,
userTimezone,
+ initialLlmCalls = 0,
initialStepCount = 0,
workspaceId,
} = params;
@@ -293,6 +294,15 @@ export async function createOperation(
operationToolSet,
status: 'idle',
stepCount: initialStepCount,
+ llmCalls: initialLlmCalls,
+ // Compat mirror for a rolling deploy: a worker still running the
+ // pre-`llmCalls` build reports only `usage.llm.apiCalls`, so a resumed
+ // run that seeds its prior total here alone would lose every call made
+ // before the resume the moment one of those workers finalizes it. Seeding
+ // both keeps `getLlmCallCount`'s max() additive on either build.
+ ...(initialLlmCalls > 0 && {
+ usage: UsageCounter.accumulateAttempts(undefined, initialLlmCalls),
+ }),
// How the run executes β€” frozen from here on.
plan: {
eval: evalRuntime,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts
index 07645c1be11..6556e725897 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts
@@ -1,3 +1,4 @@
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import type { Span } from '@lobechat/observability-otel/api';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { buildInvokeAgentResultAttributes } from '@lobechat/observability-otel/modules/agent-runtime';
@@ -96,6 +97,7 @@ export async function failStep(
finalStateWithError = {
...errorState!,
error: formattedError,
+ llmCalls: getLlmCallCount(errorState),
metadata: {
...errorState?.metadata,
externalRetryCount,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts
index 7b2d383f407..914ef15e404 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts
@@ -1,4 +1,5 @@
import type { AgentState } from '@lobechat/agent-runtime';
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import debug from 'debug';
import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
@@ -48,7 +49,7 @@ export async function dispatchBeforeStepHooks(
serializedContext: undefined,
stepIndex,
topicId: beforeStepOrigin.topicId,
- turnCount: agentState?.stepCount || 0,
+ turnCount: getLlmCallCount(agentState),
},
sourceId: `${operationId}:before:${stepIndex}`,
sourceType: 'runtime.before_step',
@@ -70,7 +71,7 @@ export async function dispatchBeforeStepHooks(
finalState: agentState,
operationId,
stepIndex,
- steps: agentState?.stepCount || 0,
+ steps: getLlmCallCount(agentState),
userId: beforeStepOrigin.userId || deps.userId,
},
agentState?.host?.hooks,
@@ -131,7 +132,7 @@ export async function dispatchAfterStepHooks(
serializedContext: undefined,
stepIndex,
topicId: origin.topicId,
- turnCount: stepResult.newState?.stepCount || 0,
+ turnCount: getLlmCallCount(stepResult.newState),
},
sourceId: `${operationId}:after:${stepIndex}`,
sourceType: 'runtime.after_step',
@@ -164,7 +165,7 @@ export async function dispatchAfterStepHooks(
stepCost: stepPresentationData.stepCost,
stepIndex,
stepType: stepPresentationData.stepType,
- steps: stepResult.newState?.stepCount || 0,
+ steps: getLlmCallCount(stepResult.newState),
thinking: stepPresentationData.thinking,
toolCalls: stepResult.newState?.usage?.tools?.totalCalls,
toolsCalling: stepPresentationData.toolsCalling,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
index 4dcf1ae8f43..0138c3885a3 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
@@ -1,3 +1,4 @@
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import { context as otelContext, trace as otelTrace } from '@lobechat/observability-otel/api';
import {
buildInvokeAgentAttributes,
@@ -157,9 +158,14 @@ export async function executeStep(
const { uiMessages: stepStartUiMessages, messages: stepEntryMessages } =
await deps.queryStepEntryMessages(agentState);
await deps.streamManager.publishStreamEvent(operationId, {
- data: gatewayMessagePatchEnabled
- ? { messageRevision: stepIndex }
- : { ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }) },
+ data: {
+ ...(gatewayMessagePatchEnabled
+ ? { messageRevision: stepIndex }
+ : { ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }) }),
+ // User-facing metric: completed LLM calls, independent of the
+ // execution `stepIndex` used for scheduling/idempotency.
+ llmCalls: getLlmCallCount(agentState),
+ },
stepIndex,
type: 'step_start',
});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
index c56957b17b6..4d3469345cd 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
@@ -1,4 +1,5 @@
import type { AgentRuntime, AgentRuntimeContext } from '@lobechat/agent-runtime';
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import debug from 'debug';
import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';
@@ -252,6 +253,7 @@ export async function saveAndPublishStep(
...(stepResult.newState.host?.includeFinalState === true && {
finalState: stepResult.newState,
}),
+ llmCalls: getLlmCallCount(stepResult.newState),
nextStepScheduled,
stepIndex,
},
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts
index 1a3bf6ce503..50b35fd9491 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts
@@ -1,5 +1,5 @@
import type { AgentState } from '@lobechat/agent-runtime';
-import { isParkedStatus } from '@lobechat/agent-runtime';
+import { getLlmCallCount, isParkedStatus } from '@lobechat/agent-runtime';
import debug from 'debug';
import { redisService } from '@/server/services/redis';
@@ -448,7 +448,7 @@ export async function getOperationStatus(
: 0,
totalCost: currentState.cost?.total || 0,
totalMessages: currentState.messages?.length || 0,
- totalSteps: currentState.stepCount || 0,
+ totalSteps: getLlmCallCount(currentState),
uptime: operationMetadata.createdAt
? Date.now() - new Date(operationMetadata.createdAt).getTime()
: 0,
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
index b197cfa06a2..4696e92f7ce 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
@@ -260,6 +260,7 @@ export class CompletionLifecycle {
model: input.model ?? undefined,
provider: input.provider ?? undefined,
stepCount: input.stepCount ?? null,
+ llmCalls: input.llmCalls ?? undefined,
usage: input.usage ?? undefined,
};
}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts
index 94ea6d83796..ae45bbb868a 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/lifecycleEvent.ts
@@ -1,6 +1,7 @@
/**
* The lifecycle event payload every completion consumer receives.
*/
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';
import {
@@ -110,7 +111,7 @@ export function buildLifecycleEvent(
errorType: formattedError?.type === undefined ? undefined : String(formattedError.type),
finalState: state,
lastAssistantContent,
- llmCalls: state?.usage?.llm?.apiCalls,
+ llmCalls: getLlmCallCount(state),
operationId,
reason,
status: state?.status || reason,
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts
index 14ac1266157..9a63761e784 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts
@@ -2,7 +2,7 @@
* Terminal persistence: the `agent_operations` completion row, the topic
* running mark, and the topic usage rollup.
*/
-import { isParkedStatus } from '@lobechat/agent-runtime';
+import { getLlmCallCount, isParkedStatus } from '@lobechat/agent-runtime';
import { type AgentOperationStatus, isAgentOperationInFlight } from '@lobechat/types';
import debug from 'debug';
@@ -139,7 +139,7 @@ export async function persistCompletion(
cost: state?.cost ?? null,
error: state?.error ?? null,
interruption: state?.interruption ?? null,
- llmCalls: add(state?.usage?.llm?.apiCalls, rollup?.llmCalls ?? 0),
+ llmCalls: add(getLlmCallCount(state), 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
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/signals.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/signals.ts
index 6ceccc74d60..2d1b0e2e821 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/signals.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/signals.ts
@@ -1,6 +1,7 @@
/**
* Completion Agent Signal source events.
*/
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import { isRecord } from '@lobechat/utils/object';
import debug from 'debug';
@@ -157,7 +158,7 @@ export async function emitSignalEvents(
reason,
serializedContext: undefined,
topicId: runOrigin.topicId,
- turnCount: state?.stepCount || 0,
+ turnCount: getLlmCallCount(state),
},
sourceId: `${operationId}:complete:${reason}`,
sourceType: 'agent.execution.failed',
@@ -194,9 +195,9 @@ export async function emitSignalEvents(
// can project receipts. Undefined for every other agent.
selfIteration,
serializedContext: undefined,
- steps: state?.stepCount || 0,
+ steps: getLlmCallCount(state),
topicId: runOrigin.topicId,
- turnCount: state?.stepCount || 0,
+ turnCount: getLlmCallCount(state),
},
sourceId: `${operationId}:complete:${reason}`,
sourceType: 'agent.execution.completed',
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
index 91e1d6ed347..ef384c9572a 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
@@ -37,6 +37,8 @@ export interface OperationCompletionInput {
* in-process path's user turn.
*/
goal?: unknown;
+ /** User-facing LLM-call count for the run (derived from `usage` when omitted). */
+ llmCalls?: number | null;
/** Executed model β€” the verify gate keys off `op.model`, so hetero backfills it. */
model?: string | null;
operationId: string;
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 1062aeb32d5..8a5c27605ff 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -1786,7 +1786,7 @@ describe('AgentRuntimeService.executeStep - step_start uiMessages payload', () =
const stepStartCall = streamManager.publishStreamEvent.mock.calls.find(
([, evt]: any) => evt?.type === 'step_start',
);
- expect(stepStartCall[1].data).toEqual({ messageRevision: 5 });
+ expect(stepStartCall[1].data).toEqual({ llmCalls: 0, messageRevision: 5 });
});
it('still pushes the whole snapshot to a client that declared nothing', async () => {
@@ -1818,7 +1818,7 @@ describe('AgentRuntimeService.executeStep - step_start uiMessages payload', () =
const stepStartCall = streamManager.publishStreamEvent.mock.calls.find(
([, evt]: any) => evt?.type === 'step_start',
);
- expect(stepStartCall[1].data).toEqual({
+ expect(stepStartCall[1].data).toMatchObject({
uiMessages: [{ id: 'large-history', role: 'user' }],
});
});
diff --git a/apps/server/src/services/agentRuntime/stepPresentation.ts b/apps/server/src/services/agentRuntime/stepPresentation.ts
index 76fcbcdcb35..9033267b44c 100644
--- a/apps/server/src/services/agentRuntime/stepPresentation.ts
+++ b/apps/server/src/services/agentRuntime/stepPresentation.ts
@@ -1,3 +1,5 @@
+import { getLlmCallCount } from '@lobechat/agent-runtime';
+
import type { StepPresentationData } from './types';
interface StepResultLike {
@@ -136,7 +138,7 @@ export function buildStepPresentation(
totalCost: cost?.total ?? 0,
totalInputTokens: tokens?.input ?? 0,
totalOutputTokens: tokens?.output ?? 0,
- totalSteps: stepResult.newState.stepCount ?? 0,
+ totalSteps: getLlmCallCount(stepResult.newState),
totalTokens: tokens?.total ?? 0,
};
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 80acfe91cfc..af882ad998a 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -570,6 +570,8 @@ export interface OperationCreationParams {
/** Opt into runtime state snapshots on step_complete events. Defaults to false. */
includeFinalState?: boolean;
initialContext: AgentRuntimeContext;
+ /** Initial LLM-call count offset for resumed operations (accumulated from previous runs) */
+ initialLlmCalls?: number;
initialMessages?: any[];
/** Initial step count offset for resumed operations (accumulated from previous runs) */
initialStepCount?: number;
diff --git a/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts b/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts
new file mode 100644
index 00000000000..618e50cc941
--- /dev/null
+++ b/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { pickThreadUsageBaseline } from '../threadRunHooks';
+
+describe('pickThreadUsageBaseline', () => {
+ it('ignores legacy totalSteps when no versioned LLM baseline exists', () => {
+ const baseline = pickThreadUsageBaseline({ totalSteps: 9 } as any);
+
+ // Legacy `totalSteps` is in execution-step units; reusing it would mix units.
+ expect(baseline.totalLlmCalls).toBeUndefined();
+ });
+
+ it('uses the versioned totalLlmCalls baseline', () => {
+ const baseline = pickThreadUsageBaseline({ totalLlmCalls: 3, totalSteps: 9 } as any);
+
+ expect(baseline.totalLlmCalls).toBe(3);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
index 8219cd48dc8..5dcade0b4ea 100644
--- a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
+++ b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
@@ -1,4 +1,5 @@
import type { AgentHookEvent, AgentState } from '@lobechat/agent-runtime';
+import { getLlmCallCount } from '@lobechat/agent-runtime';
import type { ThreadMetadata } from '@lobechat/types';
import { ThreadStatus } from '@lobechat/types';
import debug from 'debug';
@@ -30,12 +31,13 @@ export function calculateTotalTokens(usage?: AgentState['usage']): number | unde
*/
export type ThreadUsageBaseline = Pick<
ThreadMetadata,
- 'totalCost' | 'totalMessages' | 'totalTokens' | 'totalToolCalls'
+ 'totalCost' | 'totalLlmCalls' | 'totalMessages' | 'totalTokens' | 'totalToolCalls'
>;
export const pickThreadUsageBaseline = (metadata?: ThreadMetadata | null): ThreadUsageBaseline => ({
totalCost: metadata?.totalCost,
totalMessages: metadata?.totalMessages,
+ totalLlmCalls: metadata?.totalLlmCalls,
totalTokens: metadata?.totalTokens,
totalToolCalls: metadata?.totalToolCalls,
});
@@ -79,6 +81,8 @@ export function createThreadMetadataCallbacks(
operationId: state.operationId,
startedAt,
totalMessages: state.messages?.length ?? 0,
+ totalSteps: getLlmCallCount(state),
+ totalLlmCalls: getLlmCallCount(state),
totalTokens: calculateTotalTokens(state.usage),
totalToolCalls: accumulatedToolCalls,
},
@@ -155,6 +159,8 @@ export function createThreadMetadataCallbacks(
startedAt,
totalCost: finalState.cost?.total,
totalMessages: finalState.messages?.length ?? 0,
+ totalSteps: getLlmCallCount(finalState),
+ totalLlmCalls: getLlmCallCount(finalState),
totalTokens: calculateTotalTokens(finalState.usage),
totalToolCalls: accumulatedToolCalls,
},
@@ -199,6 +205,8 @@ export function createThreadHooks(
startedAt,
totalCost: usageBaseline.totalCost,
totalMessages: state.messages?.length ?? 0,
+ totalSteps: addUsage(usageBaseline.totalLlmCalls, getLlmCallCount(state)),
+ totalLlmCalls: addUsage(usageBaseline.totalLlmCalls, getLlmCallCount(state)),
totalTokens: addUsage(usageBaseline.totalTokens, calculateTotalTokens(state.usage)),
totalToolCalls: addUsage(
usageBaseline.totalToolCalls,
@@ -279,6 +287,8 @@ export function createThreadHooks(
startedAt,
totalCost: addUsage(usageBaseline.totalCost, finalState.cost?.total),
totalMessages: finalState.messages?.length ?? 0,
+ totalSteps: addUsage(usageBaseline.totalLlmCalls, getLlmCallCount(finalState)),
+ totalLlmCalls: addUsage(usageBaseline.totalLlmCalls, getLlmCallCount(finalState)),
totalTokens: addUsage(
usageBaseline.totalTokens,
calculateTotalTokens(finalState.usage),
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
index 850811b0d67..fedad37fc49 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
@@ -74,6 +74,16 @@ describe('startOperation β€Ί member_runtime_end declaration', () => {
expect(agentRuntimeService.acceptsMemberRuntimeEnd).not.toHaveBeenCalled();
});
+ it('forwards the resumed LLM baseline to the new operation', async () => {
+ const { agentRuntimeService, ctx, deps, input } = setup(false);
+
+ await startOperation(deps, ctx, input({ initialLlmCalls: 3, initialStepCount: 7 }));
+
+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ initialLlmCalls: 3, initialStepCount: 7 }),
+ );
+ });
+
// The v2 approval endpoint starts the continuation server-side, without the
// client's `streamFeatures`: it is the same client, so the parked op's
// declaration carries over (read before that op is retired).
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 3dc0800bf09..0bd244164ce 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -123,6 +123,7 @@ export const execAgentTurn = async (
evalRuntime,
maxSteps,
disableLocalSystem,
+ initialLlmCalls,
initialStepCount,
signal,
userInterventionConfig: requestedUserInterventionConfig = { approvalMode: 'headless' },
@@ -712,6 +713,7 @@ export const execAgentTurn = async (
evalRuntime,
hooks,
initialContext,
+ initialLlmCalls,
initialStepCount,
maxSteps,
operationId,
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 8ad5129bfb9..a0007924cf3 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -50,6 +50,7 @@ export interface StartOperationInput {
includeFinalState?: boolean;
/** Final runtime context β€” base prep context with 16b/16c overrides applied. */
initialContext: OperationPrepResult['initialContext'];
+ initialLlmCalls?: number;
initialStepCount?: number;
/** Relay executor the calling client declared; lands on `state.host.llmExecutor`. */
llmExecutor?: InternalExecAgentParams['llmExecutor'];
@@ -119,6 +120,7 @@ export const startOperation = async (
evalRuntime,
hooks,
initialContext,
+ initialLlmCalls,
initialStepCount,
maxSteps,
operationId,
@@ -318,6 +320,7 @@ export const startOperation = async (
projectInstructions: prep.projectInstructions,
initialContext,
initialMessages: prep.allMessages,
+ initialLlmCalls,
initialStepCount,
...(providedApprovalResolutionRequestId && approvalSourceOperationId
? {
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 9788fe06120..7b068102360 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -184,6 +184,8 @@ export interface InternalExecAgentParams extends ExecAgentParams {
functionTools?: Array<{ description?: string; name: string; parameters?: Record<string, any> }>;
/** External lifecycle hooks (auto-adapt to local/production mode) */
hooks?: AgentHook[];
+ /** Initial LLM-call count offset for resumed operations (accumulated from previous runs) */
+ initialLlmCalls?: number;
/** Initial step count offset for resumed operations (accumulated from previous runs) */
initialStepCount?: number;
/**
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 5606e4fc47c..58f13a74432 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1830,6 +1830,7 @@
"noMembersYet": "This group doesn't have any members yet. Click the + button to invite agents.",
"noSelectedAgents": "No members selected yet",
"opStatusTray.cost": "cost",
+ "opStatusTray.llmCalls": "LLM calls",
"opStatusTray.status.compressing": "Compressing context",
"opStatusTray.status.generating": "Generating",
"opStatusTray.status.reasoning": "Thinking",
@@ -2270,6 +2271,7 @@
"task.instruction": "Task Instruction",
"task.intermediateSteps": "{{count}} intermediate steps",
"task.metrics.duration": "(took {{duration}})",
+ "task.metrics.llmCallsShort": "LLM calls",
"task.metrics.stepsShort": "steps",
"task.metrics.toolCallsShort": "skill uses",
"task.status.cancelled": "Task Cancelled",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 7b41d610b0d..f91699b4f4a 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1830,6 +1830,7 @@
"noMembersYet": "θΏ™δΈͺηΎ€η»„θΏ˜ζ²‘ζœ‰ζˆε‘˜γ€‚η‚Ήε‡»γ€Œ+γ€ι‚€θ―·εŠ©η†εŠ ε…₯",
"noSelectedAgents": "还ζœͺι€‰ζ‹©ζˆε‘˜",
"opStatusTray.cost": "花费",
+ "opStatusTray.llmCalls": "ζ¬‘ζ¨‘εž‹θ°ƒη”¨",
"opStatusTray.status.compressing": "εŽ‹ηΌ©δΈŠδΈ‹ζ–‡δΈ­",
"opStatusTray.status.generating": "η”ŸζˆδΈ­",
"opStatusTray.status.reasoning": "思考中",
@@ -2270,6 +2271,7 @@
"task.instruction": "任劑说明",
"task.intermediateSteps": "{{count}} δΈͺδΈ­ι—΄ζ­₯ιͺ€",
"task.metrics.duration": "οΌˆη”¨ζ—Ά {{duration}}οΌ‰",
+ "task.metrics.llmCallsShort": "ζ¬‘ζ¨‘εž‹θ°ƒη”¨",
"task.metrics.stepsShort": "ζ­₯",
"task.metrics.toolCallsShort": "ζ¬‘ζŠ€θƒ½θ°ƒη”¨",
"task.status.cancelled": "δ»»εŠ‘ε·²ε–ζΆˆ",
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 4c108267545..638228f4c44 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -211,6 +211,11 @@ export interface ToolEndData {
export interface StepCompleteData {
/** Present only when the run opts into includeFinalState. */
finalState?: unknown;
+ /**
+ * User-facing LLM-call total after this step. Independent of `event.stepIndex`
+ * (the internal execution index used for scheduling and idempotency).
+ */
+ llmCalls?: number;
phase: string;
reason?: string;
reasonDetail?: string;
diff --git a/packages/agent-runtime/src/core/UsageCounter.ts b/packages/agent-runtime/src/core/UsageCounter.ts
index 0c5d5ede5d2..4d9025cd858 100644
--- a/packages/agent-runtime/src/core/UsageCounter.ts
+++ b/packages/agent-runtime/src/core/UsageCounter.ts
@@ -121,13 +121,15 @@ export class UsageCounter {
* @returns Updated usage and cost
*/
static accumulateLLM(params: {
+ /** Number of provider attempts this accumulation represents (defaults to 1). */
+ apiCallsDelta?: number;
cost?: Cost;
model: string;
modelUsage: ModelUsage;
provider: string;
usage?: Usage;
}): { cost?: Cost; usage: Usage } {
- const { usage, cost, provider, model, modelUsage } = params;
+ const { usage, cost, provider, model, modelUsage, apiCallsDelta = 1 } = params;
// Ensure usage exists
const newUsage = usage ? structuredClone(usage) : this.createDefaultUsage();
@@ -136,7 +138,7 @@ export class UsageCounter {
newUsage.llm.tokens.input += modelUsage.totalInputTokens ?? 0;
newUsage.llm.tokens.output += modelUsage.totalOutputTokens ?? 0;
newUsage.llm.tokens.total += modelUsage.totalTokens ?? 0;
- newUsage.llm.apiCalls += 1;
+ newUsage.llm.apiCalls += apiCallsDelta;
// Ensure cost exists if modelUsage has cost
const newCost = cost
@@ -175,6 +177,19 @@ export class UsageCounter {
return { cost: newCost, usage: newUsage };
}
+ /**
+ * Count provider attempts that produced no finalized output.
+ *
+ * Retries and terminal failures still reached the provider, so the
+ * user-facing LLM-call metric counts them even though there are no tokens or
+ * cost to accumulate.
+ */
+ static accumulateAttempts(usage: Usage | undefined, attempts: number): Usage {
+ const newUsage = usage ? structuredClone(usage) : this.createDefaultUsage();
+ newUsage.llm.apiCalls += Math.max(0, attempts);
+ return newUsage;
+ }
+
/**
* Accumulate tool usage and cost
* @param params - Accumulation parameters
diff --git a/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts b/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
index 1da3b5a70aa..7ca863e18c9 100644
--- a/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/UsageCounter.test.ts
@@ -875,5 +875,49 @@ describe('UsageCounter', () => {
totalTokens: 420,
});
});
+
+ it('should count the supplied attempt delta', () => {
+ const state = AgentRuntime.createInitialState();
+ const modelUsage: ModelUsage = { totalTokens: 10 };
+
+ const { usage } = UsageCounter.accumulateLLM({
+ apiCallsDelta: 3,
+ model: 'gpt-4',
+ modelUsage,
+ provider: 'openai',
+ usage: state.usage,
+ });
+
+ expect(usage.llm.apiCalls).toBe(3);
+ expect(usage.llm.tokens.total).toBe(10);
+ });
+ });
+
+ describe('UsageCounter.accumulateAttempts', () => {
+ it('should count attempts without adding tokens or cost', () => {
+ const state = AgentRuntime.createInitialState();
+
+ const usage = UsageCounter.accumulateAttempts(state.usage, 3);
+
+ expect(usage.llm.apiCalls).toBe(3);
+ expect(usage.llm.tokens.total).toBe(0);
+ expect(usage.llm.tokens.input).toBe(0);
+ expect(usage.llm.tokens.output).toBe(0);
+ });
+
+ it('should accumulate on top of existing usage', () => {
+ const state = AgentRuntime.createInitialState();
+ const withOne = UsageCounter.accumulateLLM({
+ model: 'gpt-4',
+ modelUsage: { totalTokens: 10 },
+ provider: 'openai',
+ usage: state.usage,
+ }).usage;
+
+ const usage = UsageCounter.accumulateAttempts(withOne, 2);
+
+ expect(usage.llm.apiCalls).toBe(3);
+ expect(usage.llm.tokens.total).toBe(10);
+ });
});
});
diff --git a/packages/agent-runtime/src/core/__tests__/llmCallCount.test.ts b/packages/agent-runtime/src/core/__tests__/llmCallCount.test.ts
new file mode 100644
index 00000000000..c160e38d93b
--- /dev/null
+++ b/packages/agent-runtime/src/core/__tests__/llmCallCount.test.ts
@@ -0,0 +1,232 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { Agent, AgentRuntimeContext, AgentState, Usage } from '../../types';
+import { getLlmCallCount, withLlmAttemptCount } from '../../utils/llmCalls';
+import { AgentRuntime } from '../runtime';
+
+const createContext = (): AgentRuntimeContext => ({
+ payload: {},
+ phase: 'user_input',
+ session: {
+ messageCount: 1,
+ sessionId: 'test-op',
+ status: 'idle',
+ stepCount: 0,
+ },
+});
+
+const createAgent = (): Agent =>
+ ({
+ executors: {},
+ modelRuntime: async function* () {
+ yield { content: 'ok' };
+ },
+ runner: async (context: AgentRuntimeContext) =>
+ context.phase === 'user_input'
+ ? { payload: { messages: [] }, type: 'call_llm' }
+ : { reason: 'completed', reasonDetail: 'Done', type: 'finish' },
+ tools: {},
+ }) as unknown as Agent;
+
+const createUsage = (apiCalls: number): Usage => ({
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: {
+ apiCalls,
+ processingTimeMs: 0,
+ tokens: { input: 0, output: 0, total: 0 },
+ },
+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
+});
+
+describe('llmCalls metric', () => {
+ it('increments llmCalls for LLM work but not for a finish-only step', async () => {
+ const runtime = new AgentRuntime(createAgent());
+ const state = AgentRuntime.createInitialState({
+ messages: [{ content: 'hi', role: 'user' }],
+ operationId: 'test-op',
+ });
+
+ const first = await runtime.step(state, createContext());
+ expect(first.newState.stepCount).toBe(1);
+ expect(first.newState.llmCalls).toBe(1);
+
+ const second = await runtime.step(first.newState, first.nextContext);
+ // `finish` is not a real execution step and not an LLM call either.
+ expect(second.newState.stepCount).toBe(1);
+ expect(second.newState.llmCalls).toBe(1);
+ });
+
+ it('counts provider attempts when the LLM call fails terminally', async () => {
+ const runtime = new AgentRuntime(createAgent());
+ // @ts-expect-error - accessing a private property for testing
+ runtime.executors.call_llm = vi
+ .fn()
+ .mockRejectedValue(withLlmAttemptCount(new Error('provider down'), 3));
+
+ const state = AgentRuntime.createInitialState({ operationId: 'test-op' });
+ const result = await runtime.step(state, createContext());
+
+ expect(result.newState.status).toBe('error');
+ expect(result.newState.usage?.llm.apiCalls).toBe(3);
+ expect(result.newState.llmCalls).toBe(3);
+ });
+
+ it('adds retried attempts on top of a resumed baseline', async () => {
+ const runtime = new AgentRuntime(createAgent());
+ // @ts-expect-error - accessing a private property for testing
+ runtime.executors.call_llm = vi.fn().mockImplementation(async (_instruction, state) => ({
+ events: [],
+ newState: { ...state, usage: createUsage(2) },
+ }));
+
+ const state = {
+ ...AgentRuntime.createInitialState({ operationId: 'test-op' }),
+ llmCalls: 5,
+ usage: createUsage(0),
+ };
+
+ const result = await runtime.step(state, createContext());
+
+ // 5 calls from the resumed trajectory + 2 provider attempts in this step,
+ // not max(2, 6).
+ expect(result.newState.llmCalls).toBe(7);
+ });
+
+ it('counts every call_llm instruction in one step when the executor leaves usage untouched', async () => {
+ // A runner may queue several LLM calls in a single step; the executor here
+ // does not mutate `usage`, so the fallback has to count the instructions
+ // instead of treating the step as one call.
+ const agent = {
+ ...createAgent(),
+ runner: async () =>
+ [
+ { payload: { messages: [] }, type: 'call_llm' },
+ { payload: { messages: [] }, type: 'call_llm' },
+ ] as any,
+ } as unknown as Agent;
+ const runtime = new AgentRuntime(agent);
+ // @ts-expect-error - accessing a private property for testing
+ runtime.executors.call_llm = vi
+ .fn()
+ .mockImplementation(async (_instruction, state) => ({ events: [], newState: state }));
+
+ const state = AgentRuntime.createInitialState({ operationId: 'test-op' });
+ const result = await runtime.step(state, createContext());
+
+ expect(result.newState.llmCalls).toBe(2);
+ });
+
+ it('keeps the earlier calls of a step when a later LLM call fails', async () => {
+ // Two `call_llm` instructions in one step: the first succeeded, the second
+ // burned two provider attempts and threw. Rebuilding the error state from
+ // the step-entry state used to report 2 calls and lose the first one.
+ const agent = {
+ ...createAgent(),
+ runner: async () =>
+ [
+ { payload: { messages: [] }, type: 'call_llm' },
+ { payload: { messages: [] }, type: 'call_llm' },
+ ] as any,
+ } as unknown as Agent;
+ const runtime = new AgentRuntime(agent);
+ // @ts-expect-error - accessing a private property for testing
+ runtime.executors.call_llm = vi
+ .fn()
+ .mockImplementationOnce(async (_instruction, state) => ({
+ events: [],
+ newState: { ...state, usage: createUsage(1) },
+ }))
+ .mockRejectedValueOnce(withLlmAttemptCount(new Error('provider down'), 2));
+
+ const state = AgentRuntime.createInitialState({ operationId: 'test-op' });
+ const result = await runtime.step(state, createContext());
+
+ expect(result.newState.status).toBe('error');
+ expect(result.newState.usage?.llm.apiCalls).toBe(3);
+ expect(result.newState.llmCalls).toBe(3);
+ });
+
+ it('keeps the calls of a step whose later non-LLM instruction throws', async () => {
+ // The successful call must not be reported as zero just because a tool in
+ // the same step exploded afterwards.
+ const agent = {
+ ...createAgent(),
+ runner: async () =>
+ [
+ { payload: { messages: [] }, type: 'call_llm' },
+ { payload: { toolCalling: {}, type: 'default' }, type: 'call_tool' },
+ ] as any,
+ } as unknown as Agent;
+ const runtime = new AgentRuntime(agent);
+ // @ts-expect-error - accessing a private property for testing
+ runtime.executors.call_llm = vi.fn().mockImplementation(async (_instruction, state) => ({
+ events: [],
+ newState: { ...state, usage: createUsage(1) },
+ }));
+ // @ts-expect-error - accessing a private property for testing
+ runtime.executors.call_tool = vi.fn().mockRejectedValue(new Error('tool exploded'));
+
+ const state = AgentRuntime.createInitialState({ operationId: 'test-op' });
+ const result = await runtime.step(state, createContext());
+
+ expect(result.newState.status).toBe('error');
+ expect(result.newState.llmCalls).toBe(1);
+ });
+
+ it('does not count a call_llm that failed before the transport ran', async () => {
+ // Missing model/provider, an absent parent message, or a rejected context
+ // all throw before `runAttempt`, so no provider call happened. The fallback
+ // must not invent one just because the instruction was queued.
+ const runtime = new AgentRuntime(createAgent());
+ // @ts-expect-error - accessing a private property for testing
+ runtime.executors.call_llm = vi
+ .fn()
+ .mockRejectedValue(new Error('call_llm produced no non-system messages'));
+
+ const state = AgentRuntime.createInitialState({ operationId: 'test-op' });
+ const result = await runtime.step(state, createContext());
+
+ expect(result.newState.status).toBe('error');
+ expect(result.newState.llmCalls).toBe(0);
+ expect(result.newState.usage?.llm.apiCalls ?? 0).toBe(0);
+ });
+
+ it('counts only the call_llm instructions whose executor ran', async () => {
+ // The first call reached the transport and left `usage` untouched, so the
+ // fallback counts it; the second failed preflight and never reached the
+ // provider, so it must not be counted on top.
+ const agent = {
+ ...createAgent(),
+ runner: async () =>
+ [
+ { payload: { messages: [] }, type: 'call_llm' },
+ { payload: { messages: [] }, type: 'call_llm' },
+ ] as any,
+ } as unknown as Agent;
+ const runtime = new AgentRuntime(agent);
+ // @ts-expect-error - accessing a private property for testing
+ runtime.executors.call_llm = vi
+ .fn()
+ .mockImplementationOnce(async (_instruction, state) => ({ events: [], newState: state }))
+ .mockRejectedValueOnce(new Error('Model and provider are required for call_llm'));
+
+ const state = AgentRuntime.createInitialState({ operationId: 'test-op' });
+ const result = await runtime.step(state, createContext());
+
+ expect(result.newState.status).toBe('error');
+ expect(result.newState.llmCalls).toBe(1);
+ });
+
+ it('reads the explicit llmCalls field before falling back to usage', () => {
+ const state = { llmCalls: 5, usage: createUsage(2) } as AgentState;
+ expect(getLlmCallCount(state)).toBe(5);
+
+ expect(getLlmCallCount({ usage: createUsage(2) })).toBe(2);
+ expect(getLlmCallCount(null)).toBe(0);
+ });
+});
diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.ts
index 4ade262ed3a..3493e841132 100644
--- a/packages/agent-runtime/src/core/runtime.ts
+++ b/packages/agent-runtime/src/core/runtime.ts
@@ -18,7 +18,9 @@ import type {
ToolsCalling,
Usage,
} from '../types';
+import { getLlmAttemptCount } from '../utils/llmCalls';
import { isBlockedStatus } from '../utils/status';
+import { UsageCounter } from './UsageCounter';
/**
* Simplified Agent Runtime - The "Engine" that executes instructions from an "Agent" (Brain).
@@ -83,6 +85,18 @@ export class AgentRuntime {
state: AgentState,
context?: AgentRuntimeContext,
): Promise<{ events: AgentEvent[]; newState: AgentState; nextContext?: AgentRuntimeContext }> {
+ // LLM-call accounting is additive. `usage.llm.apiCalls` only counts the
+ // current operation and `llmCalls` carries the seeded baseline of a resumed
+ // one, so remember where this step started and add the attempts it actually
+ // made instead of taking a max that drops retries.
+ const llmCallsBeforeStep = Math.max(state.llmCalls ?? 0, state.usage?.llm?.apiCalls ?? 0);
+ const apiCallsBeforeStep = state.usage?.llm?.apiCalls ?? 0;
+
+ // Tracked outside the try block: when an instruction throws, the error path
+ // still has to keep the work the earlier instructions of this step finished.
+ let latestState: AgentState | undefined;
+ let executedLlmInstructions = 0;
+
try {
// Increment step count and check limits
const newState = structuredClone(state);
@@ -215,10 +229,17 @@ export class AgentRuntime {
// Execute all instructions sequentially
let currentState = newState;
+ latestState = currentState;
const allEvents: AgentEvent[] = [];
let finalNextContext: AgentRuntimeContext | undefined = undefined;
let hasFinishInstruction = false;
+ // Counted rather than flagged: a runner may queue several `call_llm`
+ // instructions in one step (the fallback path when the selected executor
+ // does not mutate `usage`). Only the instructions whose executor actually
+ // ran are counted β€” see the increment inside the loop below.
+ executedLlmInstructions = 0;
+
for (const [instructionIndex, instruction] of normalizedInstructions.entries()) {
if (instruction.type === 'finish') hasFinishInstruction = true;
@@ -248,11 +269,21 @@ export class AgentRuntime {
result = await executor(instruction, currentState, instructionContext);
}
+ // Count a `call_llm` only once its executor returned. A preflight
+ // failure β€” missing model/provider, absent parent message, or a rejected
+ // context β€” throws before the transport is invoked, so no provider call
+ // happened. Counting it up-front would let the fallback in the success
+ // and error paths report a model call that never ran, and inflate the
+ // `maxSteps` budget with it.
+ if (instruction.type === 'call_llm') executedLlmInstructions += 1;
+
// Accumulate events
allEvents.push(...result.events);
// Update state
currentState = result.newState;
+ latestState = currentState;
+
// A call_llm consumes any resume-seeded assistant placeholder exactly
// once β€” it has now either reused that message id or created its own β€”
@@ -284,6 +315,13 @@ export class AgentRuntime {
// Ensure stepCount and lastModified are preserved
currentState.stepCount = newState.stepCount;
currentState.lastModified = newState.lastModified;
+ // Prefer the attempts the provider actually reported; fall back to one
+ // call per executed LLM instruction when usage is unavailable.
+ const apiCallsDelta = Math.max(
+ (currentState.usage?.llm?.apiCalls ?? 0) - apiCallsBeforeStep,
+ 0,
+ );
+ currentState.llmCalls = llmCallsBeforeStep + (apiCallsDelta || executedLlmInstructions);
// A 'finish' instruction is not a real execution step, undo the +1 from the top of step()
if (hasFinishInstruction) {
@@ -299,8 +337,28 @@ export class AgentRuntime {
nextContext: isBlockedStatus(currentState.status) ? undefined : finalNextContext,
};
} catch (error) {
- const errorState = structuredClone(state);
- errorState.stepCount += 1;
+ // Keep the progress this step already made. Earlier instructions may have
+ // reached the provider and mutated `usage`; rebuilding from the step-entry
+ // `state` would drop those calls, so a step whose second `call_llm` threw
+ // reported only the failed call and a step whose later tool threw reported
+ // the successful call as zero.
+ const errorState = structuredClone(latestState ?? state);
+ // `newState` bumped the counter before the first instruction; only the
+ // untouched step-entry state still needs it.
+ if (!latestState) errorState.stepCount += 1;
+
+ // A terminated LLM call still made provider attempts. Record them even
+ // though no output was finalized, so the user-facing count and the
+ // `maxSteps` budget match what actually happened.
+ const llmAttempts = getLlmAttemptCount(error);
+ if (llmAttempts > 0) {
+ errorState.usage = UsageCounter.accumulateAttempts(errorState.usage, llmAttempts);
+ }
+ const apiCallsDelta = Math.max(
+ (errorState.usage?.llm?.apiCalls ?? 0) - apiCallsBeforeStep,
+ 0,
+ );
+ errorState.llmCalls = llmCallsBeforeStep + (apiCallsDelta || executedLlmInstructions);
errorState.lastModified = new Date().toISOString();
return this.createErrorResult(errorState, error);
}
@@ -524,6 +582,7 @@ export class AgentRuntime {
messages: [],
status: 'idle',
stepCount: 0,
+ llmCalls: 0,
usage: AgentRuntime.createDefaultUsage(),
// User provided values override defaults
...(partialState || { operationId: '' }),
diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.ts
index 56f1eebabc3..b3afbe5d119 100644
--- a/packages/agent-runtime/src/executors/callLlm.test.ts
+++ b/packages/agent-runtime/src/executors/callLlm.test.ts
@@ -418,6 +418,7 @@ describe('callLlm executor', () => {
const error = new Error('temporary outage');
const firstOutput = createAttemptOutput('partial');
const finalOutput = createAttemptOutput('complete');
+ finalOutput.usage = { totalTokens: 10 };
const runAttempt = vi
.fn()
.mockResolvedValueOnce({ error, ok: false, output: firstOutput })
@@ -489,6 +490,8 @@ describe('callLlm executor', () => {
type: 'stream_retry',
});
expect(policy.waitForRetry).toHaveBeenCalledWith(1000);
+ // Both provider attempts count toward the user-facing LLM-call metric.
+ expect(result.newState.usage?.llm.apiCalls).toBe(2);
expect(result.newState.messages.at(-1)).toMatchObject({ content: 'complete' });
expect(transport.trace.recordResult).toHaveBeenCalledWith(finalOutput);
expect(policy.onError).not.toHaveBeenCalled();
diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.ts
index 488f9b0ff25..5e003ef9064 100644
--- a/packages/agent-runtime/src/executors/callLlm.ts
+++ b/packages/agent-runtime/src/executors/callLlm.ts
@@ -13,6 +13,7 @@ import type {
CallLLMPayload,
InstructionExecutor,
} from '../types';
+import { withLlmAttemptCount } from '../utils/llmCalls';
import { getLLMRetryDelayMs, shouldRetryLLM } from '../utils/runtimeRetry';
import { finalizeCallLlmTurn, persistInterruptedCallLlmResult } from './callLlmFinalizer';
@@ -76,6 +77,7 @@ const executePreparedCall = async (
let errorHandled = false;
let lastOutput: LLMAttemptOutput | undefined;
let terminalError: unknown;
+ let attemptsMade = 0;
try {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
@@ -93,10 +95,12 @@ const executePreparedCall = async (
}),
);
lastOutput = execution.output;
+ attemptsMade = attempt;
if (execution.ok) {
return await finalizeCallLlmTurn({
assistantMessageId: prepared.assistantMessageId,
+ attempts: attemptsMade,
events,
host,
model: prepared.model,
@@ -162,10 +166,13 @@ const executePreparedCall = async (
retryBudget,
});
});
- throw error;
+ throw withLlmAttemptCount(error, attemptsMade);
}
- throw new Error('LLM execution retry loop exited unexpectedly');
+ throw withLlmAttemptCount(
+ new Error('LLM execution retry loop exited unexpectedly'),
+ attemptsMade,
+ );
} catch (error) {
terminalError = error;
if (!errorHandled) {
@@ -186,7 +193,7 @@ const executePreparedCall = async (
});
});
}
- throw error;
+ throw withLlmAttemptCount(error, attemptsMade);
} finally {
await trace?.close(terminalError);
}
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index 4f4d9c747e9..8729feaf301 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -677,6 +677,22 @@ describe('callLlmFinalizer', () => {
consoleError.mockRestore();
});
+ it('counts provider attempts even when a successful response omits usage', async () => {
+ const result = await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-1',
+ attempts: 2,
+ events: [],
+ host: createHost(),
+ model: 'gpt-4',
+ output: createOutput({ usage: undefined }),
+ provider: 'openai',
+ shouldReplayAssistantReasoning: false,
+ state: AgentRuntime.createInitialState({ operationId: 'operation-1' }),
+ });
+
+ expect(result.newState.usage.llm.apiCalls).toBe(2);
+ });
+
it('does not publish early visible output end when the host disables it', async () => {
const stream = createStreamSink();
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index 9d0633f09a4..00734466e87 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -44,6 +44,8 @@ interface CallLlmMessageMetadata extends MessageMetadata {
interface FinalizeCallLlmTurnInput {
assistantMessageId: string;
+ /** Provider attempts spent on this call, including retries. */
+ attempts?: number;
events: AgentEvent[];
host: AgentRuntimeHost;
model: string;
@@ -219,6 +221,7 @@ const persistFinalMessage = async ({
const buildFinalState = ({
assistantMessageId,
+ attempts,
model,
output,
provider,
@@ -250,6 +253,7 @@ const buildFinalState = ({
if (output.usage) {
const { usage, cost } = UsageCounter.accumulateLLM({
+ apiCallsDelta: attempts ?? 1,
cost: newState.cost,
model,
modelUsage: output.usage,
@@ -259,6 +263,11 @@ const buildFinalState = ({
newState.usage = usage;
if (cost) newState.cost = cost;
+ } else {
+ // A successful response may omit usage. The provider attempt still
+ // happened, so record it independently of token accumulation instead of
+ // dropping it from the LLM-call metric.
+ newState.usage = UsageCounter.accumulateAttempts(newState.usage, Math.max(attempts ?? 1, 1));
}
if (stepLabel || visibleOutputEndPublishedStepIndex !== undefined) {
@@ -276,6 +285,7 @@ const buildFinalState = ({
export const finalizeCallLlmTurn = async ({
assistantMessageId,
+ attempts,
events,
host,
model,
@@ -363,6 +373,7 @@ export const finalizeCallLlmTurn = async ({
});
const newState = buildFinalState({
assistantMessageId,
+ attempts,
finalReasoning,
model,
output: finalizedOutput,
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index a8ba3db0c6d..12fc57cab89 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -418,6 +418,14 @@ export interface AgentState {
};
lastModified: string;
+ /**
+ * User-facing count of LLM calls made by this operation.
+ *
+ * Kept in sync with `usage.llm.apiCalls` at every step boundary. Unlike
+ * {@link stepCount}, tool-only runtime iterations do not increase it.
+ */
+ llmCalls?: number;
+
/**
* Optional maximum number of steps allowed.
* If set, execution will stop with error when exceeded.
@@ -470,7 +478,6 @@ export interface AgentState {
provider: string;
};
};
-
/**
* Credentials this run listed once when it was created. A step renders
* `{{CREDS_LIST}}` from here instead of asking the Market API again; absent
@@ -481,13 +488,13 @@ export interface AgentState {
operationId: string;
/** Operation-level tool set snapshot (immutable after creation) */
operationToolSet?: OperationToolSet;
+
// --- Origin ---
/**
* Where this run came from and where it sits in the run tree. Frozen when
* the operation is created.
*/
origin?: AgentRunOrigin;
-
pendingApprovalBatch?: {
assistantMessageId: string;
id: string;
@@ -515,8 +522,8 @@ export interface AgentState {
* Cleared once consumed.
*/
pendingAssistantMessageId?: string;
- pendingHumanPrompt?: { metadata?: Record<string, unknown>; prompt: string };
+ pendingHumanPrompt?: { metadata?: Record<string, unknown>; prompt: string };
pendingHumanSelect?: {
metadata?: Record<string, unknown>;
multi?: boolean;
@@ -538,6 +545,7 @@ export interface AgentState {
principal?: AgentRunPrincipal;
/** @deprecated Use `principal.policy.securityBlacklist`. */
securityBlacklist?: SecurityBlacklistConfig;
+
// --- State Machine ---
status:
| 'idle'
@@ -553,6 +561,11 @@ export interface AgentState {
/**
* Number of execution steps in this session.
* Incremented on each runtime.step() call.
+ *
+ * This is the scheduling/idempotency counter (QStash `stepIndex`, stale
+ * delivery guards, resume). It intentionally keeps its original meaning so
+ * workers from the previous build can keep scheduling during a rolling
+ * deploy.
*/
stepCount: number;
diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.ts
index 66aa168681c..f51bfd2b26a 100644
--- a/packages/agent-runtime/src/utils/index.ts
+++ b/packages/agent-runtime/src/utils/index.ts
@@ -1,3 +1,4 @@
+export * from './llmCalls';
export * from './llmErrorClassifier';
export * from './messageSelectors';
export * from './normalizeAgentState';
diff --git a/packages/agent-runtime/src/utils/llmCalls.ts b/packages/agent-runtime/src/utils/llmCalls.ts
new file mode 100644
index 00000000000..9aa6ea83bc1
--- /dev/null
+++ b/packages/agent-runtime/src/utils/llmCalls.ts
@@ -0,0 +1,48 @@
+import type { AgentState } from '../types';
+
+/**
+ * User-facing LLM-call count for an operation.
+ *
+ * Prefers the field maintained by the runtime and falls back to the usage
+ * counter for states written before the field existed (or by a pre-slot
+ * worker during a rolling deploy).
+ */
+export const getLlmCallCount = (
+ state?: { llmCalls?: number; usage?: AgentState['usage'] } | null,
+): number => {
+ if (!state) return 0;
+ // `usage` stays authoritative across a rolling deploy: a pre-slot worker
+ // keeps accumulating it but never updates the new `llmCalls` field. Take the
+ // larger value so a stale field can never under-report real calls.
+ return Math.max(state.llmCalls ?? 0, state.usage?.llm?.apiCalls ?? 0);
+};
+
+/**
+ * Attempts made by a failed LLM call are carried on the thrown error so the
+ * runtime can still record them in the usage counter (a terminal failure has
+ * no finalized output to accumulate from).
+ */
+const LLM_ATTEMPT_COUNT_KEY = 'llmAttempts';
+
+export const getLlmAttemptCount = (error: unknown): number => {
+ if (!error || typeof error !== 'object') return 0;
+ const value = (error as Record<string, unknown>)[LLM_ATTEMPT_COUNT_KEY];
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
+};
+
+export const withLlmAttemptCount = <T>(error: T, attempts: number): T => {
+ if (error && typeof error === 'object') {
+ Object.defineProperty(error, LLM_ATTEMPT_COUNT_KEY, {
+ configurable: true,
+ enumerable: false,
+ value: attempts,
+ writable: true,
+ });
+ return error;
+ }
+
+ return Object.assign(new Error(String(error)), {
+ [LLM_ATTEMPT_COUNT_KEY]: attempts,
+ cause: error,
+ }) as T;
+};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 473d2c94c31..6585211a8e4 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1441,6 +1441,7 @@ export default {
'opStatusTray.status.toolCalling': 'Calling tools',
'opStatusTray.cost': 'cost',
'opStatusTray.steps': 'steps',
+ 'opStatusTray.llmCalls': 'LLM calls',
'opStatusTray.tokens': 'tokens',
// Connect Agent wizard (device-first): pick a machine, auto-scan the agents
@@ -1891,6 +1892,7 @@ export default {
'task.intermediateSteps': '{{count}} intermediate steps',
'task.metrics.duration': '(took {{duration}})',
'task.metrics.stepsShort': 'steps',
+ 'task.metrics.llmCallsShort': 'LLM calls',
'task.metrics.toolCallsShort': 'skill uses',
'task.status.cancelled': 'Task Cancelled',
'task.status.failed': 'Task Failed',
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 3938fe398ee..c31be19122d 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -187,7 +187,10 @@ export interface TaskDetail {
totalCost?: number;
/** Total messages created during execution */
totalMessages?: number;
- /** Total execution steps */
+ /**
+ * Total LLM calls made during execution β€” the user-facing step metric.
+ * Tool-only runtime iterations are not counted here.
+ */
totalSteps?: number;
/** Total tokens consumed */
totalTokens?: number;
diff --git a/packages/types/src/topic/thread.ts b/packages/types/src/topic/thread.ts
index 70b6020f12d..6799d46d82c 100644
--- a/packages/types/src/topic/thread.ts
+++ b/packages/types/src/topic/thread.ts
@@ -68,8 +68,18 @@ export interface ThreadMetadata {
subagentType?: string;
/** Total cost in dollars */
totalCost?: number;
+ /**
+ * Total LLM calls made (user-facing step metric).
+ *
+ * Versioned baseline for continuation runs: legacy threads only have
+ * `totalSteps` in execution-step units, so that value must not be reused to
+ * accumulate LLM calls.
+ */
+ totalLlmCalls?: number;
/** Total messages created during execution */
totalMessages?: number;
+ /** Total LLM calls made (user-facing step metric) */
+ totalSteps?: number;
/** Total tokens consumed */
totalTokens?: number;
/** Total tool calls made */
@@ -132,8 +142,10 @@ export const threadMetadataSchema = z.object({
startedAt: z.string().optional(),
subagentType: z.string().optional(),
totalCost: z.number().optional(),
+ totalLlmCalls: z.number().optional(),
totalMessages: z.number().optional(),
totalTokens: z.number().optional(),
+ totalSteps: z.number().optional(),
totalToolCalls: z.number().optional(),
});
diff --git a/src/features/Conversation/ChatInput/OpStatusTray.tsx b/src/features/Conversation/ChatInput/OpStatusTray.tsx
index 792544c4532..3c5b0a87b16 100644
--- a/src/features/Conversation/ChatInput/OpStatusTray.tsx
+++ b/src/features/Conversation/ChatInput/OpStatusTray.tsx
@@ -3,7 +3,7 @@
import { formatElapsedClockTime } from '@lobechat/utils';
import { createStaticStyles, cx, Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
import type { LucideIcon } from 'lucide-react';
-import { CircleDollarSignIcon, CoinsIcon, FootprintsIcon } from 'lucide-react';
+import { BrainCircuitIcon, CircleDollarSignIcon, CoinsIcon } from 'lucide-react';
import { Fragment, memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -215,9 +215,9 @@ const formatCost = (cost: number) => {
return cost.toFixed(2);
};
-const normalizeStepCount = (stepCount: unknown) => {
- if (typeof stepCount !== 'number' || !Number.isFinite(stepCount)) return 0;
- return Math.max(0, Math.floor(stepCount));
+const normalizeCount = (count: unknown) => {
+ if (typeof count !== 'number' || !Number.isFinite(count)) return 0;
+ return Math.max(0, Math.floor(count));
};
interface OpStatusTrayProps {
@@ -234,7 +234,7 @@ interface OpStatusTrayProps {
interface MetricItem {
icon: LucideIcon;
- key: 'cost' | 'steps' | 'tokens';
+ key: 'cost' | 'llmCalls' | 'tokens';
label: string;
title: string;
value: string;
@@ -250,8 +250,8 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {
let activity: ActivityKey | undefined;
let earliestStart: number | undefined;
let latestActivityStart = -1;
+ let llmCalls = 0;
let statusSeed: string | undefined;
- let stepCount = 0;
const runtimeOperationIds: string[] = [];
for (const op of ops) {
@@ -270,7 +270,13 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {
}
runtimeOperationIds.push(op.id);
- stepCount = Math.max(stepCount, normalizeStepCount(op.metadata.stepCount));
+ // Prefer the explicit LLM-call total; older servers only sent the
+ // execution step index, which is the best available fallback.
+ const opLlmCalls =
+ typeof op.metadata.llmCalls === 'number'
+ ? normalizeCount(op.metadata.llmCalls)
+ : normalizeCount(op.metadata.stepCount);
+ llmCalls = Math.max(llmCalls, opLlmCalls);
const turnStartTime = op.metadata.turnStartTime ?? op.metadata.startTime;
if (earliestStart === undefined || turnStartTime < earliestStart) {
@@ -280,10 +286,10 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {
}
return {
activity: activity ?? 'generating',
+ llmCalls,
operationIdsKey: runtimeOperationIds.join('|'),
startTime: earliestStart,
statusSeed,
- steps: stepCount,
};
});
const operationsByMessage = useChatStore((s) => s.operationsByMessage);
@@ -319,7 +325,7 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {
const { totalCost, totalTokens } = usageMetrics;
const elapsed = now - startTime;
const costLabel = t('chat:opStatusTray.cost');
- const stepLabel = t('chat:opStatusTray.steps');
+ const llmCallsLabel = t('chat:opStatusTray.llmCalls');
const tokenLabel = t('chat:opStatusTray.tokens', { defaultValue: 'tokens' });
const generatingPhrases = parseStatusPhrases(
t('opStatusTray:generatingPhrases', {
@@ -339,16 +345,16 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {
? randomGeneratingStatus
: t(`chat:opStatusTray.status.${operationState.activity}`);
- // Zero-valued metrics render nothing; steps only matter for long-running
- // multi-step tasks, so a single step stays hidden too.
+ // Zero-valued metrics render nothing. LLM calls are the user-facing "step"
+ // metric: tool-only iterations never increment it.
const metrics = [
- operationState.steps > 1
+ operationState.llmCalls > 0
? {
- icon: FootprintsIcon,
- key: 'steps',
- label: stepLabel,
- title: `${operationState.steps} ${stepLabel}`,
- value: String(operationState.steps),
+ icon: BrainCircuitIcon,
+ key: 'llmCalls',
+ label: llmCallsLabel,
+ title: `${operationState.llmCalls} ${llmCallsLabel}`,
+ value: String(operationState.llmCalls),
}
: undefined,
totalTokens > 0
diff --git a/src/features/Conversation/Messages/GroupTasks/TaskItem/ClientTaskItem.tsx b/src/features/Conversation/Messages/GroupTasks/TaskItem/ClientTaskItem.tsx
index 200fed496a8..114e3724ff6 100644
--- a/src/features/Conversation/Messages/GroupTasks/TaskItem/ClientTaskItem.tsx
+++ b/src/features/Conversation/Messages/GroupTasks/TaskItem/ClientTaskItem.tsx
@@ -6,7 +6,7 @@ import { memo, useMemo, useState } from 'react';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { useChatStore } from '@/store/chat';
-import { displayMessageSelectors } from '@/store/chat/selectors';
+import { displayMessageSelectors, operationSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { type UIChatMessage } from '@/types/index';
import { ThreadStatus } from '@/types/index';
@@ -75,6 +75,18 @@ const ClientTaskItem = memo<ClientTaskItemProps>(({ item }) => {
[threadId, threadContext],
);
+ // A provider retry is several LLM calls but still one finalized assistant
+ // block, so `blocks.length` under-counts while the task is processing and then
+ // jumps when the completion snapshot arrives. Prefer the live counter the
+ // runtime publishes on this thread's operation metadata.
+ const liveLlmCalls = useChatStore((s) =>
+ threadId
+ ? operationSelectors
+ .getOperationsByContext(threadContext)(s)
+ .reduce((max, op) => Math.max(max, op.metadata.llmCalls ?? 0), 0)
+ : 0,
+ );
+
// Fetch thread messages (skip when executing - messages come from real-time updates)
useFetchMessages(threadContext, { skipFetch: isProcessing });
@@ -104,14 +116,15 @@ const ClientTaskItem = memo<ClientTaskItemProps>(({ item }) => {
// invoked) rather than the in-thread first assistant's createdAt (when the
// thread finished initializing) β€” the latter excludes init / approval wait.
startTime: item.createdAt,
- steps: blocks.length,
+ llmCalls: liveLlmCalls || blocks.length,
toolCalls,
};
}
if (isCompleted || isError) {
return {
duration: taskDetail?.duration,
- steps: taskDetail?.totalSteps,
+ // `totalSteps` is the server's user-facing step metric: actual LLM calls.
+ llmCalls: taskDetail?.totalSteps,
toolCalls: taskDetail?.totalToolCalls,
};
}
@@ -121,6 +134,7 @@ const ClientTaskItem = memo<ClientTaskItemProps>(({ item }) => {
isCompleted,
isError,
blocks,
+ liveLlmCalls,
item.createdAt,
taskDetail?.duration,
taskDetail?.totalSteps,
diff --git a/src/features/Conversation/Messages/GroupTasks/TaskItem/ServerTaskItem.tsx b/src/features/Conversation/Messages/GroupTasks/TaskItem/ServerTaskItem.tsx
index e58dcd41846..3e4ba65c55e 100644
--- a/src/features/Conversation/Messages/GroupTasks/TaskItem/ServerTaskItem.tsx
+++ b/src/features/Conversation/Messages/GroupTasks/TaskItem/ServerTaskItem.tsx
@@ -41,7 +41,8 @@ const ServerTaskItem = memo<ServerTaskItemProps>(({ item }) => {
if (isCompleted || isError) {
return {
duration: taskDetail?.duration,
- steps: taskDetail?.totalSteps,
+ // `totalSteps` is the server's user-facing step metric: actual LLM calls.
+ llmCalls: taskDetail?.totalSteps,
toolCalls: taskDetail?.totalToolCalls,
};
}
diff --git a/src/features/Conversation/Messages/GroupTasks/TaskItem/TaskTitle.tsx b/src/features/Conversation/Messages/GroupTasks/TaskItem/TaskTitle.tsx
index d20a21944fb..207f3e2bd8d 100644
--- a/src/features/Conversation/Messages/GroupTasks/TaskItem/TaskTitle.tsx
+++ b/src/features/Conversation/Messages/GroupTasks/TaskItem/TaskTitle.tsx
@@ -2,7 +2,7 @@
import { ThreadStatus } from '@lobechat/types';
import { Avatar, Block, cssVar, Flexbox, Icon, Spin, Text } from '@lobehub/ui';
-import { Footprints, ListChecksIcon, Wrench, XIcon } from 'lucide-react';
+import { BrainCircuit, ListChecksIcon, Wrench, XIcon } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,10 +15,10 @@ export interface TaskMetrics {
duration?: number;
/** Whether metrics are still loading */
isLoading?: boolean;
+ /** Number of LLM calls made by the task */
+ llmCalls?: number;
/** Start time timestamp for elapsed time calculation */
startTime?: number;
- /** Number of execution steps/blocks */
- steps?: number;
/** Total tool calls count */
toolCalls?: number;
}
@@ -29,7 +29,7 @@ interface TaskTitleProps {
avatar?: string;
backgroundColor?: string | null;
};
- /** Metrics to display (steps, tool calls, elapsed time) */
+ /** Metrics to display (LLM calls, tool calls, elapsed time) */
metrics?: TaskMetrics;
status?: ThreadStatus;
title?: string;
@@ -81,7 +81,7 @@ interface MetricsDisplayProps {
const MetricsDisplay = memo<MetricsDisplayProps>(({ metrics, status }) => {
const { t } = useTranslation('chat');
- const { steps, toolCalls, startTime, duration, isLoading } = metrics;
+ const { llmCalls, toolCalls, startTime, duration, isLoading } = metrics;
const [elapsedTime, setElapsedTime] = useState(0);
const isProcessing = status ? isProcessingStatus(status) : false;
@@ -107,21 +107,21 @@ const MetricsDisplay = memo<MetricsDisplayProps>(({ metrics, status }) => {
// Don't show metrics if loading or no data
if (isLoading) return null;
- const hasSteps = steps !== undefined && steps > 0;
+ const hasLlmCalls = llmCalls !== undefined && llmCalls > 0;
const hasToolCalls = toolCalls !== undefined && toolCalls > 0;
const hasTime = isProcessing ? startTime !== undefined : duration !== undefined;
// Don't render if no metrics to show
- if (!hasSteps && !hasToolCalls && !hasTime) return null;
+ if (!hasLlmCalls && !hasToolCalls && !hasTime) return null;
return (
<Flexbox horizontal align="center" gap={8}>
- {/* Steps */}
- {hasSteps && (
+ {/* LLM calls */}
+ {hasLlmCalls && (
<Flexbox horizontal align="center" gap={2}>
- <Icon color={cssVar.colorTextTertiary} icon={Footprints} size={12} />
+ <Icon color={cssVar.colorTextTertiary} icon={BrainCircuit} size={12} />
<Text fontSize={12} type="secondary">
- {steps}
+ {llmCalls}
</Text>
</Flexbox>
)}
diff --git a/src/features/Conversation/Messages/Tasks/TaskItem/ClientTaskItem.tsx b/src/features/Conversation/Messages/Tasks/TaskItem/ClientTaskItem.tsx
index 7338f41912a..b11b58f28a8 100644
--- a/src/features/Conversation/Messages/Tasks/TaskItem/ClientTaskItem.tsx
+++ b/src/features/Conversation/Messages/Tasks/TaskItem/ClientTaskItem.tsx
@@ -4,7 +4,7 @@ import { Accordion, Block, Text } from '@lobehub/ui';
import { memo, useMemo, useState } from 'react';
import { useChatStore } from '@/store/chat';
-import { displayMessageSelectors } from '@/store/chat/selectors';
+import { displayMessageSelectors, operationSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { type UIChatMessage } from '@/types/index';
import { ThreadStatus } from '@/types/index';
@@ -60,6 +60,18 @@ const ClientTaskItem = memo<ClientTaskItemProps>(({ item }) => {
[threadId, threadContext],
);
+ // A provider retry is several LLM calls but still one finalized assistant
+ // block, so `blocks.length` under-counts while the task is processing and then
+ // jumps when the completion snapshot arrives. Prefer the live counter the
+ // runtime publishes on this thread's operation metadata.
+ const liveLlmCalls = useChatStore((s) =>
+ threadId
+ ? operationSelectors
+ .getOperationsByContext(threadContext)(s)
+ .reduce((max, op) => Math.max(max, op.metadata.llmCalls ?? 0), 0)
+ : 0,
+ );
+
// Fetch thread messages (skip when executing - messages come from real-time updates)
useFetchMessages(threadContext, { skipFetch: isProcessing });
@@ -89,14 +101,15 @@ const ClientTaskItem = memo<ClientTaskItemProps>(({ item }) => {
// invoked) rather than the in-thread first assistant's createdAt (when the
// thread finished initializing) β€” the latter excludes init / approval wait.
startTime: item.createdAt,
- steps: blocks.length,
+ llmCalls: liveLlmCalls || blocks.length,
toolCalls,
};
}
if (isCompleted || isError) {
return {
duration: taskDetail?.duration,
- steps: taskDetail?.totalSteps,
+ // `totalSteps` is the server's user-facing step metric: actual LLM calls.
+ llmCalls: taskDetail?.totalSteps,
toolCalls: taskDetail?.totalToolCalls,
};
}
@@ -106,6 +119,7 @@ const ClientTaskItem = memo<ClientTaskItemProps>(({ item }) => {
isCompleted,
isError,
blocks,
+ liveLlmCalls,
item.createdAt,
taskDetail?.duration,
taskDetail?.totalSteps,
diff --git a/src/features/Conversation/Messages/Tasks/TaskItem/ServerTaskItem.tsx b/src/features/Conversation/Messages/Tasks/TaskItem/ServerTaskItem.tsx
index 568ab907e34..903544a8a00 100644
--- a/src/features/Conversation/Messages/Tasks/TaskItem/ServerTaskItem.tsx
+++ b/src/features/Conversation/Messages/Tasks/TaskItem/ServerTaskItem.tsx
@@ -30,7 +30,8 @@ const ServerTaskItem = memo<ServerTaskItemProps>(({ item }) => {
if (isCompleted || isError) {
return {
duration: taskDetail?.duration,
- steps: taskDetail?.totalSteps,
+ // `totalSteps` is the server's user-facing step metric: actual LLM calls.
+ llmCalls: taskDetail?.totalSteps,
toolCalls: taskDetail?.totalToolCalls,
};
}
diff --git a/src/features/Conversation/Messages/Tasks/TaskItem/TaskTitle.tsx b/src/features/Conversation/Messages/Tasks/TaskItem/TaskTitle.tsx
index 175658ab780..81fbbbd89fd 100644
--- a/src/features/Conversation/Messages/Tasks/TaskItem/TaskTitle.tsx
+++ b/src/features/Conversation/Messages/Tasks/TaskItem/TaskTitle.tsx
@@ -1,7 +1,7 @@
'use client';
import { Block, cssVar, Flexbox, Icon, Spin, Text } from '@lobehub/ui';
-import { Footprints, ListChecksIcon, Wrench, XIcon } from 'lucide-react';
+import { BrainCircuit, ListChecksIcon, Wrench, XIcon } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,16 +14,16 @@ export interface TaskMetrics {
duration?: number;
/** Whether metrics are still loading */
isLoading?: boolean;
+ /** Number of LLM calls made by the task */
+ llmCalls?: number;
/** Start time timestamp for elapsed time calculation */
startTime?: number;
- /** Number of execution steps/blocks */
- steps?: number;
/** Total tool calls count */
toolCalls?: number;
}
interface TaskTitleProps {
- /** Metrics to display (steps, tool calls, elapsed time) */
+ /** Metrics to display (LLM calls, tool calls, elapsed time) */
metrics?: TaskMetrics;
status?: ThreadStatus;
title?: string;
@@ -75,7 +75,7 @@ interface MetricsDisplayProps {
const MetricsDisplay = memo<MetricsDisplayProps>(({ metrics, status }) => {
const { t } = useTranslation('chat');
- const { steps, toolCalls, startTime, duration, isLoading } = metrics;
+ const { llmCalls, toolCalls, startTime, duration, isLoading } = metrics;
const [elapsedTime, setElapsedTime] = useState(0);
const isProcessing = status ? isProcessingStatus(status) : false;
@@ -101,21 +101,21 @@ const MetricsDisplay = memo<MetricsDisplayProps>(({ metrics, status }) => {
// Don't show metrics if loading or no data
if (isLoading) return null;
- const hasSteps = steps !== undefined && steps > 0;
+ const hasLlmCalls = llmCalls !== undefined && llmCalls > 0;
const hasToolCalls = toolCalls !== undefined && toolCalls > 0;
const hasTime = isProcessing ? startTime !== undefined : duration !== undefined;
// Don't render if no metrics to show
- if (!hasSteps && !hasToolCalls && !hasTime) return null;
+ if (!hasLlmCalls && !hasToolCalls && !hasTime) return null;
return (
<Flexbox horizontal align="center" gap={8}>
- {/* Steps */}
- {hasSteps && (
+ {/* LLM calls */}
+ {hasLlmCalls && (
<Flexbox horizontal align="center" gap={2}>
- <Icon color={cssVar.colorTextTertiary} icon={Footprints} size={12} />
+ <Icon color={cssVar.colorTextTertiary} icon={BrainCircuit} size={12} />
<Text fontSize={12} type="secondary">
- {steps}
+ {llmCalls}
</Text>
</Flexbox>
)}
diff --git a/src/features/Conversation/Messages/Tasks/shared/CompletedState.tsx b/src/features/Conversation/Messages/Tasks/shared/CompletedState.tsx
index bb3fff1170e..df651050926 100644
--- a/src/features/Conversation/Messages/Tasks/shared/CompletedState.tsx
+++ b/src/features/Conversation/Messages/Tasks/shared/CompletedState.tsx
@@ -3,7 +3,7 @@
import { type TaskDetail } from '@lobechat/types';
import { type IconProps } from '@lobehub/ui';
import { createStaticStyles, cssVar, Flexbox, Icon, Tag } from '@lobehub/ui';
-import { Footprints, Timer, Wrench } from 'lucide-react';
+import { BrainCircuit, Timer, Wrench } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -70,8 +70,8 @@ const MetricsRow = memo<MetricsRowProps>(
// Build metrics array in order
if (totalSteps !== undefined && totalSteps > 0) {
metrics.push({
- icon: Footprints,
- label: t('task.metrics.stepsShort'),
+ icon: BrainCircuit,
+ label: t('task.metrics.llmCallsShort'),
value: totalSteps,
});
}
diff --git a/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx b/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx
index 94e6af6dd42..1f7f2587313 100644
--- a/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx
+++ b/src/features/Conversation/Messages/Tasks/shared/ProcessingState.tsx
@@ -2,7 +2,7 @@
import { type TaskDetail } from '@lobechat/types';
import { createStaticStyles, Flexbox, keyframes, Spin, Text } from '@lobehub/ui';
-import { Footprints, Timer, Wrench } from 'lucide-react';
+import { BrainCircuit, Timer, Wrench } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -250,14 +250,14 @@ const ProcessingState = memo<ProcessingStateProps>(
)}
</Flexbox>
<Flexbox horizontal align="center" gap={12}>
- {/* Steps */}
+ {/* LLM calls (`totalSteps` holds the LLM-call total) */}
{totalSteps !== undefined && totalSteps > 0 && (
<Text as={'span'} fontSize={12} type={'secondary'}>
- <Footprints size={12} />
+ <BrainCircuit size={12} />
<Text as={'span'} fontSize={12} type={'secondary'} weight={500}>
{totalSteps}
</Text>
- <span>{t('task.metrics.stepsShort')}</span>
+ <span>{t('task.metrics.llmCallsShort')}</span>
</Text>
)}
{/* Tool Calls */}
@@ -332,11 +332,11 @@ const ProcessingState = memo<ProcessingStateProps>(
<Flexbox horizontal align="center" gap={12}>
{totalSteps !== undefined && totalSteps > 0 && (
<Text as={'span'} fontSize={12} type={'secondary'}>
- <Footprints size={12} />
+ <BrainCircuit size={12} />
<Text as={'span'} fontSize={12} type={'secondary'} weight={500}>
{totalSteps}
</Text>
- <span>{t('task.metrics.stepsShort')}</span>
+ <span>{t('task.metrics.llmCallsShort')}</span>
</Text>
)}
{totalToolCalls !== undefined && totalToolCalls > 0 && (
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 440cf02f458..29d9e2274db 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -296,6 +296,7 @@ export interface UpdateClientTaskThreadStatusParams {
error?: string;
metadata?: {
totalCost?: number;
+ totalLlmCalls?: number;
totalMessages?: number;
totalSteps?: number;
totalTokens?: number;
diff --git a/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts
index 500edf6bbbb..3325a5076e9 100644
--- a/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts
@@ -120,6 +120,10 @@ export const executeDirectMention = async (
metadata: {
totalCost: runtimeResult?.cost?.total,
totalMessages: threadMessages.length,
+ // `totalSteps` is the user-facing step metric: actual LLM calls.
+ // `totalLlmCalls` is the versioned continuation baseline.
+ totalLlmCalls: runtimeResult?.usage?.llm?.apiCalls,
+ totalSteps: runtimeResult?.usage?.llm?.apiCalls,
totalTokens: metrics.totalTokens,
totalToolCalls: metrics.toolCalls,
},
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index 8d18e89d046..6c3b1c7e82a 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -9,6 +9,7 @@ import {
AgentRuntime,
computeStepContext,
GeneralChatAgent,
+ getLlmCallCount,
isParkedStatus,
} from '@lobechat/agent-runtime';
import { createDryRunAudit, DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';
@@ -885,6 +886,9 @@ export class StreamingExecutorActionImpl {
state = result.newState;
+ // User-facing LLM-call total; `stepCount` above remains the execution index.
+ this.#get().updateOperationMetadata(operationId, { llmCalls: getLlmCallCount(state) });
+
// Check if operation was cancelled after step completion
const operationAfterStep = this.#get().operations[operationId];
if (operationAfterStep?.status === 'cancelled') {
@@ -1149,6 +1153,8 @@ export class StreamingExecutorActionImpl {
metadata: {
totalCost,
totalMessages: subTaskMessages.length,
+ totalLlmCalls: usage?.llm?.apiCalls,
+ totalSteps: usage?.llm?.apiCalls,
totalTokens,
totalToolCalls,
},
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index 137af28c761..7de24fe28b0 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -43,6 +43,7 @@ import {
isCompletedRuntimeEnd,
resolveRuntimeEndStatus,
} from './runtimeEndReason';
+import { applyStepMetrics } from './stepMetrics';
// Lazy-loaded to break the import cycle:
// gateway.ts β†’ gatewayEventHandler.ts β†’ executors/index.ts (which pulls in
@@ -1059,12 +1060,9 @@ export const createGatewayEventHandler = (
});
}
- // The server's stepIndex is the authoritative step counter β€” mirror it
- // onto the operation so step-based UI (OpStatusTray) stays correct
- // even across page-refresh reconnects.
- if (typeof event.stepIndex === 'number') {
- get().updateOperationMetadata(operationId, { stepCount: event.stepIndex + 1 });
- }
+ // `stepIndex` is the execution counter; `llmCalls` is the user-facing metric.
+ const update = get().updateOperationMetadata;
+ applyStepMetrics(update, operationId, event.stepIndex, (event.data as any)?.llmCalls);
// Server attaches the canonical UIChatMessage[] snapshot at every
// step boundary (agent-runtime #15152). Use it as Source of Truth
@@ -1236,6 +1234,8 @@ export const createGatewayEventHandler = (
break;
}
+ applyStepMetrics(get().updateOperationMetadata, operationId, undefined, data?.llmCalls);
+
// Refresh on execution_complete to ensure final step state is consistent
if (data?.phase === 'execution_complete') {
enqueue(async () => {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStepMetrics.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStepMetrics.test.ts
new file mode 100644
index 00000000000..5c297cb8e18
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStepMetrics.test.ts
@@ -0,0 +1,45 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import type { ConversationContext } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createGatewayEventHandler } from './gatewayEventHandler';
+
+const context = {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+} as ConversationContext;
+
+const makeEvent = (type: AgentStreamEvent['type'], data?: AgentStreamEvent['data']) =>
+ ({
+ data,
+ id: 'event-1',
+ operationId: 'op-1',
+ stepIndex: 1,
+ timestamp: 0,
+ type,
+ }) as AgentStreamEvent;
+
+const flush = async () => {
+ for (let i = 0; i < 50; i += 1) await Promise.resolve();
+};
+
+describe('gateway step metrics', () => {
+ it('applies the post-step LLM count from step_complete', async () => {
+ const store = {
+ dbMessagesMap: {},
+ operations: {},
+ operationsByContext: {},
+ updateOperationMetadata: vi.fn(),
+ } as any;
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'assistant-1',
+ context,
+ operationId: 'op-1',
+ });
+
+ void handler(makeEvent('step_complete', { llmCalls: 3, phase: 'tool_result' }));
+ await flush();
+
+ expect(store.updateOperationMetadata).toHaveBeenCalledWith('op-1', { llmCalls: 3 });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/stepMetrics.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/stepMetrics.ts
new file mode 100644
index 00000000000..7c9ff98397b
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/stepMetrics.ts
@@ -0,0 +1,33 @@
+/**
+ * Operation-metadata patch for a gateway step event.
+ *
+ * `stepIndex` stays the internal execution counter (`stepCount`); `llmCalls`
+ * is the user-facing metric (actual model calls, retries included) and is
+ * independent of it. Returns `undefined` when the event carries neither.
+ */
+export const resolveStepMetricPatch = (
+ stepIndex: unknown,
+ llmCalls: unknown,
+): Record<string, number> | undefined => {
+ const patch: Record<string, number> = {};
+ if (typeof stepIndex === 'number') patch.stepCount = stepIndex + 1;
+ if (typeof llmCalls === 'number') patch.llmCalls = llmCalls;
+ return Object.keys(patch).length > 0 ? patch : undefined;
+};
+
+type UpdateOperationMetadata = (operationId: string, metadata: Record<string, number>) => void;
+
+/**
+ * Apply whichever metric fields the event carries. `step_start` supplies both;
+ * `step_complete` supplies the post-step `llmCalls` only (with `stepIndex`
+ * omitted), so a single-call run is not stuck at zero until it disappears.
+ */
+export const applyStepMetrics = (
+ update: UpdateOperationMetadata,
+ operationId: string,
+ stepIndex: unknown,
+ llmCalls: unknown,
+): void => {
+ const patch = resolveStepMetricPatch(stepIndex, llmCalls);
+ if (patch) update(operationId, patch);
+};
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index e67cc756621..8abe1d113d8 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -169,6 +169,14 @@ export interface OperationMetadata {
// UI state (for sendMessage operation)
inputEditorTempState?: any | null; // Editor state snapshot for cancel restoration
inputSendErrorMsg?: string; // Error message to display in UI
+ /**
+ * User-facing LLM-call total for the running operation.
+ *
+ * Counts only actual model invocations β€” tool-only runtime iterations do not
+ * increment it. `stepCount` in operation metadata remains the internal
+ * scheduling/execution index.
+ */
+ llmCalls?: number;
// Progress information
progress?: {
current: number;