Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(usage): 显示三套 harness 的回合速度与耗时 (#2161)

Chris Zhang70a6acbdac60
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index b7b5e01598..897c36c50e 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -71,6 +71,38 @@ describe('maker:event hot path ordering', () => {
expect(wireSessionSource.slice(0, broadcastIndex)).not.toContain('handleAgentEvent(sessionMetaForIsland');
});
+ it('tracks Claude wall clock across continuation segments and only consumes it at product completion', () => {
+ const wireSessionSource = extractWireSessionSource();
+
+ expect(wireSessionSource).toContain(
+ "const startedProductTurn = productTurnWallClockTracker.start(session.id);",
+ );
+ expect(wireSessionSource).toContain(
+ 'if (startedProductTurn) productTurnUsageTargetTracker.clear(session.id);',
+ );
+ expect(source).toMatch(
+ /decision\.action === 'resume'[\s\S]*?productTurnWallClockTracker\.preserveForContinuation\(session\.id\);[\s\S]*?await session\.send\(/,
+ );
+ expect(wireSessionSource).toMatch(
+ /event\.source === 'claude-code'\s*&&\s*!isContinuationBoundary\s*&&\s*!isSilentStopDone[\s\S]*?productTurnWallClockTracker\.finish\(session\.id\)/,
+ );
+ expect(wireSessionSource).toContain(
+ 'const claudeTurnDurationMs =\n completedTurnWallClockMs ??',
+ );
+ expect(wireSessionSource.match(/claudeTurnDurationMs,/g)).toHaveLength(3);
+ });
+
+ it('uses the assistant API message id as Vertex output-lag evidence', () => {
+ const wireSessionSource = extractWireSessionSource();
+
+ expect(wireSessionSource).toContain('assistant_message_id?: unknown;');
+ expect(wireSessionSource).toContain(
+ "typeof doneData?.assistant_message_id === 'string'",
+ );
+ expect(wireSessionSource).toContain('? doneData.assistant_message_id');
+ expect(wireSessionSource).toContain('doneData?.is_error !== true');
+ });
+
it('wakes deferred Goal resumes from the shared product-terminal idle boundary', () => {
const wireSessionSource = extractWireSessionSource();
const broadcastIndex = wireSessionSource.indexOf('broadcastToAllWindows(MAKER_PUSH.EVENT');
diff --git a/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts b/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts
index 4edb4edabf..90dcd03c12 100644
--- a/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts
@@ -209,6 +209,66 @@ describe('recordTurnCostOnMessage', () => {
});
});
+ it('较晚到达的 token 明细保留同消息先落下的完整整轮耗时', async () => {
+ const terminal = buildTurnUsageDetails({ turnDurationMs: 6_500 });
+ const { deps, broadcasts, patchCalls } = makeDeps(
+ true,
+ { money: null, costUsd: 0, hasEstimatedValue: false },
+ { turnUsageDetails: terminal },
+ );
+
+ await recordTurnCostOnMessage({ ...ARGS, turnUsageDetails: DETAILS }, deps);
+
+ expect(patchCalls).toHaveLength(2);
+ expect(patchCalls[1]?.patch).toEqual({
+ turnUsageDetails: { ...DETAILS, turnDurationMs: 6_500 },
+ });
+ expect(broadcasts[0]?.turnUsageDetails).toEqual({
+ ...DETAILS,
+ turnDurationMs: 6_500,
+ });
+ });
+
+ it('已有明细无需补耗时时不做冗余二次写入', async () => {
+ const { deps, patchCalls } = makeDeps(
+ true,
+ { money: null, costUsd: 0, hasEstimatedValue: false },
+ { turnUsageDetails: DETAILS },
+ );
+
+ await expect(
+ recordTurnCostOnMessage({ ...ARGS, turnUsageDetails: DETAILS }, deps),
+ ).resolves.toBe(true);
+
+ expect(patchCalls).toHaveLength(1);
+ });
+
+ it('补耗时的二次写入失效时保留第一次成功结果', async () => {
+ const terminal = buildTurnUsageDetails({ turnDurationMs: 6_500 });
+ const { deps, broadcasts, runCostCalls } = makeDeps(
+ true,
+ { money: null, costUsd: 0, hasEstimatedValue: false },
+ { turnUsageDetails: terminal },
+ );
+ let callCount = 0;
+ deps.patchAgentMeta = vi.fn(async (_sessionId, _clientId, patch) => {
+ callCount += 1;
+ if (callCount > 1) return null;
+ return {
+ previous: { turnUsageDetails: terminal },
+ next: { turnUsageDetails: terminal, ...patch },
+ };
+ });
+
+ await expect(
+ recordTurnCostOnMessage({ ...ARGS, turnUsageDetails: DETAILS }, deps),
+ ).resolves.toBe(true);
+
+ expect(callCount).toBe(2);
+ expect(runCostCalls).toHaveLength(1);
+ expect(broadcasts[0]?.turnUsageDetails).toEqual(DETAILS);
+ });
+
it('价格未知时仍可单独持久化并广播 token/cache 明细', async () => {
const { deps, broadcasts, patchCalls } = makeDeps(true);
await expect(recordTurnUsageOnMessage({
@@ -412,6 +472,79 @@ describe('recordTurnUsageOnMessage', () => {
expect(broadcasts).toHaveLength(0);
});
+ it('0 token 终段把完整耗时合并到同消息已有 token 明细', async () => {
+ const terminal = buildTurnUsageDetails({ turnDurationMs: 6_500 });
+ const { deps, broadcasts, patchCalls } = makeDeps(
+ true,
+ { money: null, costUsd: 0, hasEstimatedValue: false },
+ { turnUsageDetails: DETAILS },
+ );
+
+ await expect(
+ recordTurnUsageOnMessage(
+ { sessionId: 's1', clientId: 'm1', turnUsageDetails: terminal },
+ deps,
+ ),
+ ).resolves.toBe(true);
+
+ expect(patchCalls).toHaveLength(2);
+ expect(patchCalls[0]?.patch).toEqual({ turnUsageDetails: terminal });
+ expect(patchCalls[1]?.patch).toEqual({
+ turnUsageDetails: {
+ ...DETAILS,
+ models: ['claude-sonnet-4-6'],
+ turnDurationMs: 6_500,
+ },
+ });
+ expect(broadcasts[0]?.turnUsageDetails).toEqual({
+ ...DETAILS,
+ models: ['claude-sonnet-4-6'],
+ turnDurationMs: 6_500,
+ });
+ });
+
+ it('仅输入/cache 的 continuation 终段保留同消息已有输出与生成耗时', async () => {
+ const previous = buildTurnUsageDetails({
+ inputTokens: 100,
+ outputTokens: 20,
+ cacheReadTokens: 10,
+ durationMs: 1_200,
+ turnDurationMs: 2_000,
+ model: 'claude-sonnet-4-6',
+ }) as TurnUsageDetails;
+ const terminal = buildTurnUsageDetails({
+ inputTokens: 5,
+ cacheReadTokens: 95,
+ turnDurationMs: 6_500,
+ model: 'claude-sonnet-4-6',
+ }) as TurnUsageDetails;
+ const expected = buildTurnUsageDetails({
+ inputTokens: 105,
+ outputTokens: 20,
+ cacheReadTokens: 105,
+ durationMs: 1_200,
+ turnDurationMs: 6_500,
+ model: 'claude-sonnet-4-6',
+ models: ['claude-sonnet-4-6'],
+ });
+ const { deps, broadcasts, patchCalls } = makeDeps(
+ true,
+ { money: null, costUsd: 0, hasEstimatedValue: false },
+ { turnUsageDetails: previous },
+ );
+
+ await expect(
+ recordTurnUsageOnMessage(
+ { sessionId: 's1', clientId: 'm1', turnUsageDetails: terminal },
+ deps,
+ ),
+ ).resolves.toBe(true);
+
+ expect(patchCalls).toHaveLength(2);
+ expect(patchCalls[1]?.patch).toEqual({ turnUsageDetails: expected });
+ expect(broadcasts[0]?.turnUsageDetails).toEqual(expected);
+ });
+
it('sessionId / clientId 缺失 → 直接跳过', async () => {
const { deps, patchCalls } = makeDeps(true);
await expect(
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/turnWallClock.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/turnWallClock.test.ts
new file mode 100644
index 0000000000..96ee885844
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/turnWallClock.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+
+import { ProductTurnUsageTargetTracker, ProductTurnWallClockTracker } from '../turnWallClock';
+
+describe('ProductTurnWallClockTracker', () => {
+ it('keeps continuation gaps inside the final product-turn duration', () => {
+ const tracker = new ProductTurnWallClockTracker();
+ expect(tracker.start('session-1', 1_000)).toBe(true);
+
+ // Temporary idle/running boundaries do not consume or restart the clock.
+ tracker.preserveForContinuation('session-1');
+ expect(tracker.start('session-1', 6_000)).toBe(false);
+ expect(tracker.finish('other-session', 6_000)).toBeUndefined();
+ expect(tracker.finish('session-1', 7_500)).toBe(6_500);
+ });
+
+ it('restarts the clock when the next running boundary is not a continuation', () => {
+ const tracker = new ProductTurnWallClockTracker();
+ expect(tracker.start('session-1', 1_000)).toBe(true);
+ expect(tracker.start('session-1', 6_000)).toBe(true);
+ expect(tracker.finish('session-1', 8_000)).toBe(2_000);
+ });
+
+ it('returns undefined for missing or invalid time boundaries', () => {
+ const tracker = new ProductTurnWallClockTracker();
+ expect(tracker.finish('missing', 2_000)).toBeUndefined();
+
+ tracker.start('reversed', 3_000);
+ expect(tracker.finish('reversed', 2_000)).toBeUndefined();
+
+ tracker.start('invalid', Number.NaN);
+ expect(tracker.finish('invalid', 4_000)).toBeUndefined();
+ });
+
+ it('clears abandoned turns without leaking their start into a later turn', () => {
+ const tracker = new ProductTurnWallClockTracker();
+ tracker.start('session-1', 1_000);
+ tracker.clear('session-1');
+ expect(tracker.finish('session-1', 5_000)).toBeUndefined();
+
+ tracker.start('session-1', 6_000);
+ expect(tracker.finish('session-1', 8_000)).toBe(2_000);
+ });
+});
+
+describe('ProductTurnUsageTargetTracker', () => {
+ it('reuses the latest continuation assistant for a tokenless final segment', () => {
+ const tracker = new ProductTurnUsageTargetTracker();
+ tracker.remember('session-1', 'assistant-1');
+ tracker.remember('session-1', 'assistant-2');
+
+ expect(tracker.finish('session-1', undefined)).toBe('assistant-2');
+ expect(tracker.finish('session-1', undefined)).toBeUndefined();
+ });
+
+ it('prefers a final segment assistant and clears abandoned targets', () => {
+ const tracker = new ProductTurnUsageTargetTracker();
+ tracker.remember('session-1', 'assistant-1');
+ expect(tracker.finish('session-1', 'assistant-final')).toBe('assistant-final');
+
+ tracker.remember('session-1', 'stale-assistant');
+ tracker.clear('session-1');
+ expect(tracker.finish('session-1', undefined)).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 2bba2acbc4..3e3897327e 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -395,8 +395,8 @@ import {
setModelPriceOverride,
} from '../usage/modelPriceOverrideStore.js';
import {
+ ClaudeOutputLagTimingGuard,
computeModelUsageDeltas,
- detectOutputLag,
type ModelUsageCumulative,
type ModelUsageDeltaEntry,
} from '../usage/modelUsageDelta.js';
@@ -693,6 +693,10 @@ import {
isTerminalTurnErrorEvent,
SessionTurnActivityTracker,
} from './sessionTurnActivityTracker.js';
+import {
+ ProductTurnUsageTargetTracker,
+ ProductTurnWallClockTracker,
+} from './turnWallClock.js';
import { resolveClearSessionBoundary } from './clearSessionBoundary.js';
import {
captureDataOwnerBroadcastScope,
@@ -2380,6 +2384,9 @@ let pendingAgentSwitchApplyHolder:
let cancelPendingAgentSwitchHolder: ((sessionId: string) => void) | null = null;
let gitSnapshotCoordinator: GitSnapshotCoordinator | null = null;
const sessionTurnActivityTracker = new SessionTurnActivityTracker();
+const productTurnWallClockTracker = new ProductTurnWallClockTracker();
+const productTurnUsageTargetTracker = new ProductTurnUsageTargetTracker();
+const claudeOutputLagTimingGuard = new ClaudeOutputLagTimingGuard();
/**
* Own the session input boundary while rewind stops an active turn and changes
@@ -3161,6 +3168,8 @@ function settleSilentStopDone(
reason: 'exhausted' | 'skip' | 'send-failed',
): void {
void finalizeTurnChangeSet(sessionId, null, 'complete');
+ productTurnWallClockTracker.clear(sessionId);
+ productTurnUsageTargetTracker.clear(sessionId);
sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(sessionId);
noteClaudeSessionTurnState(sessionId, false);
agentInputCoordinatorHolder?.onTurnEvent(sessionId, 'done');
@@ -3220,6 +3229,9 @@ async function handleSilentStopTurnEnd(
const decision = silentStopAutoResumeGuard.onSilentStop(session.id, doneAt);
if (decision.action === 'resume') {
try {
+ // The next Claude running boundary belongs to the same user-visible turn.
+ // Mark it before send(), which may synchronously emit status events.
+ productTurnWallClockTracker.preserveForContinuation(session.id);
const clientId = randomUUID();
const sendResult = await session.send(
{ type: 'user', content: SILENT_STOP_RESUME_PROMPT },
@@ -3418,6 +3430,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
let pendingCodexAccountUsageSnapshot: unknown | null = null;
let shouldMarkTurnStatusIdleAfterBroadcast = false;
let shouldMarkTurnTerminalIdleAfterBroadcast = false;
+ let completedTurnWallClockMs: number | undefined;
const isContinuationBoundary = isTurnContinuationBoundaryEvent(event);
// 探针:continuation 边界命中会跳过 status idle / ended 写 / tracker idle,
// 若 claim 悬挂会导致 UI 永久「正在生成」。区分「claim 悬挂」与「done 未到达」。
@@ -3454,6 +3467,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
clearPending: typeof event.turnAttemptToken === 'number',
});
const wasInTurn = sessionTurnActivityTracker.isSessionInTurn(session.id);
+ if (!wasInTurn && event.source === 'claude-code') {
+ const startedProductTurn = productTurnWallClockTracker.start(session.id);
+ if (startedProductTurn) productTurnUsageTargetTracker.clear(session.id);
+ }
sessionTurnActivityTracker.setSessionInTurn(session.id, data.isRunning);
if (!wasInTurn) advanceSessionTurnBoundaryGeneration(session.id);
// 后台活动检测:turn 开始 → 该会话的 API 流量回归主线,后台横幅熄灭。
@@ -3500,6 +3517,13 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
const rawTurn = (event.data as { raw?: { id?: unknown; status?: unknown } } | null)?.raw;
const isSilentStopDone =
(event.data as { silentStop?: boolean } | null | undefined)?.silentStop === true;
+ if (
+ event.source === 'claude-code' &&
+ !isContinuationBoundary &&
+ !isSilentStopDone
+ ) {
+ completedTurnWallClockMs = productTurnWallClockTracker.finish(session.id);
+ }
if (!isContinuationBoundary && !isSilentStopDone) {
shouldMarkTurnTerminalIdleAfterBroadcast = true;
}
@@ -3758,6 +3782,16 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
}
pendingFailedTurnAssistantPersistId.delete(session.id);
}
+ if (event.type === 'done' && event.source === 'claude-code') {
+ if (isContinuationBoundary) {
+ productTurnUsageTargetTracker.remember(session.id, turnAssistantPersistId);
+ } else {
+ turnAssistantPersistId = productTurnUsageTargetTracker.finish(
+ session.id,
+ turnAssistantPersistId,
+ );
+ }
+ }
flushOrphanToolResults(session.id, eventAgentMeta);
if (turnBoundaryAssistantPersistId) {
// 在同一 durable FIFO 内先盖 turn seal、再复用 local-db:messages:created 广播
@@ -3928,6 +3962,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
const doneData = event.data as
| {
total_cost_usd?: unknown;
+ duration_ms?: unknown;
+ duration_api_ms?: unknown;
usage?: {
input_tokens?: number;
output_tokens?: number;
@@ -3935,10 +3971,15 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
cache_creation_input_tokens?: number;
};
modelUsage?: Record<string, unknown>;
+ assistant_message_id?: unknown;
+ is_error?: unknown;
}
| undefined;
const cumulative = doneData?.total_cost_usd;
const modelUsage = doneData?.modelUsage;
+ const claudeTurnDurationMs =
+ completedTurnWallClockMs ??
+ (typeof doneData?.duration_ms === 'number' ? doneData.duration_ms : undefined);
let modelUsageDeltas: ModelUsageDeltaEntry[] | undefined;
if (modelUsage && typeof modelUsage === 'object') {
const { next, deltas } = computeModelUsageDeltas(
@@ -3948,6 +3989,20 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
lastReportedModelUsageBySession.set(session.id, next);
modelUsageDeltas = deltas;
}
+ const outputLagTiming = claudeOutputLagTimingGuard.evaluate(
+ session.id,
+ modelUsageDeltas ?? [],
+ !isContinuationBoundary,
+ typeof doneData?.assistant_message_id === 'string'
+ ? doneData.assistant_message_id
+ : undefined,
+ doneData?.is_error !== true,
+ );
+ const claudeGenerationDurationMs = outputLagTiming.suppressTiming
+ ? undefined
+ : typeof doneData?.duration_api_ms === 'number'
+ ? doneData.duration_api_ms
+ : undefined;
// total_cost_usd 累计基线: 主路径不靠它算钱, 但仍跟住, 以便万一某轮缺 modelUsage
// 走兜底时累计差才准。先取"更新前"基线给兜底用, 再写入本轮累计。
const prevReportedCost = lastReportedCostUsdBySession.get(session.id) ?? 0;
@@ -3958,7 +4013,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 判定主线被上游静默替换(如 fable-5 高负载被路由到 opus-4-8),把标记挂到本轮
// 收尾 assistant 的 agent_meta 上(AssistantMessage 渲染降级提示行)。
// fire-and-forget,与记账 sink 互不阻塞;判定纯函数见 shared/modelMismatch.ts。
- if (modelUsageDeltas && detectOutputLag(modelUsageDeltas)) {
+ if (modelUsageDeltas && outputLagTiming.detected) {
// 上游在 done 时点还没结算本轮输出(实测 Vertex),这一轮的费用会偏低、下一轮偏高。
// 总量不丢,只是归属错位;不做纠正的理由见 usage/modelUsageDelta 文件头。
log.warn(
@@ -4079,6 +4134,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
deltas,
'unknown',
perModel,
+ claudeGenerationDurationMs,
+ claudeTurnDurationMs,
);
recordTurnSpend(turnMoney);
recordSessionTurnSpend(session.id, turnMoney);
@@ -4130,6 +4187,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
deltas,
'unknown',
perModel,
+ claudeGenerationDurationMs,
+ claudeTurnDurationMs,
);
if (turnEstimatedValue && turnEstimatedValue.amount > 0) {
const changedScheduleId = await recordSchedulerTurnCost({
@@ -4167,6 +4226,9 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
doneData?.usage,
undefined,
resolvedModel,
+ undefined,
+ claudeGenerationDurationMs,
+ claudeTurnDurationMs,
);
// 本分支有三个"记不了钱"的出口(本轮 cost 未增长 / 订阅直连 / 订阅与网关路由),
// 账本口径一个字不改,但都把本轮 token 明细落下来 —— 钱算不出来不代表用量
@@ -4269,6 +4331,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
completionTokens?: number;
reasoningTokens?: number;
cachedTokens?: number;
+ durationMs?: number;
+ turnDurationMs?: number;
};
const promptTokens = Number(u.promptTokens) || 0;
const completionTokens = Number(u.completionTokens) || 0;
@@ -4355,6 +4419,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
cacheReadTokens: cachedTokens,
cacheCreateTokens: 0,
model: turnModel,
+ durationMs: u.durationMs,
+ turnDurationMs: u.turnDurationMs,
});
const recordCodexUsageOnly = async () => {
if (!turnAssistantPersistId) return;
@@ -4507,6 +4573,14 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
const turnUsageDetails = buildTurnUsageDetails({
...tokens,
model: turnModel,
+ durationMs:
+ typeof (rawUsage as { durationMs?: unknown }).durationMs === 'number'
+ ? (rawUsage as { durationMs: number }).durationMs
+ : undefined,
+ turnDurationMs:
+ typeof (rawUsage as { turnDurationMs?: unknown }).turnDurationMs === 'number'
+ ? (rawUsage as { turnDurationMs: number }).turnDurationMs
+ : undefined,
});
// Pi 也必须进 daily_model_usage,否则首页仪表盘会把 Pi 的
@@ -4653,6 +4727,9 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
lastReportedCostUsdBySession.delete(session.id);
lastReportedModelUsageBySession.delete(session.id);
turnModelPromiseBySession.delete(session.id);
+ productTurnWallClockTracker.clear(session.id);
+ productTurnUsageTargetTracker.clear(session.id);
+ claudeOutputLagTimingGuard.clear(session.id);
// 后台活动检测:会话进程已关闭(closeSession / 删除),清账并广播横幅熄灭。
clearClaudeSessionBackgroundActivity(session.id);
clearSessionPersistState(session.id);
diff --git a/apps/desktop/src/main/maker-ipc/turnWallClock.ts b/apps/desktop/src/main/maker-ipc/turnWallClock.ts
new file mode 100644
index 0000000000..01073344d9
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/turnWallClock.ts
@@ -0,0 +1,71 @@
+/**
+ * Tracks the wall-clock duration of one user-visible product turn.
+ *
+ * A Claude answer may span multiple SDK segments. The tracker therefore starts
+ * at the first running boundary and is only consumed by the final product
+ * terminal, so continuation gaps remain part of the displayed elapsed time.
+ */
+export class ProductTurnWallClockTracker {
+ private readonly startedAtBySession = new Map<string, number>();
+ private readonly continuationPendingBySession = new Set<string>();
+
+ preserveForContinuation(sessionId: string): void {
+ if (this.startedAtBySession.has(sessionId)) {
+ this.continuationPendingBySession.add(sessionId);
+ }
+ }
+
+ start(sessionId: string, startedAt = Date.now()): boolean {
+ if (!Number.isFinite(startedAt)) {
+ this.clear(sessionId);
+ return false;
+ }
+ // Only a confirmed Claude silentStop auto-resume may reuse the existing
+ // product boundary. Any other running boundary starts a genuinely new turn
+ // and overwrites stale state left by an abnormal terminal path.
+ if (
+ this.continuationPendingBySession.delete(sessionId) &&
+ this.startedAtBySession.has(sessionId)
+ ) {
+ return false;
+ }
+ this.startedAtBySession.set(sessionId, startedAt);
+ return true;
+ }
+
+ finish(sessionId: string, completedAt = Date.now()): number | undefined {
+ const startedAt = this.startedAtBySession.get(sessionId);
+ this.clear(sessionId);
+ if (startedAt === undefined || !Number.isFinite(completedAt)) return undefined;
+ const durationMs = completedAt - startedAt;
+ return durationMs > 0 && Number.isFinite(durationMs) ? durationMs : undefined;
+ }
+
+ clear(sessionId: string): void {
+ this.startedAtBySession.delete(sessionId);
+ this.continuationPendingBySession.delete(sessionId);
+ }
+}
+
+/**
+ * Keeps the latest assistant message target across Claude continuation SDK
+ * segments. A tokenless final segment can then attach the complete product-turn
+ * duration to the last message that actually carried output.
+ */
+export class ProductTurnUsageTargetTracker {
+ private readonly clientIdBySession = new Map<string, string>();
+
+ remember(sessionId: string, clientId: string | null | undefined): void {
+ if (clientId) this.clientIdBySession.set(sessionId, clientId);
+ }
+
+ finish(sessionId: string, currentClientId: string | null | undefined): string | undefined {
+ const rememberedClientId = this.clientIdBySession.get(sessionId);
+ this.clientIdBySession.delete(sessionId);
+ return currentClientId || rememberedClientId;
+ }
+
+ clear(sessionId: string): void {
+ this.clientIdBySession.delete(sessionId);
+ }
+}
diff --git a/apps/desktop/src/main/turnCostBroadcaster.ts b/apps/desktop/src/main/turnCostBroadcaster.ts
index dc8ff10fed..7d42ab0ca8 100644
--- a/apps/desktop/src/main/turnCostBroadcaster.ts
+++ b/apps/desktop/src/main/turnCostBroadcaster.ts
@@ -24,7 +24,11 @@ import { BrowserWindow } from 'electron';
import type { SendOrigin } from '@cindy/maker-core';
import type { MessageTurnCostPayload } from '../shared/turnCostPayload.js';
-import type { TurnUsageDetails } from '../shared/turnUsageDetails.js';
+import {
+ mergeTurnUsageDetailsForMessage,
+ normalizeTurnUsageDetails,
+ type TurnUsageDetails,
+} from '../shared/turnUsageDetails.js';
import {
patchMessageAgentMetaWithResult,
readPriorUserRoundCost,
@@ -121,6 +125,41 @@ const defaultDeps: TurnCostDeps = {
},
};
+async function patchAgentMetaPreservingTurnDuration(
+ deps: Pick<TurnCostDeps, 'patchAgentMeta'>,
+ sessionId: string,
+ clientId: string,
+ patch: Record<string, unknown>,
+ turnUsageDetails: TurnUsageDetails | null | undefined,
+): Promise<{
+ result: MessageAgentMetaPatchResult;
+ turnUsageDetails: TurnUsageDetails | null | undefined;
+} | null> {
+ const first = await deps.patchAgentMeta(sessionId, clientId, patch);
+ if (!first) return null;
+ if (!turnUsageDetails) return { result: first, turnUsageDetails };
+
+ const previousUsage = normalizeTurnUsageDetails(first.previous.turnUsageDetails);
+ if (!previousUsage) return { result: first, turnUsageDetails };
+ const mergedUsage = mergeTurnUsageDetailsForMessage(previousUsage, turnUsageDetails);
+ const needsMergePatch =
+ (turnUsageDetails.totalTokens <= 0 && previousUsage.totalTokens > 0) ||
+ (turnUsageDetails.outputTokens <= 0 && previousUsage.outputTokens > 0) ||
+ (previousUsage.turnDurationMs ?? 0) > (turnUsageDetails.turnDurationMs ?? 0);
+ if (!needsMergePatch) return { result: first, turnUsageDetails };
+ const second = await deps.patchAgentMeta(sessionId, clientId, {
+ turnUsageDetails: mergedUsage,
+ });
+ // The first patch already persisted the segment cost/usage. If the message
+ // is rewound between the two writes, keep the original success semantics so
+ // ledger side effects and broadcasts are not silently skipped.
+ if (!second) return { result: first, turnUsageDetails };
+ return {
+ result: { previous: first.previous, next: second.next },
+ turnUsageDetails: mergedUsage,
+ };
+}
+
/**
* 把一笔 SDK 分段费用写到指定消息,并同时写入从本轮用户消息累计的展示费用。
*
@@ -146,6 +185,7 @@ export async function recordTurnCostOnMessage(
try {
let userTurnMoney = normalized;
let userTurnCostIsEstimate = normalized.kind === 'value-estimate';
+ let persistedTurnUsageDetails = turnUsageDetails;
const patched = await deps.enqueue(`turn-cost:${sessionId}:${clientId}`, async () => {
// This runs in the durable FIFO after prior assistant cost patches, so
// the query sees every earlier segment of this user round.
@@ -178,8 +218,16 @@ export async function recordTurnCostOnMessage(
patch.origin = turnOrigin;
}
if (turnUsageDetails) patch.turnUsageDetails = turnUsageDetails;
- const result = await deps.patchAgentMeta(sessionId, clientId, patch);
- if (!result) return null;
+ const patchedMeta = await patchAgentMetaPreservingTurnDuration(
+ deps,
+ sessionId,
+ clientId,
+ patch,
+ turnUsageDetails,
+ );
+ if (!patchedMeta) return null;
+ const { result } = patchedMeta;
+ persistedTurnUsageDetails = patchedMeta.turnUsageDetails;
try {
await deps.applyScheduleRunCostChange(result.previous, result.next);
} catch (err) {
@@ -203,7 +251,7 @@ export async function recordTurnCostOnMessage(
userTurnMoney,
...(userTurnMoney.currency === 'USD' ? { userTurnCostUsd: userTurnMoney.amount } : {}),
userTurnCostIsEstimate,
- ...(turnUsageDetails ? { turnUsageDetails } : {}),
+ ...(persistedTurnUsageDetails ? { turnUsageDetails: persistedTurnUsageDetails } : {}),
};
try {
if (deps.broadcastWithOwnerScope) {
@@ -249,7 +297,8 @@ export type TurnUsageDeps = Pick<
* —— 而 readPriorUserRoundCost 的契约本来就是「让收尾消息承载整轮总额」。所以这里读一次
* 往轮累计,有则连同 userTurnCost 一起投影到消息与 payload(仍不含当前无价 segment)。
*
- * turnUsageDetails 为空(整轮 0 token)时直接跳过:没有可展示的事实,不写空对象。
+ * turnUsageDetails 为空时直接跳过。0 token 的最终 continuation 仍可携带整轮耗时,
+ * 并与该消息先前已落下的 token 明细合并。
*/
export async function recordTurnUsageOnMessage(
args: {
@@ -263,6 +312,7 @@ export async function recordTurnUsageOnMessage(
if (!sessionId || !clientId || !turnUsageDetails) return false;
const ownerScope = captureOwnerScope();
try {
+ let persistedTurnUsageDetails = turnUsageDetails;
const outcome = await deps.enqueue(`turn-usage:${sessionId}:${clientId}`, async () => {
// 与 recordTurnCostOnMessage 同一条 durable FIFO,所以这里看得到本用户轮此前
// 每个 segment 已落库的费用。
@@ -277,8 +327,15 @@ export async function recordTurnUsageOnMessage(
patch.userTurnCostUsd = userTurnMoney.amount;
}
}
- const patched = await deps.patchAgentMeta(sessionId, clientId, patch);
- if (!patched) return null;
+ const patchedMeta = await patchAgentMetaPreservingTurnDuration(
+ deps,
+ sessionId,
+ clientId,
+ patch,
+ turnUsageDetails,
+ );
+ if (!patchedMeta) return null;
+ persistedTurnUsageDetails = patchedMeta.turnUsageDetails ?? turnUsageDetails;
return { userTurnMoney, userTurnCostIsEstimate: prior.hasEstimatedValue };
});
if (!outcome) return false;
@@ -290,7 +347,7 @@ export async function recordTurnUsageOnMessage(
const payload: MessageTurnCostPayload = {
sessionId,
clientId,
- turnUsageDetails,
+ turnUsageDetails: persistedTurnUsageDetails,
...(userTurnMoney
? {
userTurnMoney,
diff --git a/apps/desktop/src/main/usage/__tests__/modelUsageDelta.test.ts b/apps/desktop/src/main/usage/__tests__/modelUsageDelta.test.ts
index b1f3d85c93..4b554a89bb 100644
--- a/apps/desktop/src/main/usage/__tests__/modelUsageDelta.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelUsageDelta.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { computeModelUsageDeltas, type ModelUsageCumulative } from '../modelUsageDelta';
+import {
+ ClaudeOutputLagTimingGuard,
+ computeModelUsageDeltas,
+ type ModelUsageCumulative,
+ type ModelUsageDeltaEntry,
+} from '../modelUsageDelta';
function snap(over: Partial<ModelUsageCumulative> = {}): ModelUsageCumulative {
return {
@@ -108,3 +113,77 @@ describe('computeModelUsageDeltas', () => {
expect(deltas).toEqual([]);
});
});
+
+describe('ClaudeOutputLagTimingGuard', () => {
+ const lagged: ModelUsageDeltaEntry[] = [
+ {
+ model: 'claude-opus-4-8',
+ costUsdDelta: 0,
+ inputTokensDelta: 100,
+ outputTokensDelta: 7,
+ cacheReadTokensDelta: 20_000,
+ cacheCreateTokensDelta: 0,
+ },
+ ];
+ const settled: ModelUsageDeltaEntry[] = [
+ {
+ model: 'claude-opus-4-8',
+ costUsdDelta: 0,
+ inputTokensDelta: 100,
+ outputTokensDelta: 3_200,
+ cacheReadTokensDelta: 20_000,
+ cacheCreateTokensDelta: 0,
+ },
+ ];
+
+ it('suppresses the detected turn and the following backfill turn only', () => {
+ const guard = new ClaudeOutputLagTimingGuard();
+ expect(guard.evaluate('session-1', lagged, true, 'msg_vrtx_1')).toEqual({
+ detected: true,
+ suppressTiming: true,
+ });
+ expect(guard.evaluate('session-1', settled, true)).toEqual({
+ detected: false,
+ suppressTiming: true,
+ });
+ expect(guard.evaluate('session-1', settled, true)).toEqual({
+ detected: false,
+ suppressTiming: false,
+ });
+ });
+
+ it('keeps a lagged continuation product turn suppressed through its final segment', () => {
+ const guard = new ClaudeOutputLagTimingGuard();
+ expect(guard.evaluate('session-1', lagged, false, 'msg_vrtx_1').suppressTiming).toBe(true);
+ expect(guard.evaluate('session-1', settled, true).suppressTiming).toBe(true);
+ expect(guard.evaluate('session-1', settled, true).suppressTiming).toBe(true);
+ expect(guard.evaluate('session-1', settled, true).suppressTiming).toBe(false);
+ });
+
+ it('clears pending suppression per session', () => {
+ const guard = new ClaudeOutputLagTimingGuard();
+ guard.evaluate('session-1', lagged, true, 'msg_vrtx_1');
+ guard.clear('session-1');
+ expect(guard.evaluate('session-1', settled, true).suppressTiming).toBe(false);
+ });
+
+ it('does not suppress a legitimate short reply without Vertex evidence', () => {
+ const guard = new ClaudeOutputLagTimingGuard();
+ expect(guard.evaluate('session-1', lagged, true)).toEqual({
+ detected: false,
+ suppressTiming: false,
+ });
+ });
+
+ it('does not arm next-turn suppression from a failed Vertex turn', () => {
+ const guard = new ClaudeOutputLagTimingGuard();
+ expect(guard.evaluate('session-1', lagged, true, 'msg_vrtx_1', false)).toEqual({
+ detected: false,
+ suppressTiming: false,
+ });
+ expect(guard.evaluate('session-1', settled, true)).toEqual({
+ detected: false,
+ suppressTiming: false,
+ });
+ });
+});
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
index bb568b3f9e..aedda1c1db 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
@@ -931,4 +931,16 @@ describe('subscription value and usage details', () => {
{ model: 'claude-haiku-4-5', money: usdMoney(0.8) },
]);
});
+
+ it('keeps generation and full-turn durations separate', () => {
+ const details = buildClaudeTurnUsageDetails(
+ { input_tokens: 10, output_tokens: 25 },
+ undefined,
+ 'claude-opus-4-8',
+ undefined,
+ 1_250,
+ 8_500,
+ );
+ expect(details).toMatchObject({ durationMs: 1_250, turnDurationMs: 8_500 });
+ });
});
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCurrencyTrust.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCurrencyTrust.test.ts
index 21efe297be..a521f41563 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostCurrencyTrust.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCurrencyTrust.test.ts
@@ -138,7 +138,10 @@ describe('output lag detection', () => {
// 实测形态:40 万 token 的上下文写进 cache,output 只报 7 —— 真实的长回复被上游
// 结算延后到了下一轮。
expect(
- detectOutputLag([delta({ inputTokensDelta: 131, cacheCreateTokensDelta: 404_534, outputTokensDelta: 7 })]),
+ detectOutputLag(
+ [delta({ inputTokensDelta: 131, cacheCreateTokensDelta: 404_534, outputTokensDelta: 7 })],
+ 'msg_vrtx_1',
+ ),
).toBe(true);
});
@@ -151,4 +154,10 @@ describe('output lag detection', () => {
it('does not flag a genuinely tiny turn', () => {
expect(detectOutputLag([delta({ inputTokensDelta: 120, outputTokensDelta: 4 })])).toBe(false);
});
+
+ it('does not flag a concise high-context reply without Vertex evidence', () => {
+ expect(
+ detectOutputLag([delta({ cacheReadTokensDelta: 404_771, outputTokensDelta: 7 })]),
+ ).toBe(false);
+ });
});
diff --git a/apps/desktop/src/main/usage/modelUsageDelta.ts b/apps/desktop/src/main/usage/modelUsageDelta.ts
index 7e1462aad1..34e3745b86 100644
--- a/apps/desktop/src/main/usage/modelUsageDelta.ts
+++ b/apps/desktop/src/main/usage/modelUsageDelta.ts
@@ -19,7 +19,7 @@
*
* 这里不做纠正: 把 output 挪到别处需要知道"本轮真实输出是多少", 而两个可用数据源都
* 还没结算; 猜一个值会把"归属错位"升级成"金额算错"。detectOutputLag 只把可疑轮次标出
- * 来供日志定位, 不参与任何计费。
+ * 来供日志定位与 TPS 可靠性门禁,不参与任何计费或 token 纠正。
*
* 纯函数、零 Electron 依赖 — 可直接单测。
*/
@@ -129,9 +129,15 @@ export function computeModelUsageDeltas(
* 报回来的 output 却只有个位到几十 —— 真实回复不可能这么短。阈值取得很松,只求把
* "长回复被记成 7 个 token" 这种量级的异常捞出来,不追求精确。
*
- * 纯诊断:调用方只应拿它打日志。不参与计费,也不改任何金额。
+ * 只判异常:调用方可据此打日志或隐藏不可靠 TPS,但不得改计费、token 或金额。
*/
-export function detectOutputLag(deltas: readonly ModelUsageDeltaEntry[]): boolean {
+export function detectOutputLag(
+ deltas: readonly ModelUsageDeltaEntry[],
+ requestId?: string,
+): boolean {
+ // A concise high-context reply is legitimate. Only the known Vertex request
+ // family is evidence that this shape means deferred output settlement.
+ if (!requestId?.startsWith('msg_vrtx_')) return false;
const OUTPUT_FLOOR = 64;
const INPUT_SIGNIFICANT = 10_000;
return deltas.some((delta) => {
@@ -140,3 +146,44 @@ export function detectOutputLag(deltas: readonly ModelUsageDeltaEntry[]): boolea
return inputSide >= INPUT_SIGNIFICANT && delta.outputTokensDelta < OUTPUT_FLOOR;
});
}
+
+/**
+ * Suppresses generation timing for both the turn where output settlement is
+ * visibly late and the following turn where the missing output is expected to
+ * be backfilled. Token/cost accounting remains untouched.
+ */
+export class ClaudeOutputLagTimingGuard {
+ private readonly suppressCurrentTurnBySession = new Set<string>();
+ private readonly detectedInCurrentTurnBySession = new Set<string>();
+
+ evaluate(
+ sessionId: string,
+ deltas: readonly ModelUsageDeltaEntry[],
+ isProductTurnFinal: boolean,
+ requestId?: string,
+ allowDetection = true,
+ ): { detected: boolean; suppressTiming: boolean } {
+ const detected = allowDetection && detectOutputLag(deltas, requestId);
+ if (detected) this.detectedInCurrentTurnBySession.add(sessionId);
+ const suppressTiming =
+ this.suppressCurrentTurnBySession.has(sessionId) ||
+ this.detectedInCurrentTurnBySession.has(sessionId);
+ if (isProductTurnFinal) {
+ if (this.detectedInCurrentTurnBySession.has(sessionId)) {
+ this.suppressCurrentTurnBySession.add(sessionId);
+ } else {
+ this.suppressCurrentTurnBySession.delete(sessionId);
+ }
+ this.detectedInCurrentTurnBySession.delete(sessionId);
+ }
+ return {
+ detected,
+ suppressTiming,
+ };
+ }
+
+ clear(sessionId: string): void {
+ this.suppressCurrentTurnBySession.delete(sessionId);
+ this.detectedInCurrentTurnBySession.delete(sessionId);
+ }
+}
diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.ts
index 146fa609b7..28c9c1c91c 100644
--- a/apps/desktop/src/main/usage/turnCostCalculator.ts
+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts
@@ -359,6 +359,8 @@ export function buildClaudeTurnUsageDetails(
deltas: ModelUsageDeltaEntry[] | undefined,
fallbackModel: string,
perModel?: ResolvedModelCost[],
+ durationMs?: number,
+ turnDurationMs?: number,
): TurnUsageDetails | null {
const hasModelUsageDeltas = Boolean(deltas && deltas.length > 0);
const perModelCost = perModel
@@ -380,5 +382,7 @@ export function buildClaudeTurnUsageDetails(
model: deltas?.length === 1 ? deltas[0].model : hasModelUsageDeltas ? undefined : fallbackModel,
models: hasModelUsageDeltas ? deltas?.map((delta) => delta.model) : undefined,
perModelCost: perModelCost && perModelCost.length > 0 ? perModelCost : undefined,
+ durationMs,
+ turnDurationMs,
});
}
diff --git a/apps/desktop/src/renderer/__tests__/usagePerformanceI18n.test.ts b/apps/desktop/src/renderer/__tests__/usagePerformanceI18n.test.ts
new file mode 100644
index 0000000000..d02ce425be
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/usagePerformanceI18n.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import en from '../i18n/locales/en/common.json';
+import ja from '../i18n/locales/ja/common.json';
+import ko from '../i18n/locales/ko/common.json';
+import zhCN from '../i18n/locales/zh-CN/common.json';
+
+const KEYS = ['timeAndRateValue', 'performanceLine', 'performanceRateLine'] as const;
+
+describe('usage performance units', () => {
+ it('keeps TPS in English templates', () => {
+ const values = [
+ en.quotaCard.timeAndRateValue,
+ en.usageDetails.performanceLine,
+ en.usageDetails.performanceRateLine,
+ ];
+ for (const value of values) expect(value).toContain('TPS');
+ });
+
+ it.each([
+ ['zh-CN', zhCN, 'token/秒'],
+ ['ja', ja, 'トークン/秒'],
+ ['ko', ko, '토큰/초'],
+ ] as const)('uses a localized token-per-second unit in %s', (_locale, messages, unit) => {
+ const values = [
+ messages.quotaCard[KEYS[0]],
+ messages.usageDetails[KEYS[1]],
+ messages.usageDetails[KEYS[2]],
+ ];
+ for (const value of values) {
+ expect(value).toContain(unit);
+ expect(value).not.toContain('TPS');
+ }
+ });
+});
diff --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
index 55ae9b174d..de672456e3 100644
--- a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
@@ -23,6 +23,8 @@ export interface QuotaHoverCardTurnUsage {
totalTokensText?: string | null;
inputTokensText?: string | null;
outputTokensText?: string | null;
+ outputRateText?: string | null;
+ turnDurationText?: string | null;
cacheLineText?: string | null;
model?: string | null;
perModelCost?: ReadonlyArray<{
@@ -322,6 +324,26 @@ function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage
</div>
) : null}
+ {turnUsage.turnDurationText != null ? (
+ <div
+ data-testid="quota-performance"
+ className="mt-[5px] flex items-baseline justify-between gap-3 tabular-nums"
+ >
+ <span className="text-[var(--text-secondary)]">{t('quotaCard.timeLabel')}</span>
+ <span
+ data-testid="quota-performance-value"
+ className="ml-auto text-right font-medium text-[var(--text-primary)]"
+ >
+ {turnUsage.outputRateText != null
+ ? t('quotaCard.timeAndRateValue', {
+ duration: turnUsage.turnDurationText,
+ rate: turnUsage.outputRateText,
+ })
+ : turnUsage.turnDurationText}
+ </span>
+ </div>
+ ) : null}
+
{!showModelCostBreakdown && turnUsage.model != null ? (
<div className="mt-[5px] flex items-baseline justify-between gap-3">
<span className="text-[var(--text-secondary)]">{t('quotaCard.modelLabel')}</span>
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 460c6bc47a..832ffb39df 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -90,6 +90,8 @@ import { useXaiRateLimit, type XaiRateLimitSnapshot } from '@/hooks/useXaiRateLi
import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
import {
buildTurnUsageTooltipLines,
+ formatOutputTokenRate,
+ formatTurnDuration,
getTurnUsageSuggestion,
} from '@/lib/turnUsageTooltip';
import { aggregateAssistantTurnUsageDetails } from '@/lib/userTurnUsage';
@@ -743,6 +745,11 @@ function toQuotaHoverCardTurnUsage(
totalTokensText: formatCompactTokens(Math.max(0, Math.floor(details.totalTokens))),
inputTokensText: formatCompactTokens(details.inputTokens),
outputTokensText: formatCompactTokens(details.outputTokens),
+ outputRateText: formatOutputTokenRate(details),
+ turnDurationText:
+ typeof details.turnDurationMs === 'number'
+ ? formatTurnDuration(details.turnDurationMs, t)
+ : null,
cacheLineText: formatQuotaCacheLine(details, t),
model: quotaTurnModel(details, t),
...(details.perModelCost
diff --git a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
index 0bf6716137..b6c343d59e 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { fireEvent, render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { ClaudeSubscriptionUsageSnapshot } from '../../../../shared/claudeSubscriptionUsage';
@@ -23,6 +23,8 @@ vi.mock('react-i18next', () => ({
if (key === 'quotaCard.tokenBreakdown') {
return `(输入 ${options.input} · 输出 ${options.output})`;
}
+ if (key === 'quotaCard.timeLabel') return '耗时';
+ if (key === 'quotaCard.timeAndRateValue') return `${options.duration} 速度:${options.rate} token/秒`;
if (key === 'todaySpend.sessionCostLabel') return `本任务 ${options.cost}`;
if (key === 'todaySpend.tooltip.sessionUsed') return `本任务已用 ${options.cost}`;
if (key === 'todaySpend.codex.sessionValueLabel') return `本任务价值 ${options.cost}`;
@@ -353,6 +355,54 @@ describe('QuotaHoverCard', () => {
expect(screen.getByText('本任务价值 $0.50')).toBeTruthy();
});
+ it('订阅卡用固定耗时标题和右对齐组合值,缺速度时结构保持不变', () => {
+ const { rerender } = render(
+ <QuotaHoverCard
+ snapshot={makeSnapshot()}
+ nowMs={NOW_MS}
+ turnUsage={{ outputRateText: '40', turnDurationText: '12.3s' }}
+ />,
+ );
+
+ const performance = screen.getByTestId('quota-performance');
+ expect(within(performance).getByText('耗时')).toBeTruthy();
+ const combinedValue = within(performance).getByTestId('quota-performance-value');
+ expect(combinedValue.textContent).toBe('12.3s 速度:40 token/秒');
+ expect(combinedValue.classList.contains('ml-auto')).toBe(true);
+ expect(combinedValue.classList.contains('text-right')).toBe(true);
+
+ rerender(
+ <QuotaHoverCard
+ snapshot={makeSnapshot()}
+ nowMs={NOW_MS}
+ turnUsage={{ outputRateText: null, turnDurationText: '12.3s' }}
+ />,
+ );
+ const timeOnlyPerformance = screen.getByTestId('quota-performance');
+ expect(within(timeOnlyPerformance).getByText('耗时')).toBeTruthy();
+ const timeOnlyValue = within(timeOnlyPerformance).getByTestId('quota-performance-value');
+ expect(timeOnlyValue.textContent).toBe('12.3s');
+ expect(timeOnlyValue.classList.contains('ml-auto')).toBe(true);
+
+ rerender(
+ <QuotaHoverCard
+ snapshot={makeSnapshot()}
+ nowMs={NOW_MS}
+ turnUsage={{ outputRateText: '40', turnDurationText: null }}
+ />,
+ );
+ expect(screen.queryByTestId('quota-performance')).toBeNull();
+
+ rerender(
+ <QuotaHoverCard
+ snapshot={makeSnapshot()}
+ nowMs={NOW_MS}
+ turnUsage={{ outputRateText: null, turnDurationText: null }}
+ />,
+ );
+ expect(screen.queryByTestId('quota-performance')).toBeNull();
+ });
+
it('marks estimated value and labels user-turn totals without exposing SDK segments', () => {
const { rerender } = render(
<QuotaHoverCard
diff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
index 2662335eff..0e036398e2 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
@@ -45,6 +45,8 @@ vi.mock('react-i18next', () => ({
'quotaCard.tokenLabel': 'Token',
'quotaCard.tokenBreakdown': '(输入 {{input}} · 输出 {{output}})',
'quotaCard.cacheLabel': '缓存',
+ 'quotaCard.timeLabel': '耗时',
+ 'quotaCard.timeAndRateValue': '{{duration}} 速度:{{rate}} token/秒',
'quotaCard.modelLabel': '模型',
'quotaCard.waiting': '等待额度数据',
'quotaCard.latestMessageTitle': '最近一轮用户请求累计',
@@ -53,6 +55,8 @@ vi.mock('react-i18next', () => ({
'quotaCard.valueLine': '本轮 token 价值:{{cost}}',
'quotaCard.noBilledCost': '本轮费用暂不可用,仅显示用量',
'usageDetails.costBreakdownHeader': '按模型拆分:',
+ 'usageDetails.durationSeconds': '{{value}}秒',
+ 'usageDetails.durationMinutesSeconds': '{{minutes}}分 {{seconds}}秒',
'usageDetails.modelCostLine': '· {{model}} {{cost}}',
'usageDetails.cacheLine': '缓存拆分:读取 {{read}} · 写入 {{create}} · 命中率 {{rate}}',
'usageDetails.cacheLineNoRate': '缓存拆分:读取 {{read}} · 写入 {{create}}',
@@ -119,6 +123,8 @@ const TURN_USAGE_DETAILS = {
cacheCreateTokens: 74_000,
totalTokens: 74_018,
cacheHitRate: 0,
+ durationMs: 400,
+ turnDurationMs: 12_345,
model: 'claude-opus-5[1m]',
};
@@ -206,6 +212,9 @@ describe('TodaySpendChip Claude subscription popover', () => {
expect(screen.getByText(/^74\.0k/)).toBeTruthy();
expect(screen.getByText('(输入 2 · 输出 16)')).toBeTruthy();
expect(screen.getByText('读 0 · 写 74.0k · 命中 0%')).toBeTruthy();
+ const performance = screen.getByTestId('quota-performance');
+ expect(within(performance).getByText('耗时')).toBeTruthy();
+ expect(within(performance).getByText('12.3秒 速度:40 token/秒')).toBeTruthy();
expect(screen.getByText('claude-opus-5[1m]')).toBeTruthy();
expect(screen.getByText('缓存命中率偏低,本轮较多上下文重新计费')).toBeTruthy();
expect(document.activeElement).toBe(document.body);
@@ -229,6 +238,31 @@ describe('TodaySpendChip Claude subscription popover', () => {
expect(screen.queryByText('(输入 74000 · 输出 16)')).toBeNull();
});
+ it('没有可靠耗时时不显示 TPS,现有用量明细保持不变', () => {
+ setLatestUsageMessage({
+ turnUsageDetails: {
+ ...TURN_USAGE_DETAILS,
+ durationMs: undefined,
+ turnDurationMs: undefined,
+ },
+ });
+ renderClaudeSubscriptionChip();
+ openCardFromHover();
+ expect(screen.queryByText('速度')).toBeNull();
+ expect(screen.getByText('(输入 2 · 输出 16)')).toBeTruthy();
+ });
+
+ it('只有整轮耗时时直接显示耗时,不显示缺失速度占位', () => {
+ setLatestUsageMessage({
+ turnUsageDetails: { ...TURN_USAGE_DETAILS, durationMs: undefined },
+ });
+ renderClaudeSubscriptionChip();
+ openCardFromHover();
+ const performance = screen.getByTestId('quota-performance');
+ expect(within(performance).getByText('耗时')).toBeTruthy();
+ expect(within(performance).getByText('12.3秒')).toBeTruthy();
+ });
+
it('键盘聚焦打开时把焦点移入卡片,关闭后归还 trigger', () => {
renderClaudeSubscriptionChip();
const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4c67e3f899..57fe3117ea 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4263,6 +4263,8 @@
"tokenLabel": "Tokens",
"tokenBreakdown": "(input {{input}} · output {{output}})",
"cacheLabel": "Cache",
+ "timeLabel": "Time",
+ "timeAndRateValue": "{{duration}} TPS:{{rate}}",
"modelLabel": "Model",
"staleData": "Data updated {{minutes}} minutes ago",
"paceTrendFast": "Trending fast at the current average pace (rough estimate)",
@@ -4271,6 +4273,11 @@
"waiting": "Claude subscription usage will update after the next request completes."
},
"usageDetails": {
+ "durationSeconds": "{{value}}s",
+ "durationMinutesSeconds": "{{minutes}}m {{seconds}}s",
+ "performanceLine": "TPS {{rate}} · Time {{duration}}",
+ "performanceRateLine": "TPS {{rate}}",
+ "timeLine": "Time {{duration}}",
"costLine": "Cost this turn: {{cost}}",
"valueLine": "Token value this turn: {{cost}}",
"tokenLine": "Tokens: {{total}} total · input {{input}} · output {{output}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a8ce2a466c..7da34f1374 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4261,6 +4261,8 @@
"tokenLabel": "Token",
"tokenBreakdown": "(入力 {{input}} · 出力 {{output}})",
"cacheLabel": "キャッシュ",
+ "timeLabel": "時間",
+ "timeAndRateValue": "{{duration}} 速度:{{rate}} トークン/秒",
"modelLabel": "モデル",
"staleData": "データは {{minutes}} 分前に更新されました",
"paceTrendFast": "現在の平均使用ペースは速めです(おおよその傾向)",
@@ -4269,6 +4271,11 @@
"waiting": "Claude サブスクリプションの使用量は次のリクエスト完了後に更新されます。"
},
"usageDetails": {
+ "durationSeconds": "{{value}}秒",
+ "durationMinutesSeconds": "{{minutes}}分 {{seconds}}秒",
+ "performanceLine": "速度 {{rate}} トークン/秒 · 時間 {{duration}}",
+ "performanceRateLine": "速度 {{rate}} トークン/秒",
+ "timeLine": "時間 {{duration}}",
"costLine": "このターンの消費: {{cost}}",
"valueLine": "このターンの token 価値: {{cost}}",
"tokenLine": "Token: 合計 {{total}} · 入力 {{input}} · 出力 {{output}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index c6b1a0f479..e41c389ba7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4261,6 +4261,8 @@
"tokenLabel": "Token",
"tokenBreakdown": "(입력 {{input}} · 출력 {{output}})",
"cacheLabel": "캐시",
+ "timeLabel": "시간",
+ "timeAndRateValue": "{{duration}} 속도:{{rate}} 토큰/초",
"modelLabel": "모델",
"staleData": "데이터가 {{minutes}}분 전에 업데이트되었습니다",
"paceTrendFast": "현재 평균 사용 속도는 빠른 편입니다(대략적인 추세)",
@@ -4269,6 +4271,11 @@
"waiting": "Claude 구독 사용량은 다음 요청이 완료된 후 업데이트됩니다."
},
"usageDetails": {
+ "durationSeconds": "{{value}}초",
+ "durationMinutesSeconds": "{{minutes}}분 {{seconds}}초",
+ "performanceLine": "속도 {{rate}} 토큰/초 · 시간 {{duration}}",
+ "performanceRateLine": "속도 {{rate}} 토큰/초",
+ "timeLine": "시간 {{duration}}",
"costLine": "이번 턴 비용: {{cost}}",
"valueLine": "이번 턴 토큰 가치: {{cost}}",
"tokenLine": "Token: 총 {{total}} · 입력 {{input}} · 출력 {{output}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 699fe89fdd..95312dfcca 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4261,6 +4261,8 @@
"tokenLabel": "Token",
"tokenBreakdown": "(输入 {{input}} · 输出 {{output}})",
"cacheLabel": "缓存",
+ "timeLabel": "耗时",
+ "timeAndRateValue": "{{duration}} 速度:{{rate}} token/秒",
"modelLabel": "模型",
"staleData": "数据更新于 {{minutes}} 分钟前",
"paceTrendFast": "按当前平均速度偏快(粗略趋势)",
@@ -4269,6 +4271,11 @@
"waiting": "Claude 订阅余量会在下一轮完成后更新。"
},
"usageDetails": {
+ "durationSeconds": "{{value}}秒",
+ "durationMinutesSeconds": "{{minutes}}分 {{seconds}}秒",
+ "performanceLine": "速度 {{rate}} token/秒 · 耗时 {{duration}}",
+ "performanceRateLine": "速度 {{rate}} token/秒",
+ "timeLine": "耗时 {{duration}}",
"costLine": "本轮消耗:{{cost}}",
"valueLine": "本轮 token 价值:{{cost}}",
"tokenLine": "Token:共 {{total}} · 输入 {{input}} · 输出 {{output}}",
diff --git a/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts b/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts
index 788238d62c..bc35202785 100644
--- a/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts
@@ -18,11 +18,20 @@ vi.mock('../../../shared/brandRegion', () => ({
import { buildTurnUsageDetails, normalizeTurnUsageDetails } from '../../../shared/turnUsageDetails';
import { formatModelShort } from '../usageFormat';
-import { buildTurnUsageTooltipLines } from '../turnUsageTooltip';
+import {
+ buildTurnUsageTooltipLines,
+ formatOutputTokenRate,
+ formatTurnDuration,
+} from '../turnUsageTooltip';
// t 桩: 返回 `key` 或 `key|{json opts}`, 便于断言哪条 i18n key 被用到及其插值。
-const t = ((key: string, opts?: Record<string, unknown>) =>
- opts ? `${key}|${JSON.stringify(opts)}` : key) as unknown as TFunction;
+const t = ((key: string, opts?: Record<string, unknown>) => {
+ if (key === 'usageDetails.durationSeconds') return `${opts?.value}秒`;
+ if (key === 'usageDetails.durationMinutesSeconds') {
+ return `${opts?.minutes}分 ${opts?.seconds}秒`;
+ }
+ return opts ? `${key}|${JSON.stringify(opts)}` : key;
+}) as unknown as TFunction;
describe('formatModelShort', () => {
it('claude 家族 → 简短标签 (剥 [1m] / 尾部日期)', () => {
@@ -42,6 +51,13 @@ describe('formatModelShort', () => {
});
});
+describe('formatOutputTokenRate', () => {
+ it('does not round a positive sub-0.1 TPS rate down to zero', () => {
+ const details = buildTurnUsageDetails({ outputTokens: 1, durationMs: 25_000 })!;
+ expect(formatOutputTokenRate(details)).toBe('<0.1');
+ });
+});
+
describe('buildTurnUsageTooltipLines — 按模型成本明细', () => {
function lines(
perModelCost?: Array<{ model: string; costUsd: number }>,
@@ -188,6 +204,65 @@ describe('buildTurnUsageTooltipLines — 无金额 (token 回退) tooltip', () =
});
});
+describe('buildTurnUsageTooltipLines — 输出速度', () => {
+ it('有输出 token 和有效耗时时显示平均 TPS', () => {
+ const details = buildTurnUsageDetails({
+ inputTokens: 2,
+ outputTokens: 235,
+ cacheCreateTokens: 25_470,
+ durationMs: 8_954,
+ model: 'anthropic/claude-opus-5',
+ })!;
+
+ expect(buildTurnUsageTooltipLines({ details, t, costUsd: 0.17 })).toContain(
+ 'usageDetails.performanceRateLine|{"rate":"26.2"}',
+ );
+ });
+
+ it('does not hide a valid sub-100ms generation behind an arbitrary threshold', () => {
+ const details = buildTurnUsageDetails({ outputTokens: 2, durationMs: 50 })!;
+ expect(buildTurnUsageTooltipLines({ details, t })).toContain(
+ 'usageDetails.performanceRateLine|{"rate":"40"}',
+ );
+ });
+
+ it('旧消息没有耗时时不显示 TPS', () => {
+ const details = buildTurnUsageDetails({ outputTokens: 235 })!;
+ expect(
+ buildTurnUsageTooltipLines({ details, t }).some((line) =>
+ line.startsWith('usageDetails.performanceLine'),
+ ),
+ ).toBe(false);
+ });
+
+ it('shows full-turn wall-clock separately from generation speed', () => {
+ const details = buildTurnUsageDetails({
+ outputTokens: 100,
+ durationMs: 2_000,
+ turnDurationMs: 12_345,
+ })!;
+ const out = buildTurnUsageTooltipLines({ details, t });
+ expect(out).toContain('usageDetails.performanceLine|{"rate":"50","duration":"12.3秒"}');
+ });
+
+ it('shows wall-clock alone without a fake missing-speed placeholder', () => {
+ const details = buildTurnUsageDetails({
+ inputTokens: 100,
+ turnDurationMs: 12_345,
+ })!;
+ expect(buildTurnUsageTooltipLines({ details, t })).toContain(
+ 'usageDetails.timeLine|{"duration":"12.3秒"}',
+ );
+ });
+
+ it('normalizes rounded minute boundaries instead of showing 1m 60s', () => {
+ expect(formatTurnDuration(59_960)).toBe('1m 00s');
+ expect(formatTurnDuration(119_600)).toBe('2m 00s');
+ expect(formatTurnDuration(12_345, t)).toBe('12.3秒');
+ expect(formatTurnDuration(119_600, t)).toBe('2分 00秒');
+ });
+});
+
describe('normalizeTurnUsageDetails — perModelCost 往返 / 清洗', () => {
it('合法数组往返, 过滤空 model / cost<=0', () => {
const d = normalizeTurnUsageDetails({
diff --git a/apps/desktop/src/renderer/lib/turnUsageTooltip.ts b/apps/desktop/src/renderer/lib/turnUsageTooltip.ts
index 4a752413fb..1d9de9af9f 100644
--- a/apps/desktop/src/renderer/lib/turnUsageTooltip.ts
+++ b/apps/desktop/src/renderer/lib/turnUsageTooltip.ts
@@ -30,6 +30,46 @@ function formatTokens(value: number): string {
return formatCompactTokens(Math.max(0, Math.floor(value)));
}
+export function formatOutputTokenRate(details: TurnUsageDetails): string | null {
+ const durationMs = details.durationMs;
+ if (
+ details.outputTokens <= 0 ||
+ typeof durationMs !== 'number' ||
+ !Number.isFinite(durationMs) ||
+ durationMs <= 0
+ ) {
+ return null;
+ }
+ const rate = (details.outputTokens * 1000) / durationMs;
+ if (!Number.isFinite(rate) || rate <= 0) return null;
+ if (rate < 0.1) return '<0.1';
+ return rate >= 100 ? rate.toFixed(0) : rate.toFixed(1).replace(/\.0$/, '');
+}
+
+export function formatTurnDuration(durationMs: number, t?: TFunction): string | null {
+ if (!Number.isFinite(durationMs) || durationMs <= 0) return null;
+ const seconds = durationMs / 1000;
+ if (seconds < 60) {
+ const precision = seconds >= 10 ? 1 : 2;
+ const rounded = Number(seconds.toFixed(precision));
+ if (rounded < 60) {
+ return t
+ ? t('usageDetails.durationSeconds', { value: String(rounded) })
+ : `${rounded}s`;
+ }
+ }
+ const roundedSeconds = Math.round(seconds);
+ const minutes = Math.floor(roundedSeconds / 60);
+ const remainder = roundedSeconds % 60;
+ const paddedSeconds = String(remainder).padStart(2, '0');
+ return t
+ ? t('usageDetails.durationMinutesSeconds', {
+ minutes: String(minutes),
+ seconds: paddedSeconds,
+ })
+ : `${minutes}m ${paddedSeconds}s`;
+}
+
function modelLabel(details: TurnUsageDetails, t: TFunction): string | null {
if (details.model) return details.model;
if (details.models && details.models.length === 1) return details.models[0];
@@ -103,6 +143,20 @@ export function buildTurnUsageTooltipLines({
create: formatTokens(details.cacheCreateTokens),
rate: hitRate ?? '',
}));
+ const outputRate = formatOutputTokenRate(details);
+ const turnDuration = typeof details.turnDurationMs === 'number'
+ ? formatTurnDuration(details.turnDurationMs, t)
+ : null;
+ if (outputRate && turnDuration) {
+ lines.push(t('usageDetails.performanceLine', {
+ rate: outputRate,
+ duration: turnDuration,
+ }));
+ } else if (outputRate) {
+ lines.push(t('usageDetails.performanceRateLine', { rate: outputRate }));
+ } else if (turnDuration) {
+ lines.push(t('usageDetails.timeLine', { duration: turnDuration }));
+ }
// 已展开按模型明细时不再重复笼统的「N 个模型」行。
if (!showBreakdown) {
const model = modelLabel(details, t);
diff --git a/apps/desktop/src/shared/__tests__/turnUsageDetails.test.ts b/apps/desktop/src/shared/__tests__/turnUsageDetails.test.ts
index 4a19d27dd4..2df8a9723e 100644
--- a/apps/desktop/src/shared/__tests__/turnUsageDetails.test.ts
+++ b/apps/desktop/src/shared/__tests__/turnUsageDetails.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { aggregateTurnUsageDetails, buildTurnUsageDetails } from '../turnUsageDetails';
+import {
+ aggregateTurnUsageDetails,
+ buildTurnUsageDetails,
+ mergeTurnUsageDetailsForMessage,
+} from '../turnUsageDetails';
import { DEFAULT_USAGE_CURRENCY, gatewayMoney, usdMoney } from '../regionalMoney';
describe('aggregateTurnUsageDetails', () => {
@@ -10,6 +14,8 @@ describe('aggregateTurnUsageDetails', () => {
outputTokens: 20,
cacheReadTokens: 100,
cacheCreateTokens: 5,
+ durationMs: 1_000,
+ turnDurationMs: 2_000,
model: 'claude-fable-5[1m]',
perModelCost: [{ model: 'claude-fable-5', money: usdMoney(2.5) }],
});
@@ -18,6 +24,8 @@ describe('aggregateTurnUsageDetails', () => {
outputTokens: 7,
cacheReadTokens: 50,
cacheCreateTokens: 2,
+ durationMs: 500,
+ turnDurationMs: 6_500,
models: ['claude-fable-5[1m]', 'claude-opus-5[1m]'],
perModelCost: [
{ model: 'claude-fable-5', money: usdMoney(1.25) },
@@ -32,6 +40,8 @@ describe('aggregateTurnUsageDetails', () => {
cacheReadTokens: 150,
cacheCreateTokens: 7,
totalTokens: 197,
+ durationMs: 1_500,
+ turnDurationMs: 6_500,
models: ['claude-fable-5[1m]', 'claude-opus-5[1m]'],
});
expect(aggregated?.perModelCost).toEqual([
@@ -41,6 +51,36 @@ describe('aggregateTurnUsageDetails', () => {
expect(aggregated?.cacheHitRate).toBeCloseTo(150 / 170);
});
+ it('omits aggregate generation timing when any output segment lacks timing', () => {
+ const timed = buildTurnUsageDetails({ outputTokens: 20, durationMs: 1_000 });
+ const untimed = buildTurnUsageDetails({ outputTokens: 10 });
+
+ expect(aggregateTurnUsageDetails([timed, untimed])).not.toHaveProperty('durationMs');
+ });
+
+ it('does not require timing for segments that contribute no output tokens', () => {
+ const timed = buildTurnUsageDetails({ outputTokens: 20, durationMs: 1_000 });
+ const inputOnly = buildTurnUsageDetails({ inputTokens: 10, durationMs: 500 });
+
+ expect(aggregateTurnUsageDetails([timed, inputOnly])).toMatchObject({ durationMs: 1_000 });
+ });
+
+ it('keeps a complete wall clock from a tokenless terminal segment', () => {
+ const generated = buildTurnUsageDetails({
+ outputTokens: 20,
+ durationMs: 1_000,
+ turnDurationMs: 2_000,
+ });
+ const terminal = buildTurnUsageDetails({ turnDurationMs: 6_500 });
+
+ expect(terminal).toMatchObject({ totalTokens: 0, turnDurationMs: 6_500 });
+ expect(aggregateTurnUsageDetails([generated, terminal])).toMatchObject({
+ outputTokens: 20,
+ durationMs: 1_000,
+ turnDurationMs: 6_500,
+ });
+ });
+
it('uses the default usage currency when the same model has mixed segment currencies', () => {
const staleCurrency = DEFAULT_USAGE_CURRENCY === 'USD' ? 'CNY' : 'USD';
const first = buildTurnUsageDetails({
@@ -80,4 +120,74 @@ describe('aggregateTurnUsageDetails', () => {
]),
).toBeNull();
});
+
+ it('keeps valid duration and drops invalid duration values', () => {
+ expect(buildTurnUsageDetails({ outputTokens: 20, durationMs: 800 })).toMatchObject({
+ durationMs: 800,
+ });
+ expect(buildTurnUsageDetails({ outputTokens: 20, durationMs: 0 })).not.toHaveProperty(
+ 'durationMs',
+ );
+ expect(
+ buildTurnUsageDetails({ outputTokens: 20, durationMs: Number.NaN }),
+ ).not.toHaveProperty('durationMs');
+ });
+});
+
+describe('mergeTurnUsageDetailsForMessage', () => {
+ it('adds input-only continuation usage without replacing prior output timing', () => {
+ const generated = buildTurnUsageDetails({
+ inputTokens: 100,
+ outputTokens: 20,
+ cacheReadTokens: 10,
+ durationMs: 1_200,
+ turnDurationMs: 2_000,
+ model: 'claude-sonnet-4-6',
+ });
+ const terminal = buildTurnUsageDetails({
+ inputTokens: 5,
+ cacheReadTokens: 95,
+ turnDurationMs: 6_500,
+ model: 'claude-sonnet-4-6',
+ });
+
+ expect(mergeTurnUsageDetailsForMessage(generated, terminal!)).toMatchObject({
+ inputTokens: 105,
+ outputTokens: 20,
+ cacheReadTokens: 105,
+ totalTokens: 230,
+ durationMs: 1_200,
+ turnDurationMs: 6_500,
+ model: 'claude-sonnet-4-6',
+ });
+ });
+
+ it('preserves token facts when a tokenless terminal snapshot supplies the final wall clock', () => {
+ const generated = buildTurnUsageDetails({
+ inputTokens: 10,
+ outputTokens: 20,
+ durationMs: 1_000,
+ turnDurationMs: 2_000,
+ });
+ const terminal = buildTurnUsageDetails({ turnDurationMs: 6_500 });
+
+ expect(mergeTurnUsageDetailsForMessage(generated, terminal!)).toEqual({
+ ...generated,
+ turnDurationMs: 6_500,
+ });
+ });
+
+ it('preserves an earlier final wall clock when the token snapshot arrives later', () => {
+ const terminal = buildTurnUsageDetails({ turnDurationMs: 6_500 });
+ const generated = buildTurnUsageDetails({
+ outputTokens: 20,
+ durationMs: 1_000,
+ turnDurationMs: 2_000,
+ });
+
+ expect(mergeTurnUsageDetailsForMessage(terminal, generated!)).toEqual({
+ ...generated,
+ turnDurationMs: 6_500,
+ });
+ });
});
diff --git a/apps/desktop/src/shared/turnUsageDetails.ts b/apps/desktop/src/shared/turnUsageDetails.ts
index 2d87fdda7d..ae6161e86f 100644
--- a/apps/desktop/src/shared/turnUsageDetails.ts
+++ b/apps/desktop/src/shared/turnUsageDetails.ts
@@ -21,6 +21,10 @@ export interface TurnUsageDetails {
cacheCreateTokens: number;
/** 展示用总 token:input + output + cacheRead + cacheCreate。 */
totalTokens: number;
+ /** 可证明的纯模型生成耗时;不含工具执行/用户等待,用于计算输出速率。 */
+ durationMs?: number;
+ /** 整轮 wall-clock 耗时,仅供诊断展示;绝不用于计算输出速率。 */
+ turnDurationMs?: number;
/** cacheRead / (input + cacheRead + cacheCreate),无输入分母时为 null。 */
cacheHitRate: number | null;
/** 本轮主要模型;能确定时填写。 */
@@ -52,12 +56,18 @@ export interface BuildTurnUsageDetailsInput {
| null
| undefined
>;
+ durationMs?: number;
+ turnDurationMs?: number;
}
function sanitizeToken(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
}
+function sanitizeDuration(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
+}
+
function sanitizeModel(value: unknown): string | undefined {
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
}
@@ -118,7 +128,8 @@ export function aggregateTurnUsageDetails(
detailsList: readonly (TurnUsageDetails | null | undefined)[],
): TurnUsageDetails | null {
const details = detailsList.filter(
- (item): item is TurnUsageDetails => Boolean(item && item.totalTokens > 0),
+ (item): item is TurnUsageDetails =>
+ Boolean(item && (item.totalTokens > 0 || item.turnDurationMs !== undefined)),
);
if (details.length === 0) return null;
@@ -141,25 +152,75 @@ export function aggregateTurnUsageDetails(
}
}
+ // TPS is only meaningful when every segment that contributes output tokens
+ // also contributes a compatible generation duration. Dividing all output by
+ // a partial duration silently inflates the displayed rate.
+ const hasCompleteOutputTiming = details.every(
+ (detail) => detail.outputTokens <= 0 || detail.durationMs !== undefined,
+ );
+ const durationMs = hasCompleteOutputTiming
+ ? details.reduce(
+ (sum, item) => sum + (item.outputTokens > 0 ? (item.durationMs ?? 0) : 0),
+ 0,
+ ) || undefined
+ : undefined;
+ // Intermediate Claude continuation segments can carry their own SDK duration,
+ // while the final segment carries the full outer product-turn wall clock.
+ // Taking the maximum preserves that complete value without double-counting.
+ const turnDurationMs =
+ details.reduce((max, item) => Math.max(max, item.turnDurationMs ?? 0), 0) || undefined;
+
return buildTurnUsageDetails({
inputTokens: details.reduce((sum, item) => sum + item.inputTokens, 0),
outputTokens: details.reduce((sum, item) => sum + item.outputTokens, 0),
cacheReadTokens: details.reduce((sum, item) => sum + item.cacheReadTokens, 0),
cacheCreateTokens: details.reduce((sum, item) => sum + item.cacheCreateTokens, 0),
+ durationMs,
+ turnDurationMs,
model: modelNames.length === 1 ? modelNames[0] : undefined,
models: modelNames,
perModelCost: [...perModel.entries()].map(([model, money]) => ({ model, money })),
});
}
-/** Build a normalized usage detail object. Returns null when all token counts are 0. */
+/**
+ * Preserve a later complete product-turn wall clock without replacing the
+ * token facts already attached to the same assistant message. Full usage
+ * snapshots remain replacement/idempotent rather than being summed twice.
+ */
+export function mergeTurnUsageDetailsForMessage(
+ existing: TurnUsageDetails | null | undefined,
+ incoming: TurnUsageDetails,
+): TurnUsageDetails {
+ if (!existing) return incoming;
+ // A continuation can finish without assistant output while still charging
+ // input/cache tokens. That segment reuses the prior assistant message, so it
+ // must extend the existing user-turn aggregate rather than replace the
+ // output tokens and generation duration already attached to that message.
+ if (incoming.outputTokens <= 0 && existing.outputTokens > 0) {
+ return aggregateTurnUsageDetails([existing, incoming]) ?? incoming;
+ }
+ const turnDurationMs = Math.max(existing.turnDurationMs ?? 0, incoming.turnDurationMs ?? 0);
+ const base = incoming.totalTokens > 0 ? incoming : existing.totalTokens > 0 ? existing : incoming;
+ return {
+ ...base,
+ ...(turnDurationMs > 0 ? { turnDurationMs } : {}),
+ };
+}
+
+/**
+ * Build a normalized usage detail object. A positive product-turn duration is
+ * retained even when the terminal SDK segment contributes no tokens.
+ */
export function buildTurnUsageDetails(input: BuildTurnUsageDetailsInput): TurnUsageDetails | null {
const inputTokens = sanitizeToken(input.inputTokens);
const outputTokens = sanitizeToken(input.outputTokens);
const cacheReadTokens = sanitizeToken(input.cacheReadTokens);
const cacheCreateTokens = sanitizeToken(input.cacheCreateTokens);
const totalTokens = inputTokens + outputTokens + cacheReadTokens + cacheCreateTokens;
- if (totalTokens <= 0) return null;
+ const durationMs = sanitizeDuration(input.durationMs);
+ const turnDurationMs = sanitizeDuration(input.turnDurationMs);
+ if (totalTokens <= 0 && turnDurationMs === undefined) return null;
const cacheDenominator = inputTokens + cacheReadTokens + cacheCreateTokens;
const cacheHitRate = cacheDenominator > 0 ? cacheReadTokens / cacheDenominator : null;
@@ -174,6 +235,8 @@ export function buildTurnUsageDetails(input: BuildTurnUsageDetailsInput): TurnUs
cacheCreateTokens,
totalTokens,
cacheHitRate,
+ ...(durationMs ? { durationMs } : {}),
+ ...(turnDurationMs ? { turnDurationMs } : {}),
...(model ? { model } : {}),
...(models ? { models } : {}),
...(perModelCost ? { perModelCost } : {}),
@@ -195,6 +258,8 @@ export function normalizeTurnUsageDetails(value: unknown): TurnUsageDetails | un
models: Array.isArray(raw.models)
? raw.models.filter((m): m is string => typeof m === 'string')
: undefined,
+ durationMs: typeof raw.durationMs === 'number' ? raw.durationMs : undefined,
+ turnDurationMs: typeof raw.turnDurationMs === 'number' ? raw.turnDurationMs : undefined,
perModelCost: Array.isArray(raw.perModelCost)
? raw.perModelCost.map((e) =>
e && typeof e === 'object'
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts
index dc81b8f0b4..cfa202642a 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts
@@ -49,6 +49,47 @@ async function drain(queue: ReturnType<typeof createAsyncQueue<AgentEvent>>): Pr
}
describe('Claude Code translator is_error result guard', () => {
+ it('carries the assistant API message id into done for Vertex lag detection', async () => {
+ const tracker = new UsageTracker();
+ const queue = createAsyncQueue<AgentEvent>();
+ const ctx = createCtx(tracker);
+
+ translateSdkMessage(
+ {
+ type: 'assistant',
+ message: {
+ id: 'msg_vrtx_123',
+ content: [{ type: 'text', text: '完成' }],
+ },
+ },
+ queue,
+ ctx,
+ );
+ translateSdkMessage(
+ {
+ type: 'result',
+ result: '完成',
+ stop_reason: 'end_turn',
+ total_cost_usd: 0,
+ usage: { input_tokens: 20_000, output_tokens: 7 },
+ modelUsage: {
+ 'claude-opus-4-8': {
+ inputTokens: 20_000,
+ outputTokens: 7,
+ costUSD: 0,
+ contextWindow: 200_000,
+ },
+ },
+ },
+ queue,
+ ctx,
+ );
+
+ const events = await drain(queue);
+ const done = events.find((event) => event.type === 'done');
+ expect(done?.data).toMatchObject({ assistant_message_id: 'msg_vrtx_123' });
+ });
+
it('surfaces a terminal error AND keeps the Done/done tail when is_error arrives without a prior envelope', async () => {
// 原 bug 路径②: result.is_error 但 turn 内没有任何 API-error envelope → 旧实现只发
// status Done + done, renderer 的 state.error 不置位, 失败被通知成"已完成"。
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 0029dc5453..0a8a6c06a6 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -1950,6 +1950,7 @@ export class ClaudeCodeAgent extends BaseAgent {
turnState.hasEmittedText = false;
turnState.uiEmittedText = '';
turnState.pendingApiError = null;
+ turnState.lastAssistantRequestId = undefined;
// 代际前进: 迟到的被打断 result 据此被 translator 识别为已被本 send 接管。
turnState.generation += 1;
// interruptRequested **刻意不在这里清**: watchdog / tool-loop guard 先置
diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.ts
index 23c5a54c2f..cab96d4cbd 100644
--- a/packages/maker-core/src/agents/claude-code/translator.ts
+++ b/packages/maker-core/src/agents/claude-code/translator.ts
@@ -102,6 +102,12 @@ export interface TurnState {
* 见过 assistant 消息时不参与判定)。
*/
lastAssistantMsgHadSubstance: boolean;
+ /**
+ * 本 turn 最近一条 assistant API message id。Vertex 路由用 `msg_vrtx_`
+ * 前缀作为输出 token 延迟结算的确定性证据;result 本身不携带该 id,
+ * 因此必须在 assistant 消息到达时按 turn 暂存,再随 done 交给 host。
+ */
+ lastAssistantRequestId?: string;
}
export interface RuntimeState {
@@ -157,6 +163,7 @@ function resetTurnState(turn: TurnState): void {
turn.pendingApiError = null;
turn.interruptRequested = false;
turn.lastAssistantMsgHadSubstance = true;
+ turn.lastAssistantRequestId = undefined;
// generation / interruptGeneration 刻意不清: 代际跨 turn 单调递增(见字段注释)。
}
@@ -989,6 +996,12 @@ function handleAssistant(
// (mid-turn text_delta / message_delta 没有自己的 uuid, 落库时取最近一条 assistant
// 的 meta 作为 fallback, 让 messages.agent_meta 行能被 fork/rewind 反查到)。
const assistantMeta = extractAssistantMeta(msg);
+ if (
+ typeof assistantMeta.requestId === 'string' &&
+ assistantMeta.requestId.startsWith('msg_vrtx_')
+ ) {
+ ctx.turn.lastAssistantRequestId = assistantMeta.requestId;
+ }
// SDK API-error envelope: msg.error 是 SDKAssistantMessageError tag
// (invalid_request / authentication_failed / rate_limit / server_error /
@@ -1752,18 +1765,19 @@ function handleResult(
// silentStop 标记随 done 透传给 host: main 的自动续跑守卫据此决策(补发「继续」或
// surface 耗尽提示)。data 为 unknown 形状、既有消费方(记账 / IM / orca)均按需
// typeof 读字段, 加字段零影响; 不命中时 done 与现状逐字节一致。
+ const safeResult =
+ msg.is_error && typeof msg.result === 'string'
+ ? { ...msg, result: redactSensitiveText(msg.result) }
+ : msg;
+ const resultWithAssistantMessageId = ctx.turn.lastAssistantRequestId
+ ? { ...safeResult, assistant_message_id: ctx.turn.lastAssistantRequestId }
+ : safeResult;
queue.push({
type: 'done',
data:
- msg.is_error && typeof msg.result === 'string'
- ? {
- ...msg,
- result: redactSensitiveText(msg.result),
- ...(isSilentStopTurn ? { silentStop: true } : {}),
- }
- : isSilentStopTurn
- ? { ...msg, silentStop: true }
- : msg,
+ isSilentStopTurn
+ ? { ...resultWithAssistantMessageId, silentStop: true }
+ : resultWithAssistantMessageId,
source: 'claude-code',
});
// reset turn 累积 (tracker 内部已经在 endTurn 里 reset 了 currentTurn,这里只清非 usage 状态)
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index a262cd0abb..4acf3283ed 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -4537,6 +4537,7 @@ describe('CodexAgent MCP thread context hooks', () => {
});
const iterator = handle.events()[Symbol.asyncIterator]();
const transport = createdTransports[0];
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
transport.emitMockLine({
method: 'turn/started',
@@ -4548,6 +4549,7 @@ describe('CodexAgent MCP thread context hooks', () => {
await agent.forceDisposeLocalHostForAuthChange('test forced retire');
+ expect(clearIntervalSpy).toHaveBeenCalledOnce();
expect(handle.isTurnRunning?.()).toBe(false);
expect(transport.closed).toBe(true);
await expect(nextEvent(iterator)).resolves.toMatchObject({
@@ -6114,9 +6116,18 @@ describe('CodexAgent MCP thread context hooks', () => {
const transport = createdTransports[0];
expect(transport).toBeDefined();
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+ transport!.emitMockLine({
+ method: 'turn/started',
+ params: { threadId: 'thread-1', turn: { id: 'turn-close-heartbeat' } },
+ });
+ await waitForExpectation(() => {
+ expect(handle.isTurnRunning?.()).toBe(true);
+ });
await handle.close();
+ expect(clearIntervalSpy).toHaveBeenCalledOnce();
const unsubscribe = transport!.lines
.map((line) => JSON.parse(line) as { method?: string; params?: unknown })
.find((request) => request.method === Method.ThreadUnsubscribe);
@@ -12426,6 +12437,284 @@ describe('CodexAgent MCP thread context hooks', () => {
await handle.close();
});
+ it('excludes a server-resolved approval wait from the completed turn duration', async () => {
+ let now = 1_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-approval-generation-timing',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'ask',
+ });
+ const handlers = host.getThreadHandlers();
+ if (
+ !handlers?.commandExecutionApproval ||
+ !handlers.serverRequestResolved ||
+ !handlers.turnStarted ||
+ !handlers.turnCompleted
+ ) {
+ throw new Error('expected approval timing handlers');
+ }
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const interactionResolver = vi.fn(() => new Promise<never>(() => {}));
+ handle.setInteractionResolver(interactionResolver);
+
+ handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });
+ now = 2_000;
+ const approvalPromise = handlers.commandExecutionApproval({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ itemId: 'approval-item-1',
+ command: 'pwd',
+ cwd: '/repo',
+ });
+ await waitForExpectation(() => expect(interactionResolver).toHaveBeenCalledTimes(1));
+
+ now = 10_000;
+ handlers.serverRequestResolved({
+ threadId: 'start-thread-id',
+ requestId: 'approval-item-1',
+ });
+ await expect(approvalPromise).resolves.toEqual({ decision: 'decline' });
+
+ now = 12_000;
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed', durationMs: 11_000 },
+ });
+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));
+ const done = events.find((event) => event.type === 'done');
+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);
+
+ await handle.close();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it('keeps descendant approval waits out of the root generation timer', async () => {
+ let now = 1_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-descendant-approval-generation-timing',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'ask',
+ });
+ const handlers = host.getThreadHandlers();
+ if (
+ !handlers?.commandExecutionApproval
+ || !handlers.itemStarted
+ || !handlers.itemCompleted
+ || !handlers.turnStarted
+ || !handlers.turnCompleted
+ ) {
+ throw new Error('expected descendant approval timing handlers');
+ }
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const decision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(() => decision.promise);
+
+ handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'root-turn' } });
+ now = 2_000;
+ const collabItem = {
+ id: 'root-collab-item',
+ type: 'collabAgentToolCall',
+ tool: 'spawnAgent',
+ status: 'inProgress',
+ senderThreadId: 'start-thread-id',
+ receiverThreadIds: ['child-thread'],
+ agentsStates: {},
+ };
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'root-turn',
+ item: collabItem,
+ } as never);
+
+ now = 3_000;
+ const approvalPromise = handlers.commandExecutionApproval({
+ threadId: 'child-thread',
+ turnId: 'child-turn',
+ itemId: 'child-command',
+ command: 'pwd',
+ cwd: '/repo',
+ });
+ now = 9_000;
+ decision.resolve({ kind: 'permission', behavior: 'allow' });
+ await expect(approvalPromise).resolves.toEqual({ decision: 'accept' });
+
+ now = 10_000;
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'root-turn',
+ item: { ...collabItem, status: 'completed' },
+ } as never);
+ now = 12_000;
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'root-turn', status: 'completed', durationMs: 11_000 },
+ });
+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));
+ const done = events.find((event) => event.type === 'done');
+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);
+
+ await handle.close();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it.each(['answered', 'server-resolved', 'resolver-failed'] as const)(
+ 'excludes a native requestUserInput wait when it is %s',
+ async (outcome) => {
+ let now = 1_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: `session-native-user-input-timing-${outcome}`,
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (
+ !handlers?.requestUserInput
+ || !handlers.serverRequestResolved
+ || !handlers.turnStarted
+ || !handlers.turnCompleted
+ ) {
+ throw new Error('expected native user-input timing handlers');
+ }
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const decision = deferred<InteractionDecision>();
+ const interactionResolver = vi.fn(() => decision.promise);
+ handle.setInteractionResolver(interactionResolver);
+
+ handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });
+ now = 2_000;
+ const responsePromise = handlers.requestUserInput({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ itemId: 'native-question-1',
+ questions: [{
+ id: 'q1',
+ header: 'Question',
+ question: 'Pick one',
+ isOther: false,
+ isSecret: false,
+ options: null,
+ }],
+ }, { requestId: `native-question-${outcome}` });
+ await waitForExpectation(() => expect(interactionResolver).toHaveBeenCalledTimes(1));
+
+ now = 10_000;
+ if (outcome === 'answered') {
+ decision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'Pick one': 'yes' },
+ });
+ } else if (outcome === 'server-resolved') {
+ handlers.serverRequestResolved({
+ threadId: 'start-thread-id',
+ requestId: `native-question-${outcome}`,
+ });
+ } else {
+ decision.reject(new Error('interaction resolver failed'));
+ }
+ await responsePromise;
+
+ now = 12_000;
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed', durationMs: 11_000 },
+ });
+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));
+ const done = events.find((event) => event.type === 'done');
+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);
+
+ if (outcome === 'server-resolved') {
+ decision.resolve({ kind: 'ask_user_question', answers: {} });
+ }
+ await handle.close();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ },
+ );
+
+ it('omits native requestUserInput timing when the turn id is missing', async () => {
+ let now = 1_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-native-user-input-missing-turn-id',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.requestUserInput || !handlers.turnStarted || !handlers.turnCompleted) {
+ throw new Error('expected native user-input timing handlers');
+ }
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const decision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(() => decision.promise);
+
+ handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });
+ now = 2_000;
+ const responsePromise = handlers.requestUserInput({
+ threadId: 'start-thread-id',
+ turnId: null as never,
+ itemId: 'native-question-without-turn',
+ questions: [{
+ id: 'q1',
+ header: 'Question',
+ question: 'Pick one',
+ isOther: false,
+ isSecret: false,
+ options: null,
+ }],
+ }, { requestId: 'native-question-without-turn' });
+ now = 10_000;
+ decision.resolve({ kind: 'ask_user_question', answers: { 'Pick one': 'yes' } });
+ await responsePromise;
+
+ now = 12_000;
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed', durationMs: 11_000 },
+ });
+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));
+ const done = events.find((event) => event.type === 'done');
+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();
+
+ await handle.close();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
it('routes dynamic ask_user_question tool calls through ask_user_question', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent);
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 7bece0ed5a..6ea74d5eeb 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -113,6 +113,12 @@ import {
isAuthRelatedErrorMessage,
translateErrorNotification,
translateItemNotification,
+ beginCodexGenerationTurn,
+ codexGenerationDurationMs,
+ finalizeCodexGenerationTurn,
+ pauseCodexGeneration,
+ resetCodexGenerationTiming,
+ resumeCodexGeneration,
translateReasoningSummaryTextDelta,
translateReasoningSummaryPartAdded,
translateReasoningTextDelta,
@@ -3954,6 +3960,7 @@ export class CodexAgent extends BaseAgent {
const terminateHandleAfterThreadCleanupFailure = (reason: string): void => {
if (closed) return;
closed = true;
+ resetCodexGenerationTiming(translatorRt);
resetUpstreamIdleForTurnEnd();
unregisterCodexMcpContext(threadId);
unregisterDescendantCodexMcpContexts();
@@ -4824,6 +4831,34 @@ export class CodexAgent extends BaseAgent {
}
}
+ async function withCodexGenerationPaused<T>(
+ requestThreadId: string | null | undefined,
+ turnId: string | null | undefined,
+ pauseId: string,
+ run: () => Promise<T>,
+ ): Promise<T> {
+ if (requestThreadId && requestThreadId !== threadId) {
+ // Descendant requests are routed through the root session UI, but their
+ // waits belong to the child turn. The root collab item already owns the
+ // generation pause, so child ids must never reset the shared root timer.
+ return run();
+ }
+ if (!turnId) {
+ // Without a turn id the wait cannot be paired with a reliable resume
+ // boundary. Keep the interaction usable, but fail closed for TPS.
+ translatorRt.generationTimingReliable = false;
+ return run();
+ }
+ pauseCodexGeneration(translatorRt, turnId, pauseId);
+ try {
+ return await run();
+ } finally {
+ // Covers user decisions, server-side resolution, cancellation and
+ // resolver failures without leaking human wait into model duration.
+ resumeCodexGeneration(translatorRt, turnId, pauseId);
+ }
+ }
+
/**
* 计划模式审批闭环 (对齐官方 TUI plan_implementation 流程, 全部代码驱动):
* plan turn 结束 → 把捕获的 proposed plan 发给用户审批 (plan_review, 复用
@@ -4956,112 +4991,117 @@ export class CodexAgent extends BaseAgent {
* 就走用户决策; settled=true 说明 dismissAllPending 已经替它做了决定, 用户后续点了也吞掉。
*/
async function awaitApprovalDecision(
+ requestThreadId: string | null | undefined,
+ turnId: string | null,
requestId: string,
kind: 'commandExecution' | 'fileChange' | 'mcpServerElicitation',
req: InteractionRequest,
opts?: { forcePrompt?: boolean; autoReviewAction?: ReviewableAction },
): Promise<ApprovalDecision> {
- let forcePrompt =
- opts?.forcePrompt === true ||
- (req.kind === 'permission' &&
- forceTurnConfirmation(req.toolName, req.input));
- // Full access 的普通审批不应打断用户。Auto 在已验证路由上由 app-server
- // auto_review 负责;fallback 路由则由 user reviewer 把越界请求发回客户端,
- // 再由 Cindy reviewer 静默裁决。
- // forcePrompt 高风险 MCP inner tool
- // (如 contacts delete/merge/系统回写)在任何模式下都必须拿到用户的逐次确认。
- if (
- !forcePrompt &&
- mutablePermissionMode === 'bypassPermissions'
- ) {
- return Promise.resolve('accept');
- }
- // Policy turns (unattended: feishu bot / 定时任务) 以 untrusted + read-only 发射,把命令/文件
- // 升级请求发回 host 后自动接受非强制回调 —— 保留该无人值守语义,但**仍对危险桶 fail-closed**:
- // 无人值守时没有人能批准一个 destructive / 凭证 / 远程执行动作,应拒绝,而不是让它逃出 read-only
- // 沙箱静默执行(与交互式 Auto 共用同一张 Cindy core 安全网)。安全 / 仅需升级的动作照常自动
- // 接受,不影响正常无人值守自动化(真需要跑危险命令的自动化应走 bypassPermissions,不受此影响)。
- if (
- !forcePrompt &&
- activeTurnPermissionPolicy &&
- mutablePermissionMode === 'auto'
- ) {
- if (opts?.autoReviewAction) {
- const verdict = reviewAction(
- opts.autoReviewAction,
- runtimeWorkspaceRoots().filter((d): d is string => typeof d === 'string' && d.length > 0),
- { platform: sessionReviewPlatform },
- );
- // 无人值守:只接受 core 判为 auto-approve 的安全动作。prompt / prompt-each-time 都意味着
- // "需人确认"而此路径无人在场 → 一律 fail-closed decline(AGENTS.md 无人值守安全底线)。
- return verdict === 'auto-approve' ? Promise.resolve('accept') : Promise.resolve('decline');
- }
- // 命令/文件类审批却没有可分类的 action(如 permissions 能力升级)——无法审查的高权限动作 →
- // 同样 fail-closed 拒绝。mcpServerElicitation(交互输入)有自己的 forceConfirmToolCall 门,保留 auto-accept。
- if (kind === 'commandExecution' || kind === 'fileChange') {
- return Promise.resolve('decline');
- }
- return Promise.resolve('accept');
- }
- // Auto-review 兜底路径:非 OAuth 路由下 approvalsReviewer='user',app-server 把越界/网络
- // 等审批请求发回 host(OAuth 原生 auto_review 则由 server 内部裁决、根本不到这里 —— 天然
- // "原生优先、Cindy 兜底")。明显安全由本地规则放行;灰区调用当前会话模型做轻量
- // allow/block/ask 裁决。allow/block 不依赖 interactionResolver;只有真正红线 ask 才走 UI,
- // UI 不可用时 dispatchInteraction 自然 fail-closed decline。
- if (
- !forcePrompt &&
- mutablePermissionMode === 'auto' &&
- opts?.autoReviewAction
- ) {
- const decision = await reviewAutoAction(opts.autoReviewAction);
- // 热切换收口:reviewAutoAction 是 async,期间 setPermissionMode 可能收紧(Auto→Ask)或
- // 放宽(→Full)。按**最新**档位决策,否则旧 auto 档 allow 会绕过用户刚要求的确认
- // (codex review P1;与已修复的 Pi / Claude 线程同口径)。cast 破 TS 收窄:TS 不建模
- // await 期间经 setPermissionMode 的重赋值,仍视此处为 'auto';运行期确实可能已变。
- const modeAfterReview = mutablePermissionMode as PermissionMode;
- if (modeAfterReview === 'bypassPermissions') return 'accept';
- if (modeAfterReview !== 'auto') {
- forcePrompt = true;
- } else if (decision.verdict === 'allow') {
- return 'accept';
- } else if (decision.verdict === 'block') {
- // 审阅器没跑起来 ≠ 模型判定危险:前者是基础设施故障,提示一次让用户能接管;
- // 后者按 Auto 本意保持静默。动作两种都仍然 decline。
- if (decision.unavailable) autoReviewUnavailableNotice.notify();
- return 'decline';
- } else {
- // Only red-line decisions reach the user and they cannot be remembered.
- forcePrompt = true;
- }
- }
- const routedRequest =
- forcePrompt && req.kind === 'permission'
- ? { ...req, suggestions: undefined }
- : req;
- return new Promise<ApprovalDecision>((resolve) => {
- const entry: PendingEntry = { resolve, kind, settled: false, forcePrompt };
- pendingApprovals.set(requestId, entry);
- const finalize = (d: ApprovalDecision) => {
- if (entry.settled) return;
- entry.settled = true;
- pendingApprovals.delete(requestId);
- // A stale/custom UI may still return a session grant. Forced policy
- // confirmation applies to this call only and must never persist.
- resolve(forcePrompt && d === 'acceptForSession' ? 'accept' : d);
- };
- dispatchInteraction(routedRequest)
- .then((decision) => {
- if (decision.kind !== 'permission') {
- log.warn('unexpected non-permission decision → decline', { kind: decision.kind });
+ const timingPauseId = `approval:${kind}:${requestId}`;
+ return withCodexGenerationPaused(requestThreadId, turnId, timingPauseId, async () => {
+ let forcePrompt =
+ opts?.forcePrompt === true ||
+ (req.kind === 'permission' &&
+ forceTurnConfirmation(req.toolName, req.input));
+ // Full access 的普通审批不应打断用户。Auto 在已验证路由上由 app-server
+ // auto_review 负责;fallback 路由则由 user reviewer 把越界请求发回客户端,
+ // 再由 Cindy reviewer 静默裁决。
+ // forcePrompt 高风险 MCP inner tool
+ // (如 contacts delete/merge/系统回写)在任何模式下都必须拿到用户的逐次确认。
+ if (
+ !forcePrompt &&
+ mutablePermissionMode === 'bypassPermissions'
+ ) {
+ return Promise.resolve('accept');
+ }
+ // Policy turns (unattended: feishu bot / 定时任务) 以 untrusted + read-only 发射,把命令/文件
+ // 升级请求发回 host 后自动接受非强制回调 —— 保留该无人值守语义,但**仍对危险桶 fail-closed**:
+ // 无人值守时没有人能批准一个 destructive / 凭证 / 远程执行动作,应拒绝,而不是让它逃出 read-only
+ // 沙箱静默执行(与交互式 Auto 共用同一张 Cindy core 安全网)。安全 / 仅需升级的动作照常自动
+ // 接受,不影响正常无人值守自动化(真需要跑危险命令的自动化应走 bypassPermissions,不受此影响)。
+ if (
+ !forcePrompt &&
+ activeTurnPermissionPolicy &&
+ mutablePermissionMode === 'auto'
+ ) {
+ if (opts?.autoReviewAction) {
+ const verdict = reviewAction(
+ opts.autoReviewAction,
+ runtimeWorkspaceRoots().filter((d): d is string => typeof d === 'string' && d.length > 0),
+ { platform: sessionReviewPlatform },
+ );
+ // 无人值守:只接受 core 判为 auto-approve 的安全动作。prompt / prompt-each-time 都意味着
+ // "需人确认"而此路径无人在场 → 一律 fail-closed decline(AGENTS.md 无人值守安全底线)。
+ return verdict === 'auto-approve' ? Promise.resolve('accept') : Promise.resolve('decline');
+ }
+ // 命令/文件类审批却没有可分类的 action(如 permissions 能力升级)——无法审查的高权限动作 →
+ // 同样 fail-closed 拒绝。mcpServerElicitation(交互输入)有自己的 forceConfirmToolCall 门,保留 auto-accept。
+ if (kind === 'commandExecution' || kind === 'fileChange') {
+ return Promise.resolve('decline');
+ }
+ return Promise.resolve('accept');
+ }
+ // Auto-review 兜底路径:非 OAuth 路由下 approvalsReviewer='user',app-server 把越界/网络
+ // 等审批请求发回 host(OAuth 原生 auto_review 则由 server 内部裁决、根本不到这里 —— 天然
+ // "原生优先、Cindy 兜底")。明显安全由本地规则放行;灰区调用当前会话模型做轻量
+ // allow/block/ask 裁决。allow/block 不依赖 interactionResolver;只有真正红线 ask 才走 UI,
+ // UI 不可用时 dispatchInteraction 自然 fail-closed decline。
+ if (
+ !forcePrompt &&
+ mutablePermissionMode === 'auto' &&
+ opts?.autoReviewAction
+ ) {
+ const decision = await reviewAutoAction(opts.autoReviewAction);
+ // 热切换收口:reviewAutoAction 是 async,期间 setPermissionMode 可能收紧(Auto→Ask)或
+ // 放宽(→Full)。按**最新**档位决策,否则旧 auto 档 allow 会绕过用户刚要求的确认
+ // (codex review P1;与已修复的 Pi / Claude 线程同口径)。cast 破 TS 收窄:TS 不建模
+ // await 期间经 setPermissionMode 的重赋值,仍视此处为 'auto';运行期确实可能已变。
+ const modeAfterReview = mutablePermissionMode as PermissionMode;
+ if (modeAfterReview === 'bypassPermissions') return 'accept';
+ if (modeAfterReview !== 'auto') {
+ forcePrompt = true;
+ } else if (decision.verdict === 'allow') {
+ return 'accept';
+ } else if (decision.verdict === 'block') {
+ // 审阅器没跑起来 ≠ 模型判定危险:前者是基础设施故障,提示一次让用户能接管;
+ // 后者按 Auto 本意保持静默。动作两种都仍然 decline。
+ if (decision.unavailable) autoReviewUnavailableNotice.notify();
+ return 'decline';
+ } else {
+ // Only red-line decisions reach the user and they cannot be remembered.
+ forcePrompt = true;
+ }
+ }
+ const routedRequest =
+ forcePrompt && req.kind === 'permission'
+ ? { ...req, suggestions: undefined }
+ : req;
+ return await new Promise<ApprovalDecision>((resolve) => {
+ const entry: PendingEntry = { resolve, kind, settled: false, forcePrompt };
+ pendingApprovals.set(requestId, entry);
+ const finalize = (d: ApprovalDecision) => {
+ if (entry.settled) return;
+ entry.settled = true;
+ pendingApprovals.delete(requestId);
+ // A stale/custom UI may still return a session grant. Forced policy
+ // confirmation applies to this call only and must never persist.
+ resolve(forcePrompt && d === 'acceptForSession' ? 'accept' : d);
+ };
+ dispatchInteraction(routedRequest)
+ .then((decision) => {
+ if (decision.kind !== 'permission') {
+ log.warn('unexpected non-permission decision → decline', { kind: decision.kind });
+ finalize('decline');
+ return;
+ }
+ finalize(mapPermissionDecisionToApproval(decision));
+ })
+ .catch((e) => {
+ log.error('dispatchInteraction threw → decline', { requestId, message: (e as Error).message });
finalize('decline');
- return;
- }
- finalize(mapPermissionDecisionToApproval(decision));
- })
- .catch((e) => {
- log.error('dispatchInteraction threw → decline', { requestId, message: (e as Error).message });
- finalize('decline');
- });
+ });
+ });
});
}
@@ -5730,7 +5770,7 @@ export class CodexAgent extends BaseAgent {
if (turnGate instanceof Promise && !(await turnGate)) return { decision: 'decline' };
// requestId: approvalId 优先 (zsh-exec-bridge 多 callback 场景); 否则用 itemId
const requestId = params.approvalId ?? params.itemId;
- const decision = await awaitApprovalDecision(requestId, 'commandExecution', {
+ const decision = await awaitApprovalDecision(params.threadId, params.turnId, requestId, 'commandExecution', {
kind: 'permission',
requestId,
toolName: 'exec',
@@ -5763,7 +5803,7 @@ export class CodexAgent extends BaseAgent {
if (turnGate === false) return { decision: 'decline' };
if (turnGate instanceof Promise && !(await turnGate)) return { decision: 'decline' };
const requestId = params.itemId;
- const decision = await awaitApprovalDecision(requestId, 'fileChange', {
+ const decision = await awaitApprovalDecision(params.threadId, params.turnId, requestId, 'fileChange', {
kind: 'permission',
requestId,
toolName: 'file_change',
@@ -5987,6 +6027,8 @@ export class CodexAgent extends BaseAgent {
const innerToolName = mcpInnerToolName(params);
const requestId = `mcp-elicitation:${params.serverName}:${params.turnId ?? params.threadId}:${++mcpElicitationSeq}`;
const decision = await awaitApprovalDecision(
+ params.threadId,
+ params.turnId,
requestId,
'mcpServerElicitation',
{
@@ -6034,7 +6076,7 @@ export class CodexAgent extends BaseAgent {
const requestId = params.itemId ?? params.turnId;
// kind 借用 'commandExecution' 仅为复用其 fail-closed 语义(见 awaitApprovalDecision:无 action /
// 无人值守时 decline)——权限升级请求本就该 fail-closed。此处不是命令执行,只是共用同一条兜底路径。
- const decision = await awaitApprovalDecision(requestId, 'commandExecution', {
+ const decision = await awaitApprovalDecision(params.threadId, params.turnId, requestId, 'commandExecution', {
kind: 'permission',
requestId,
toolName: 'permissions',
@@ -6344,6 +6386,10 @@ export class CodexAgent extends BaseAgent {
const questions = normalizeRequestUserInputQuestions(params.questions);
if (questions.length === 0) return { answers: {} };
const kind = classifyUserInputRequest(params);
+ const activeToolContext = activeToolContexts.get(params.itemId);
+ const hasToolGenerationBoundary =
+ activeToolContext?.type === 'mcpToolCall'
+ || activeToolContext?.type === 'dynamicToolCall';
log.debug('native requestUserInput received', {
requestId,
threadId: params.threadId,
@@ -6352,7 +6398,7 @@ export class CodexAgent extends BaseAgent {
kind,
questionCount: questions.length,
});
- return userInputBroker.track(
+ const waitForUserInput = () => userInputBroker.track(
{
kind: 'request_user_input',
connectionId,
@@ -6373,6 +6419,16 @@ export class CodexAgent extends BaseAgent {
settle(response);
},
);
+ // mcpToolCall/dynamicToolCall already pause generation through their item
+ // lifecycle. Only the native fallback needs its own human-wait boundary.
+ return kind === 'ask_user_question' && !hasToolGenerationBoundary
+ ? withCodexGenerationPaused(
+ params.threadId,
+ params.turnId,
+ `user-input:${requestId}`,
+ waitForUserInput,
+ )
+ : waitForUserInput();
};
const dynamicToolCall = async (
@@ -6442,6 +6498,14 @@ export class CodexAgent extends BaseAgent {
function handleServerRequestResolved(params: ServerRequestResolvedNotification['params']): void {
const requestId = String(params.requestId);
+ const pendingApproval = pendingApprovals.get(requestId);
+ let approvalCancelled = false;
+ if (pendingApproval && !pendingApproval.settled) {
+ pendingApproval.settled = true;
+ pendingApprovals.delete(requestId);
+ pendingApproval.resolve('decline');
+ approvalCancelled = true;
+ }
const brokerKey = { connectionId, requestId: params.requestId };
const userInputPending = userInputBroker.has(brokerKey);
const dynamicPending = dynamicToolBroker.has(brokerKey);
@@ -6462,7 +6526,7 @@ export class CodexAgent extends BaseAgent {
success: false,
},
);
- if (userInputCancelled || dynamicCancelled) {
+ if (approvalCancelled || userInputCancelled || dynamicCancelled) {
eventQueue.push({
type: 'interaction_dismissed',
data: { requestId, reason: 'server_request_resolved', resolvedAs: 'deny' },
@@ -7137,6 +7201,7 @@ export class CodexAgent extends BaseAgent {
// usage 用它, 不用 contextTokens 降级值 (那是整个上下文快照, 不是本 turn 增量)。
// 必须在 endTurn 之前取: endTurn 会用降级 aggregate 覆盖后 reset。
const realTurnUsage = usageTracker.getTurnUsage();
+ finalizeCodexGenerationTurn(translatorRt, turn.id);
usageTracker.endTurn({
inputTokens: lastSnap.contextTokens ?? 0,
outputTokens: 0,
@@ -7260,11 +7325,16 @@ export class CodexAgent extends BaseAgent {
// daily_model_usage 记账) 直接累加, 不做任何 delta 化。整个 turn 没收到
// tokenUsage/updated 时就是全 0 (该 turn 不记账) — 不退回 contextTokens:
// 在直接累加的消费方手里, 上下文快照会被当成一笔巨额输入, 高估远糟于漏记。
+ const generationDurationMs = codexGenerationDurationMs(translatorRt);
const codexDoneUsage = {
promptTokens: realTurnUsage.input,
completionTokens: realTurnUsage.output,
reasoningTokens: 0,
cachedTokens: realTurnUsage.cacheRead,
+ ...(generationDurationMs !== undefined ? { durationMs: generationDurationMs } : {}),
+ ...(typeof turn.durationMs === 'number' && Number.isFinite(turn.durationMs)
+ ? { turnDurationMs: turn.durationMs }
+ : {}),
};
eventQueue.push({
type: 'done',
@@ -7968,6 +8038,7 @@ export class CodexAgent extends BaseAgent {
hostForcedRetire: ({ reason }) => {
sessionHostForceRetired = true;
subscriptionInvalidatedByTransport = false;
+ resetCodexGenerationTiming(translatorRt);
const hadPendingWork =
isTurnInFlight
@@ -8148,6 +8219,7 @@ export class CodexAgent extends BaseAgent {
// started 若无条件清空, plan 模式下刚重放的 proposed plan 永久丢失。
if (!wasSameTurn) proposedPlanText = null;
terminalErroredTurnIds.delete(params.turn.id);
+ if (!wasSameTurn) beginCodexGenerationTurn(translatorRt, params.turn.id);
// Reset auth retry-loop dedupe key — 让下一个 turn 重新可以 emit 第一条
// auth error。详见 translator.translateErrorNotification dedupe 逻辑。
translatorRt.lastAuthErrorKey = null;
@@ -8745,6 +8817,7 @@ export class CodexAgent extends BaseAgent {
): Promise<void> {
if (closed) return;
closed = true;
+ resetCodexGenerationTiming(translatorRt);
clearReconnectStall();
resetUpstreamIdleForTurnEnd();
unregisterCodexMcpContext(threadId);
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index 4f985af58f..1290fd85af 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -10,7 +10,7 @@
* 4. willRetry=false → 不论 auth 与否都 push
*/
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
extractRolloutUpdatePlanFunctionCallEvent,
@@ -19,6 +19,11 @@ import {
translateAccountRateLimitsUpdated,
translateItemNotification,
translatePlanUpdatedNotification,
+ beginCodexGenerationTurn,
+ codexGenerationDurationMs,
+ finalizeCodexGenerationTurn,
+ pauseCodexGeneration,
+ resumeCodexGeneration,
} from './translator.js';
import type { CodexRuntimeState } from './translator.js';
import type { CodexErrorInfo } from './app-server/protocol.js';
@@ -95,6 +100,172 @@ describe('translateAccountRateLimitsUpdated', () => {
});
});
+describe('Codex generation timing', () => {
+ it('includes TTFT and thinking while excluding a tool interval', async () => {
+ let now = 4_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ const ctx = makeCtx(rt);
+ try {
+ beginCodexGenerationTurn(rt, 'turn-1', 1_000);
+ translateItemNotification('started', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ startedAtMs: 400_000,
+ item: { type: 'commandExecution', id: 'tool-1', command: 'pwd', status: 'inProgress' },
+ }, q, ctx);
+ now = 10_000;
+ translateItemNotification('completed', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ completedAtMs: 406_000,
+ item: { type: 'commandExecution', id: 'tool-1', command: 'pwd', status: 'completed' },
+ }, q, ctx);
+ now = 11_000;
+ translateItemNotification('started', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ startedAtMs: 407_000,
+ item: { type: 'agentMessage', id: 'msg-1', text: '' },
+ }, q, ctx);
+ translateItemNotification('updated', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ item: { type: 'agentMessage', id: 'msg-1', text: 'hello' },
+ }, q, ctx);
+ now = 11_500;
+ translateItemNotification('completed', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ completedAtMs: 407_500,
+ item: { type: 'agentMessage', id: 'msg-1', text: 'hello' },
+ }, q, ctx);
+ finalizeCodexGenerationTurn(rt, 'turn-1', 12_000);
+ await collect(q);
+ // Local 1s→4s includes initial TTFT/thinking; 4s→10s tool time is excluded;
+ // 10s→12s includes the post-tool API call. Remote timestamps are offset by 396s.
+ expect(codexGenerationDurationMs(rt)).toBe(5_000);
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it('omits timing when a tool completion has no matching start boundary', async () => {
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ const ctx = makeCtx(rt);
+ beginCodexGenerationTurn(rt, 'turn-1', 1_000);
+ translateItemNotification('completed', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ completedAtMs: 3_500,
+ item: { type: 'commandExecution', id: 'tool-1', command: 'pwd', status: 'completed' },
+ }, q, ctx);
+ finalizeCodexGenerationTurn(rt, 'turn-1', 4_000);
+ await collect(q);
+ expect(codexGenerationDurationMs(rt)).toBeUndefined();
+ });
+
+ it('omits timing when an item arrives before the local turn-start boundary', async () => {
+ let now = 2_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ try {
+ translateItemNotification('started', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ startedAtMs: 500_000,
+ item: { type: 'commandExecution', id: 'tool-1', command: 'pwd', status: 'inProgress' },
+ }, q, makeCtx(rt));
+ now = 4_000;
+ translateItemNotification('completed', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ completedAtMs: 502_000,
+ item: { type: 'commandExecution', id: 'tool-1', command: 'pwd', status: 'completed' },
+ }, q, makeCtx(rt));
+ finalizeCodexGenerationTurn(rt, 'turn-1', 5_000);
+ await collect(q);
+ expect(codexGenerationDurationMs(rt)).toBeUndefined();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it('does not require a start boundary for completion-only file changes', async () => {
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ beginCodexGenerationTurn(rt, 'turn-1', 1_000);
+ translateItemNotification('completed', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ completedAtMs: 3_500,
+ item: { type: 'fileChange', id: 'patch-1', changes: [], status: 'completed' },
+ }, q, makeCtx(rt));
+ finalizeCodexGenerationTurn(rt, 'turn-1', 4_000);
+ await collect(q);
+ expect(codexGenerationDurationMs(rt)).toBe(3_000);
+ });
+
+ it('omits timing when context compaction has no matching start boundary', async () => {
+ const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(3_000);
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ try {
+ beginCodexGenerationTurn(rt, 'turn-1', 1_000);
+ translateItemNotification('completed', {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ item: { type: 'contextCompaction', id: 'compact-1' },
+ }, q, makeCtx(rt));
+ finalizeCodexGenerationTurn(rt, 'turn-1', 4_000);
+ const events = await collect(q);
+
+ expect(events).toEqual([
+ expect.objectContaining({
+ type: 'compact_boundary',
+ data: expect.objectContaining({ boundaryId: 'compact-1' }),
+ }),
+ ]);
+ expect(codexGenerationDurationMs(rt)).toBeUndefined();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it('excludes approval waits from generation timing', () => {
+ const rt = newCodexRuntimeState();
+ beginCodexGenerationTurn(rt, 'turn-1', 1_000);
+ pauseCodexGeneration(rt, 'turn-1', 'approval:cmd-1', 2_000);
+ resumeCodexGeneration(rt, 'turn-1', 'approval:cmd-1', 10_000);
+ finalizeCodexGenerationTurn(rt, 'turn-1', 12_000);
+ expect(codexGenerationDurationMs(rt)).toBe(3_000);
+ });
+
+ it('omits timing when the first observed boundary is an interaction pause', () => {
+ const rt = newCodexRuntimeState();
+ pauseCodexGeneration(rt, 'turn-1', 'approval:cmd-1', 2_000);
+ resumeCodexGeneration(rt, 'turn-1', 'approval:cmd-1', 10_000);
+ finalizeCodexGenerationTurn(rt, 'turn-1', 12_000);
+ expect(codexGenerationDurationMs(rt)).toBeUndefined();
+ });
+
+ it('omits timing when the model-active event loop has a suspend-sized gap', () => {
+ const wallClockSpy = vi.spyOn(Date, 'now').mockReturnValue(1_000);
+ try {
+ const rt = newCodexRuntimeState();
+ beginCodexGenerationTurn(rt, 'turn-1', 1_000);
+ wallClockSpy.mockReturnValue(40_000);
+ finalizeCodexGenerationTurn(rt, 'turn-1', 2_000);
+ expect(codexGenerationDurationMs(rt)).toBeUndefined();
+ } finally {
+ wallClockSpy.mockRestore();
+ }
+ });
+});
+
describe('translateErrorNotification', () => {
it('redacts producer logs and preserves non-secret error signals', async () => {
const rt = newCodexRuntimeState();
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index 9ebc32b548..2c266c49f8 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -75,6 +75,18 @@ export interface CodexRuntimeState {
reasoningTextLen: Map<string, number>;
/** item.id → agentMessage 已 emit 文本字符长度(citation 归一化后的空间,见 handleAgentMessage)。 */
itemTextLen: Map<string, number>;
+ /** Current model-active interval start; null while tools/approvals own the turn. */
+ generationStartedAt: number | null;
+ /** Tool/approval boundaries currently owning the turn. Generation resumes after all finish. */
+ generationPendingToolIds: Set<string>;
+ /** Sum of model-active intervals for the current turn, including TTFT and thinking. */
+ generationDurationMs: number;
+ generationTurnId: string | null;
+ /** False when a tool boundary is incomplete/out of order; unreliable TPS is omitted. */
+ generationTimingReliable: boolean;
+ /** Event-loop heartbeat while the model owns the turn; detects suspend/blocking gaps. */
+ generationHeartbeatAt: number | null;
+ generationHeartbeatTimer: ReturnType<typeof setInterval> | null;
/** 已经 emit 过 tool_use 的 item.id (避免 started + 第一次 updated 重复)。 */
emittedToolUse: Set<string>;
/** 尚未 emit 的 Web Search 候选输入,供跨 started/updated/completed 快照补全。 */
@@ -105,6 +117,13 @@ export function newCodexRuntimeState(): CodexRuntimeState {
reasoningStartedAt: new Map(),
reasoningTextLen: new Map(),
itemTextLen: new Map(),
+ generationStartedAt: null,
+ generationPendingToolIds: new Set(),
+ generationDurationMs: 0,
+ generationTurnId: null,
+ generationTimingReliable: true,
+ generationHeartbeatAt: null,
+ generationHeartbeatTimer: null,
emittedToolUse: new Set(),
pendingWebSearchInput: new Map(),
emittedWebSearchInput: new Map(),
@@ -113,6 +132,186 @@ export function newCodexRuntimeState(): CodexRuntimeState {
};
}
+const CODEX_GENERATION_HEARTBEAT_MS = 5_000;
+const CODEX_GENERATION_SUSPEND_GAP_MS = 30_000;
+
+function stopCodexGenerationHeartbeat(rt: CodexRuntimeState): void {
+ if (rt.generationHeartbeatTimer !== null) clearInterval(rt.generationHeartbeatTimer);
+ rt.generationHeartbeatTimer = null;
+ rt.generationHeartbeatAt = null;
+}
+
+function sampleCodexGenerationHeartbeat(rt: CodexRuntimeState, now = Date.now()): void {
+ const previous = rt.generationHeartbeatAt;
+ if (
+ previous !== null &&
+ now - previous > CODEX_GENERATION_HEARTBEAT_MS + CODEX_GENERATION_SUSPEND_GAP_MS
+ ) {
+ rt.generationTimingReliable = false;
+ }
+ rt.generationHeartbeatAt = now;
+}
+
+function startCodexGenerationHeartbeat(rt: CodexRuntimeState): void {
+ stopCodexGenerationHeartbeat(rt);
+ rt.generationHeartbeatAt = Date.now();
+ const timer = setInterval(() => {
+ sampleCodexGenerationHeartbeat(rt);
+ }, CODEX_GENERATION_HEARTBEAT_MS);
+ timer.unref?.();
+ rt.generationHeartbeatTimer = timer;
+}
+
+/** Reset per-turn model-generation timing; turn wall-clock is tracked separately by the host. */
+export function resetCodexGenerationTiming(rt: CodexRuntimeState): void {
+ stopCodexGenerationHeartbeat(rt);
+ rt.generationStartedAt = null;
+ rt.generationPendingToolIds.clear();
+ rt.generationDurationMs = 0;
+ rt.generationTurnId = null;
+ rt.generationTimingReliable = true;
+}
+
+function closeCodexGenerationInterval(rt: CodexRuntimeState, endedAt: number): void {
+ const startedAt = rt.generationStartedAt;
+ rt.generationStartedAt = null;
+ sampleCodexGenerationHeartbeat(rt);
+ stopCodexGenerationHeartbeat(rt);
+ if (startedAt === null) return;
+ if (endedAt < startedAt) {
+ rt.generationTimingReliable = false;
+ return;
+ }
+ rt.generationDurationMs += endedAt - startedAt;
+}
+
+export function beginCodexGenerationTurn(
+ rt: CodexRuntimeState,
+ turnId: string,
+ startedAt = Date.now(),
+): void {
+ if (rt.generationTurnId !== turnId) {
+ resetCodexGenerationTiming(rt);
+ rt.generationTurnId = turnId;
+ }
+ if (rt.generationStartedAt === null && rt.generationPendingToolIds.size === 0) {
+ rt.generationStartedAt = startedAt;
+ startCodexGenerationHeartbeat(rt);
+ }
+}
+
+export function finalizeCodexGenerationTurn(
+ rt: CodexRuntimeState,
+ turnId: string,
+ completedAt = Date.now(),
+): void {
+ if (rt.generationTurnId !== turnId) return;
+ if (rt.generationPendingToolIds.size > 0) {
+ rt.generationTimingReliable = false;
+ rt.generationStartedAt = null;
+ stopCodexGenerationHeartbeat(rt);
+ return;
+ }
+ closeCodexGenerationInterval(rt, completedAt);
+}
+
+export function codexGenerationDurationMs(rt: CodexRuntimeState): number | undefined {
+ return rt.generationTimingReliable && rt.generationDurationMs > 0
+ ? rt.generationDurationMs
+ : undefined;
+}
+
+export function pauseCodexGeneration(
+ rt: CodexRuntimeState,
+ turnId: string,
+ pauseId: string,
+ pausedAt = Date.now(),
+): void {
+ if (rt.generationTurnId !== turnId) {
+ beginCodexGenerationTurn(rt, turnId, pausedAt);
+ // Keep the interaction pair consistent, but omit TPS because the missing
+ // turn-start boundary means TTFT/thinking before this pause is unknown.
+ rt.generationTimingReliable = false;
+ }
+ if (!pauseId) {
+ rt.generationTimingReliable = false;
+ return;
+ }
+ if (rt.generationPendingToolIds.has(pauseId)) return;
+ if (rt.generationPendingToolIds.size === 0) closeCodexGenerationInterval(rt, pausedAt);
+ rt.generationPendingToolIds.add(pauseId);
+}
+
+export function resumeCodexGeneration(
+ rt: CodexRuntimeState,
+ turnId: string,
+ pauseId: string,
+ resumedAt = Date.now(),
+): void {
+ if (rt.generationTurnId !== turnId || !rt.generationPendingToolIds.delete(pauseId)) {
+ rt.generationTimingReliable = false;
+ return;
+ }
+ if (rt.generationPendingToolIds.size === 0) rt.generationStartedAt = resumedAt;
+ if (rt.generationPendingToolIds.size === 0) startCodexGenerationHeartbeat(rt);
+}
+
+const CODEX_GENERATION_PAUSE_ITEM_TYPES: ReadonlySet<string> = new Set([
+ 'commandExecution',
+ 'mcpToolCall',
+ 'dynamicToolCall',
+ 'collabAgentToolCall',
+ 'webSearch',
+ 'imageGeneration',
+ 'imageView',
+ 'contextCompaction',
+]);
+// App-server v2 reports fileChange only after the patch is complete. With no
+// matching start event it is an output notification, not a pairable timing
+// boundary; handleFileChange still publishes its tool events below.
+// contextCompaction may likewise arrive completion-only. Keeping it in the
+// paired pause set makes that shape fail closed, while still excluding the
+// compaction interval if a future app-server supplies both boundaries.
+
+function noteCodexGenerationBoundary(
+ rt: CodexRuntimeState,
+ phase: ItemPhase,
+ item: { id?: unknown; type?: unknown },
+ notification: { turnId?: unknown },
+): void {
+ const turnId = notification.turnId;
+ if (typeof turnId !== 'string') return;
+ // App-server timestamps may originate on a remote SSH host whose wall clock
+ // differs from the desktop. Keep every generation boundary in the local
+ // receipt-time domain so interval subtraction never mixes remote clocks.
+ // A separate event-loop heartbeat fails closed on suspend-sized local jumps.
+ const receivedAt = Date.now();
+ if (rt.generationTurnId !== turnId) {
+ beginCodexGenerationTurn(rt, turnId, receivedAt);
+ // The authoritative local turn-start boundary was not observed. Starting
+ // at this item receipt would drop TTFT/thinking, so keep the state usable
+ // for pause pairing but fail closed for TPS.
+ rt.generationTimingReliable = false;
+ }
+ if (
+ typeof item.type !== 'string' ||
+ !CODEX_GENERATION_PAUSE_ITEM_TYPES.has(item.type)
+ ) {
+ return;
+ }
+ if (typeof item.id !== 'string' || item.id.length === 0) {
+ rt.generationTimingReliable = false;
+ return;
+ }
+ const pauseId = `item:${item.id}`;
+ if (phase === 'started') {
+ pauseCodexGeneration(rt, turnId, pauseId, receivedAt);
+ return;
+ }
+ if (phase !== 'completed') return;
+ resumeCodexGeneration(rt, turnId, pauseId, receivedAt);
+}
+
// ── 上下文 ────────────────────────────────────────────────────────────────────
interface TranslatorLog {
@@ -174,6 +373,12 @@ export function translateItemNotification(
ctx.log.warn('item missing type field', { phase, itemKeys: Object.keys(item) });
return;
}
+ noteCodexGenerationBoundary(
+ ctx.rt,
+ phase,
+ item as { id?: unknown; type?: unknown },
+ notification as { turnId?: unknown },
+ );
switch (itemType) {
case 'agentMessage':
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 72374a80ce..577b7c9453 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -23,6 +23,7 @@ const knobs = vi.hoisted(() => ({
getStateRejects: false,
closeCount: 0,
onExit: null as null | ((info: { code: number | null; signal: string | null }) => void),
+ onEvent: null as null | ((event: unknown) => void),
spawnedEnvs: [] as Array<Record<string, string | undefined>>,
spawnedArgs: [] as string[][],
}));
@@ -33,9 +34,15 @@ vi.mock('../rpc-client.js', () => ({
constructor(opts: unknown) {
// 捕获 onExit 以便单测模拟进程异常退出(crash);捕获 env 以断言每会话隔离 configHome。
const o = opts as
- | { onExit?: typeof knobs.onExit; env?: Record<string, string | undefined>; args?: string[] }
+ | {
+ onExit?: typeof knobs.onExit;
+ onEvent?: typeof knobs.onEvent;
+ env?: Record<string, string | undefined>;
+ args?: string[];
+ }
| undefined;
knobs.onExit = o?.onExit ?? null;
+ knobs.onEvent = o?.onEvent ?? null;
knobs.spawnedEnvs.push({ ...(o?.env ?? {}) });
knobs.spawnedArgs.push([...(o?.args ?? [])]);
if (knobs.ctorThrows) throw new Error('spawn failed (mock)');
@@ -78,6 +85,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
knobs.getStateRejects = false;
knobs.closeCount = 0;
knobs.onExit = null;
+ knobs.onEvent = null;
knobs.spawnedEnvs = [];
knobs.spawnedArgs = [];
disposed = 0;
@@ -88,6 +96,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
});
afterEach(() => {
+ vi.restoreAllMocks();
rmSync(agentHome, { recursive: true, force: true });
rmSync(cwd, { recursive: true, force: true });
});
@@ -163,6 +172,8 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
it('does not dispose ctx on the success path (dispose is deferred to close())', async () => {
const agent = new PiAgent(buildDeps());
const handle = await agent.startSession(opts());
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+ knobs.onEvent?.({ type: 'message_start' });
expect(preparedMcpContext).toMatchObject({
sessionId: 's1',
sessionInstanceId: 'pi-instance-1',
@@ -171,6 +182,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(disposed).toBe(0);
expect(proxyDisposed).toBe(0);
await handle.close();
+ expect(clearIntervalSpy).toHaveBeenCalledOnce();
expect(disposed).toBe(1); // close() 才注销
expect(proxyDisposed).toBe(1);
});
@@ -206,8 +218,11 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(disposed).toBe(0);
expect(proxyDisposed).toBe(0);
expect(knobs.onExit).toBeTypeOf('function');
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+ knobs.onEvent?.({ type: 'message_start' });
knobs.onExit!({ code: 1, signal: null }); // 模拟进程异常退出
+ expect(clearIntervalSpy).toHaveBeenCalledOnce();
expect(disposed).toBe(1);
expect(proxyDisposed).toBe(1);
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
index 8bb2d458e9..bddf8f87bb 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
@@ -67,7 +67,12 @@ describe('pi translator', () => {
translatePiEvent(
ev({
type: 'message_end',
- message: { role: 'assistant', content: [{ type: 'text', text: 'hi' }], usage: { input: 100, output: 20, cacheRead: 5, cacheWrite: 3 } },
+ message: {
+ role: 'assistant',
+ content: [{ type: 'text', text: 'hi' }],
+ usage: { input: 100, output: 20, cacheRead: 5, cacheWrite: 3 },
+ duration: 1_200,
+ },
}),
queue,
ctx,
@@ -81,6 +86,8 @@ describe('pi translator', () => {
expect(usage.outputTokens).toBe(20);
expect(usage.cacheReadTokens).toBe(5);
expect(usage.cacheCreationTokens).toBe(3);
+ expect(usage.durationMs).toBeGreaterThanOrEqual(1_200);
+ expect(usage.turnDurationMs).toBeGreaterThanOrEqual(0);
// 快照累计 input+output。
expect(usageSnapshotOf(ctx).tokenUsage).toBe(120);
// done.data.result 带上最终回复文本 —— register.ts 的 will-assistant-message 出口钩子
@@ -92,6 +99,83 @@ describe('pi translator', () => {
}));
});
+ it('reads Pi v0.83 generation duration from timestamp with a live heartbeat', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ const timestamp = Date.now() - 1_200;
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(ev({ type: 'message_start' }), queue, ctx);
+ translatePiEvent(
+ ev({
+ type: 'message_end',
+ message: {
+ role: 'assistant',
+ content: [{ type: 'text', text: 'answer after a tool' }],
+ usage: { input: 10, output: 5 },
+ timestamp,
+ },
+ }),
+ queue,
+ ctx,
+ );
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+ const usage = (events.find((e) => e.type === 'done')!.data as { usage: Record<string, unknown> }).usage;
+ expect(usage.durationMs).toEqual(expect.any(Number));
+ expect(usage.durationMs).toBeGreaterThanOrEqual(1_200);
+ expect(usage.turnDurationMs).toEqual(expect.any(Number));
+ });
+
+ it('omits timestamp-derived timing after a suspend-sized heartbeat gap', () => {
+ const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(1_000);
+ try {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(ev({ type: 'message_start' }), queue, ctx);
+ nowSpy.mockReturnValue(40_000);
+ translatePiEvent(
+ ev({
+ type: 'message_end',
+ message: { role: 'assistant', content: [], usage: { output: 5 }, timestamp: 1_000 },
+ }),
+ queue,
+ ctx,
+ );
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+ const usage = (events.find((e) => e.type === 'done')!.data as { usage: Record<string, unknown> }).usage;
+ expect(usage).not.toHaveProperty('durationMs');
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it('omits timing when one of multiple output messages lacks duration', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(
+ ev({
+ type: 'message_end',
+ message: { role: 'assistant', content: [], usage: { output: 10 }, duration: 500 },
+ }),
+ queue,
+ ctx,
+ );
+ translatePiEvent(
+ ev({
+ type: 'message_end',
+ message: { role: 'assistant', content: [], usage: { output: 5 } },
+ }),
+ queue,
+ ctx,
+ );
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+
+ const usage = (events.find((e) => e.type === 'done')!.data as { usage: Record<string, unknown> }).usage;
+ expect(usage.outputTokens).toBe(15);
+ expect(usage).not.toHaveProperty('durationMs');
+ });
+
it('done.result carries the last assistant message text (multi-message turn) and resets per turn', () => {
const ctx = createPiTranslateContext(noopLogger);
const { queue, events } = makeQueue();
@@ -408,12 +492,38 @@ describe('pi translator', () => {
translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
const done = events.find((e) => e.type === 'done');
- expect((done?.data as { usage?: unknown }).usage).toEqual({
+ expect((done?.data as { usage?: unknown }).usage).toMatchObject({
inputTokens: 100,
outputTokens: 20,
cacheReadTokens: 5,
cacheCreationTokens: 2,
});
+ expect(
+ (done?.data as { usage?: { turnDurationMs?: unknown } }).usage?.turnDurationMs,
+ ).toEqual(expect.any(Number));
+ expect((done?.data as { usage?: Record<string, unknown> }).usage).not.toHaveProperty(
+ 'durationMs',
+ );
+ });
+
+ it('omits parent-only timing after delegated output joins the turn', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(
+ ev({
+ type: 'message_end',
+ message: { role: 'assistant', content: [], usage: { output: 10 }, duration: 1_000 },
+ }),
+ queue,
+ ctx,
+ );
+ translatePiEvent(progressEvent('sa-1', { input: 100, output: 20 }), queue, ctx);
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+
+ const usage = (events.find((e) => e.type === 'done')!.data as { usage: Record<string, unknown> }).usage;
+ expect(usage.outputTokens).toBe(30);
+ expect(usage).not.toHaveProperty('durationMs');
});
it('only counts the increment — progress frames report cumulative totals', () => {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index ae382bc718..72d54986aa 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -83,6 +83,7 @@ import { PiRpcProcess, type PiRpcEvent } from './rpc-client.js';
import { capturePiRuntimeCapabilityManifest } from './runtime-capabilities.js';
import {
createPiTranslateContext,
+ disposePiTranslateContext,
translatePiEvent,
usageSnapshotOf,
type PiTranslateContext,
@@ -1311,6 +1312,7 @@ export class PiAgent extends BaseAgent {
translatePiEvent(event, queue, ctx);
},
onExit: ({ code, signal }) => {
+ disposePiTranslateContext(ctx);
clearActiveTurnPermissionPolicy('process_exit', { dismissPending: true });
runtimeCapabilityGeneration++;
publishRuntimeCapabilities(undefined);
@@ -1340,6 +1342,7 @@ export class PiAgent extends BaseAgent {
},
});
} catch (err) {
+ disposePiTranslateContext(ctx);
try {
disposeSessionRegistrations();
} catch {
@@ -1556,6 +1559,7 @@ export class PiAgent extends BaseAgent {
}
}
} catch (err) {
+ disposePiTranslateContext(ctx);
try {
disposeSessionRegistrations();
} catch {
@@ -1852,6 +1856,7 @@ export class PiAgent extends BaseAgent {
async close(): Promise<void> {
closed = true;
+ disposePiTranslateContext(ctx);
runtimeCapabilityGeneration++;
publishRuntimeCapabilities(undefined);
runtimeCapabilityListeners.clear();
diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.ts
index c1be326d88..d570a53aa3 100644
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@ -33,6 +33,10 @@ interface PiAssistantMessage {
role: 'assistant';
content?: Array<Record<string, unknown>>;
usage?: PiUsage;
+ /** provider-reported duration when the runtime supplies one. */
+ duration?: number;
+ /** Pi v0.83 generation-start wall-clock timestamp (milliseconds). */
+ timestamp?: number;
model?: string;
stopReason?: string;
}
@@ -71,6 +75,14 @@ export interface PiTranslateContext {
* 不带上就会对 Pi 静默跳过这些钩子(codex review P1)。
*/
finalAssistantText: string;
+ /** 整轮 wall-clock 起点;只用于诊断,不参与 TPS。 */
+ turnWallClockStartedAt: number;
+ generationDurationMs: number;
+ /** False when any reported output lacks compatible parent generation timing. */
+ generationTimingReliable: boolean;
+ generationHeartbeatAt: number;
+ generationHeartbeatTimer: ReturnType<typeof setInterval> | null;
+ generationHeartbeatReliable: boolean;
/**
* 每个子代理调用(taskId)最近一次上报的**累计**委派用量。进度帧报累计值,这里存上次值
* 用来算增量,避免同一批用量被反复加进 turn 记账。与其它 turn 计数器同点(agent_start)清空。
@@ -93,10 +105,51 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {
thinkingSeq: 0,
thinkingBlocks: new Map(),
finalAssistantText: '',
+ turnWallClockStartedAt: 0,
+ generationDurationMs: 0,
+ generationTimingReliable: true,
+ generationHeartbeatAt: 0,
+ generationHeartbeatTimer: null,
+ generationHeartbeatReliable: true,
delegatedUsage: new Map(),
};
}
+const PI_GENERATION_HEARTBEAT_MS = 5_000;
+const PI_GENERATION_SUSPEND_GAP_MS = 30_000;
+
+function stopPiGenerationHeartbeat(ctx: PiTranslateContext): void {
+ if (ctx.generationHeartbeatTimer !== null) clearInterval(ctx.generationHeartbeatTimer);
+ ctx.generationHeartbeatTimer = null;
+ ctx.generationHeartbeatAt = 0;
+}
+
+/** Release translator-owned resources when a Pi session ends outside a normal turn boundary. */
+export function disposePiTranslateContext(ctx: PiTranslateContext): void {
+ stopPiGenerationHeartbeat(ctx);
+ ctx.isStreaming = false;
+}
+
+function samplePiGenerationHeartbeat(ctx: PiTranslateContext, now = Date.now()): void {
+ if (
+ ctx.generationHeartbeatAt > 0 &&
+ now - ctx.generationHeartbeatAt >
+ PI_GENERATION_HEARTBEAT_MS + PI_GENERATION_SUSPEND_GAP_MS
+ ) {
+ ctx.generationHeartbeatReliable = false;
+ }
+ ctx.generationHeartbeatAt = now;
+}
+
+function startPiGenerationHeartbeat(ctx: PiTranslateContext): void {
+ stopPiGenerationHeartbeat(ctx);
+ ctx.generationHeartbeatReliable = true;
+ ctx.generationHeartbeatAt = Date.now();
+ const timer = setInterval(() => samplePiGenerationHeartbeat(ctx), PI_GENERATION_HEARTBEAT_MS);
+ timer.unref?.();
+ ctx.generationHeartbeatTimer = timer;
+}
+
export function usageSnapshotOf(ctx: PiTranslateContext): UsageSnapshot {
return {
tokenUsage: ctx.turnTokens,
@@ -165,6 +218,10 @@ function applyDelegatedUsage(
ctx.turnCacheRead += delta.cacheRead;
ctx.turnCacheWrite += delta.cacheWrite;
ctx.costUsd += delta.cost;
+ // Child progress exposes wall-clock card duration, not generation-only time.
+ // Once child output joins the numerator, parent-only timing cannot produce a
+ // compatible TPS denominator, so retain usage but omit speed for this turn.
+ if (delta.output > 0) ctx.generationTimingReliable = false;
}
function assistantTextOf(message: PiAssistantMessage): string {
@@ -229,6 +286,10 @@ export function translatePiEvent(
ctx.turnCacheRead = 0;
ctx.turnCacheWrite = 0;
ctx.finalAssistantText = '';
+ ctx.turnWallClockStartedAt = Date.now();
+ ctx.generationDurationMs = 0;
+ ctx.generationTimingReliable = true;
+ stopPiGenerationHeartbeat(ctx);
// 与其它 turn 计数器同点清:新 turn 的委派用量不该跟上一 turn 的累计值作差,
// 也避免长会话里 taskId 条目无界堆积。
ctx.delegatedUsage.clear();
@@ -241,6 +302,7 @@ export function translatePiEvent(
case 'message_start': {
ctx.thinkingBlocks.clear();
+ startPiGenerationHeartbeat(ctx);
return;
}
@@ -255,6 +317,28 @@ export function translatePiEvent(
const message = event.message as PiAssistantMessage | undefined;
if (!message || message.role !== 'assistant') return;
applyUsage(ctx, message.usage);
+ const hadGenerationHeartbeat = ctx.generationHeartbeatAt > 0;
+ samplePiGenerationHeartbeat(ctx);
+ const messageDurationMs =
+ typeof message.duration === 'number' &&
+ Number.isFinite(message.duration) &&
+ message.duration > 0
+ ? message.duration
+ : hadGenerationHeartbeat &&
+ ctx.generationHeartbeatReliable &&
+ typeof message.timestamp === 'number' &&
+ Number.isFinite(message.timestamp) &&
+ message.timestamp > 0
+ ? Date.now() - message.timestamp
+ : 0;
+ stopPiGenerationHeartbeat(ctx);
+ if (messageDurationMs > 0) {
+ ctx.generationDurationMs += messageDurationMs;
+ } else if ((message.usage?.output ?? 0) > 0) {
+ // A single untimed output-bearing message makes the whole turn's TPS
+ // denominator partial. Keep token/cost accounting, but do not publish it.
+ ctx.generationTimingReliable = false;
+ }
const fullText = assistantTextOf(message);
if (fullText.length > 0) {
// 覆盖为本 turn 最新一条有文本的 assistant 回复,agent_settled 作 done.result 上报。
@@ -331,6 +415,7 @@ export function translatePiEvent(
case 'agent_settled': {
ctx.isStreaming = false;
+ stopPiGenerationHeartbeat(ctx);
queue.push({
type: 'done',
data: {
@@ -346,6 +431,15 @@ export function translatePiEvent(
outputTokens: ctx.turnOutput,
cacheReadTokens: ctx.turnCacheRead,
cacheCreationTokens: ctx.turnCacheWrite,
+ // durationMs is deliberately generation-only. If Pi does not report a
+ // per-assistant generation duration, omit it instead of charging tool
+ // execution / user waits to TPS.
+ ...(ctx.generationTimingReliable && ctx.generationDurationMs > 0
+ ? { durationMs: ctx.generationDurationMs }
+ : {}),
+ ...(ctx.turnWallClockStartedAt > 0
+ ? { turnDurationMs: Math.max(0, Date.now() - ctx.turnWallClockStartedAt) }
+ : {}),
},
},
source: 'pi',