Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(usage): 修正 token 平均速度计算并补充悬浮说明 (#3953)
Dashc43335b8faf0
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex f79479df84..cac4f641b4 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -5562,6 +5562,10 @@ function RunningStatusBar({});const rateText =usageMeta.kind === 'rate' ? t('chat.runningStatus.tokenRate', { rate: usageMeta.rate }) : null;+ const rateTipText = [+ t('chat.runningStatus.tokenRateDescription'),+ ...(tokenUsage > 0 ? [tokenCountTipText] : []),+ ].join('\n');// 淡入淡出/隐藏占位样式 —— 同时作用于左(状态)、右(elapsed/tokens)两段。// visibility:hidden 只隐藏不收高,让 linger / fade 阶段稳定;淡出结束后整个@@ -5674,17 +5678,11 @@ function RunningStatusBar({·</span>{rateText ? (- tokenUsage > 0 ? (- <Tip text={tokenCountTipText} side="top">- <span className="text-13 font-medium text-[var(--status-bar-meta)]">- {rateText}- </span>- </Tip>- ) : (+ <Tip text={rateTipText} side="top" contentClassName="whitespace-pre-line"><span className="text-13 font-medium text-[var(--status-bar-meta)]">{rateText}</span>- )+ </Tip>) : (<><ArrowDown size={13} className="shrink-0 text-[var(--status-bar-meta)]" />diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 10f5d35587..58419976d2 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7846,6 +7846,7 @@},"runningStatus": {"tokenRate": "{{rate}} tok/s",+ "tokenRateDescription": "The main Agent’s average generation speed for this turn, including thinking and excluding tool execution and approval waits. Updated with reported usage; the adjacent timer shows total turn time.","tokenCount": "{{tokens}} tok"},"shareImage": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex cbdaf1a130..accf55e792 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7841,6 +7841,7 @@},"runningStatus": {"tokenRate": "{{rate}} tok/s",+ "tokenRateDescription": "このターンのメイン Agent の平均生成速度です。思考を含み、ツール実行と承認待ちは除きます。使用量の報告に合わせて更新され、隣にはターン全体の経過時間が表示されます。","tokenCount": "{{tokens}} tok"},"shareImage": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex d84651ce4d..293ff05651 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7841,6 +7841,7 @@},"runningStatus": {"tokenRate": "{{rate}} tok/s",+ "tokenRateDescription": "이번 턴에서 메인 Agent의 평균 생성 속도입니다. 사고 과정을 포함하며 도구 실행과 승인 대기 시간은 제외합니다. 사용량 보고에 따라 갱신되며, 옆에는 턴의 전체 경과 시간이 표시됩니다.","tokenCount": "{{tokens}} tok"},"shareImage": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 98a9647f35..795abe8697 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7841,6 +7841,7 @@},"runningStatus": {"tokenRate": "{{rate}} tok/s",+ "tokenRateDescription": "本轮主 Agent 的平均生成速度,含思考,排除工具执行和审批等待。随用量回报更新;旁边显示本轮总耗时。","tokenCount": "{{tokens}} tok"},"shareImage": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 4497c1256b..5e28d68b0e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -7840,6 +7840,7 @@},"runningStatus": {"tokenRate": "{{rate}} tok/s",+ "tokenRateDescription": "本輪主 Agent 的平均生成速度,含思考,排除工具執行與審批等待。隨用量回報更新;旁邊顯示本輪總耗時。","tokenCount": "{{tokens}} tok"},"shareImage": {diff --git a/packages/maker-core/src/agents/claude-code/generation-timing.test.ts b/packages/maker-core/src/agents/claude-code/generation-timing.test.tsindex 29340a308b..0d13e49e3a 100644--- a/packages/maker-core/src/agents/claude-code/generation-timing.test.ts+++ b/packages/maker-core/src/agents/claude-code/generation-timing.test.ts@@ -256,7 +256,7 @@ describe('claude generation pause boundaries', () => {queue.end();});- it('attaches live generation fields to the terminal snapshot without message_delta', async () => {+ it('keeps terminal tokens but omits unproven speed without message_delta', async () => {vi.useFakeTimers();vi.setSystemTime(1_000);const ctx = createTranslatorCtx();@@ -301,10 +301,10 @@ describe('claude generation pause boundaries', () => {expect(doneStatus?.data).toMatchObject({isRunning: false,outputTokens: 40,- generationDurationMs: 800,- generationReliable: true,+ generationReliable: false,generationActive: false,});+ expect(doneStatus?.data).not.toHaveProperty('generationDurationMs');resetClaudeGenerationTiming(ctx.rt.generation);vi.useRealTimers();});@@ -492,6 +492,8 @@ describe('claude generation pause boundaries', () => {});it('fails closed when a resumed result aggregate cannot prove streamed segment completeness', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000);const ctx = createTranslatorCtx();const queue = createAsyncQueue<AgentEvent>();translateSdkMessage(@@ -505,6 +507,7 @@ describe('claude generation pause boundaries', () => {queue,ctx,);+ vi.setSystemTime(2_000);translateSdkMessage({type: 'stream_event',@@ -535,6 +538,18 @@ describe('claude generation pause boundaries', () => {const events: AgentEvent[] = [];for await (const event of queue) events.push(event);const done = events.find((event) => event.type === 'done');+ const statuses = events.filter((event) => event.type === 'status');+ expect(statuses.at(-2)?.data).toMatchObject({+ outputTokens: 25,+ generationDurationMs: 1_000,+ generationReliable: true,+ });+ expect(statuses.at(-1)?.data).toMatchObject({+ status: 'Done',+ outputTokens: 225,+ generationReliable: false,+ });+ expect(statuses.at(-1)?.data).not.toHaveProperty('generationDurationMs');expect(done?.data).toMatchObject({usageSegmentsComplete: false,usageSegments: [@@ -550,6 +565,137 @@ describe('claude generation pause boundaries', () => {});});+ it('samples only accepted output growth across input-only, duplicate, and older deltas', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000);+ const ctx = createTranslatorCtx();+ const queue = createAsyncQueue<AgentEvent>();+ const send = (message: Parameters<typeof translateSdkMessage>[0]) =>+ translateSdkMessage(message, queue, ctx);+ send({ type: 'stream_event', event: {+ type: 'message_start', message: { usage: { input_tokens: 10 } },+ } });+ vi.setSystemTime(2_000);+ send({ type: 'stream_event', event: { type: 'message_delta', usage: { output_tokens: 100 } } });+ for (const [index, usage] of [+ { input_tokens: 20 },+ { output_tokens: 0, cache_read_input_tokens: 10 },+ { output_tokens: 100 },+ { output_tokens: 50 },+ ].entries()) {+ vi.setSystemTime(3_000 + index * 1_000);+ send({ type: 'stream_event', event: { type: 'message_delta', usage } });+ expect(ctx.tracker.getTurnUsage().output).toBe(100);+ expect(ctx.rt.generation.outputDurationMs).toBe(1_000);+ }+ expect(ctx.tracker.getTurnUsage()).toMatchObject({ input: 20, cacheRead: 10 });+ vi.setSystemTime(7_000);+ send({ type: 'stream_event', event: { type: 'message_delta', usage: { output_tokens: 200 } } });+ expect(ctx.rt.generation.outputDurationMs).toBe(6_000);+ vi.setSystemTime(8_000);+ send({ type: 'stream_event', event: { type: 'message_delta', usage: { input_tokens: 30 } } });+ vi.setSystemTime(12_000);+ send({ type: 'result', stop_reason: 'end_turn',+ usage: { input_tokens: 30, output_tokens: 200, cache_read_input_tokens: 10 },+ });+ queue.end();+ const events: AgentEvent[] = [];+ for await (const event of queue) events.push(event);+ const statuses = events.filter((event) => event.type === 'status');+ expect(statuses.filter((event) => event.data.outputTokens === 100)).toHaveLength(5);+ for (const event of statuses.filter((event) => event.data.outputTokens === 100)) {+ expect(event.data.generationDurationMs).toBe(1_000);+ }+ expect(statuses.at(-1)?.data).toMatchObject({+ status: 'Done', outputTokens: 200, generationDurationMs: 6_000, generationReliable: true,+ });+ });++ it('keeps the last paired rate when the matching final result is delayed', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000);+ const ctx = createTranslatorCtx();+ const queue = createAsyncQueue<AgentEvent>();+ translateSdkMessage({ type: 'stream_event', event: {+ type: 'message_start', message: { usage: { input_tokens: 10 } },+ } }, queue, ctx);+ vi.setSystemTime(2_000);+ translateSdkMessage({ type: 'stream_event', event: {+ type: 'message_delta', usage: { output_tokens: 100 },+ } }, queue, ctx);+ vi.setSystemTime(12_000);+ translateSdkMessage({ type: 'result', stop_reason: 'end_turn',+ usage: { input_tokens: 10, output_tokens: 100 },+ }, queue, ctx);+ queue.end();+ const events: AgentEvent[] = [];+ for await (const event of queue) events.push(event);+ const statuses = events.filter((event) => event.type === 'status');+ for (const event of statuses.slice(-2)) {+ expect(event.data).toMatchObject({+ outputTokens: 100, generationDurationMs: 1_000, generationReliable: true,+ });+ }+ expect(statuses.at(-1)?.data).toMatchObject({ status: 'Done', generationActive: false });+ });++ it.each([false, true])('ignores background child tool timing (assistant envelope: %s)', async (hasEnvelope) => {+ vi.useFakeTimers();+ vi.setSystemTime(1_000);+ const ctx = createTranslatorCtx();+ const queue = createAsyncQueue<AgentEvent>();+ const send = (message: Parameters<typeof translateSdkMessage>[0]) =>+ translateSdkMessage(message, queue, ctx);+ send({ type: 'stream_event', event: { type: 'message_start', message: {} } });+ send({ type: 'stream_event', event: {+ type: 'content_block_start', index: 0,+ content_block: { type: 'tool_use', id: 'bg-agent', name: 'Agent', input: {} },+ } });+ vi.setSystemTime(1_800);+ send({ type: 'stream_event', event: { type: 'message_delta', usage: { output_tokens: 80 } } });+ vi.setSystemTime(2_200);+ send({ type: 'user', message: { content: [+ { type: 'tool_result', tool_use_id: 'bg-agent', content: 'async_launched' },+ ] } });+ vi.setSystemTime(3_000);+ send({ type: 'stream_event', event: { type: 'message_start', message: {} } });+ vi.setSystemTime(3_400);+ send({ type: 'stream_event', parent_tool_use_id: 'bg-agent',+ event: { type: 'message_start', message: {} } });+ if (hasEnvelope) {+ send({ type: 'assistant', parent_tool_use_id: 'bg-agent', message: { content: [+ { type: 'tool_use', id: 'child-bash', name: 'Bash', input: { command: 'sleep 10' } },+ ] } });+ }+ expect(ctx.rt.generation.startedAt).toBe(2_200);+ expect(ctx.rt.generation.pendingToolIds.size).toBe(0);+ vi.setSystemTime(13_400);+ send({ type: 'user', parent_tool_use_id: 'bg-agent', message: { content: [+ { type: 'tool_result', tool_use_id: 'child-bash', content: 'child done' },+ ] } });+ expect(ctx.rt.generation.startedAt).toBe(2_200);+ expect(ctx.rt.generation.reliable).toBe(true);+ vi.setSystemTime(14_000);+ send({ type: 'stream_event', event: { type: 'message_delta', usage: { output_tokens: 1_180 } } });+ queue.end();+ const events: AgentEvent[] = [];+ for await (const event of queue) events.push(event);+ expect(events.filter((event) => event.type === 'status').at(-1)?.data).toMatchObject({+ outputTokens: 1_260,+ generationDurationMs: 12_600,+ generationReliable: true,+ });+ expect(events).toContainEqual(expect.objectContaining({+ type: 'tool_result_full', data: { toolUseId: 'child-bash', fullText: 'child done' },+ }));+ if (hasEnvelope) {+ expect(events).toContainEqual(expect.objectContaining({+ type: 'tool_use', data: expect.objectContaining({ toolUseId: 'child-bash' }),+ }));+ }+ resetClaudeGenerationTiming(ctx.rt.generation);+ });+it('keeps parent timing reliable for a complete subagent assistant without message_delta', () => {vi.useFakeTimers();vi.setSystemTime(1_000);@@ -693,8 +839,9 @@ describe('claude generation pause boundaries', () => {);expect(generating[1]?.data).toMatchObject({outputTokens: 0,- generationReliable: false,+ generationReliable: true,});+ expect(generating[1]?.data).not.toHaveProperty('generationDurationMs');expect(generating.at(-1)?.data).toMatchObject({outputTokens: 80,generationReliable: true,@@ -711,7 +858,7 @@ describe('claude generation pause boundaries', () => {vi.useRealTimers();});- it('hides live tok/s until the current parent request streams output', async () => {+ it('retains the last paired parent sample until the next request reports output', async () => {vi.useFakeTimers();vi.setSystemTime(1_000);const ctx = createTranslatorCtx();@@ -874,9 +1021,12 @@ describe('claude generation pause boundaries', () => {);const pendingCurrentParent = generating.filter((event) => {const data = event.data as { outputTokens?: number; generationReliable?: boolean };- return data.outputTokens === 80 && data.generationReliable === false;+ return data.outputTokens === 80;});expect(pendingCurrentParent.length).toBeGreaterThan(0);+ for (const event of pendingCurrentParent) {+ expect(event.data).toMatchObject({ generationReliable: true, generationDurationMs: 800 });+ }expect(generating.at(-1)?.data).toMatchObject({outputTokens: 120,generationReliable: true,@@ -1731,7 +1881,7 @@ describe('claude generation pause boundaries', () => {outputTokens: 150,generationReliable: true,generationActive: false,- generationDurationMs: 1_300,+ generationDurationMs: 1_000,});resetClaudeGenerationTiming(ctx.rt.generation);vi.useRealTimers();diff --git a/packages/maker-core/src/agents/claude-code/generation-timing.ts b/packages/maker-core/src/agents/claude-code/generation-timing.tsindex 4a1e1a0c7a..ec16960afb 100644--- a/packages/maker-core/src/agents/claude-code/generation-timing.ts+++ b/packages/maker-core/src/agents/claude-code/generation-timing.ts@@ -4,6 +4,8 @@ const CLAUDE_GENERATION_SUSPEND_GAP_MS = 30_000;export interface ClaudeGenerationState {startedAt: number | null;durationMs: number;+ /** Model time sampled with the latest parent output usage. */+ outputDurationMs: number;pendingToolIds: Set<string>;/*** Pause ids that already resumed this generation. A later pause of the same@@ -31,6 +33,7 @@ export function newClaudeGenerationState(): ClaudeGenerationState {return {startedAt: null,durationMs: 0,+ outputDurationMs: 0,pendingToolIds: new Set(),settledPauseIds: new Set(),reliable: true,@@ -85,6 +88,7 @@ export function resetClaudeGenerationTiming(state: ClaudeGenerationState): voidstate.pendingToolIds.clear();state.settledPauseIds.clear();state.durationMs = 0;+ state.outputDurationMs = 0;state.reliable = true;state.sawSubagent = false;state.parentStreamedOutputIncomplete = false;diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.tsindex 768179087b..37a6052db2 100644--- a/packages/maker-core/src/agents/claude-code/translator.ts+++ b/packages/maker-core/src/agents/claude-code/translator.ts@@ -37,7 +37,7 @@ import {} from '../shared/context-overflow-error.js';import type { UsageTracker } from '../shared/usage-tracker.js';import { isModelAccessDenied } from './model-access-error.js';-import { attachLiveGeneration } from '../shared/live-generation-snapshot.js';+import { attachLiveGeneration, sampleGenerationDuration } from '../shared/live-generation-snapshot.js';import {beginClaudeGeneration,beginClaudeGenerationAtRequestStart,@@ -266,18 +266,6 @@ function applySubagentLiveReliability(ctx: TranslateContext): void {}}-/**- * Snapshot-only: the current parent generation interval has no streamed output- * yet. Hide this status without sticky-failing `generation.reliable`, so a- * later parent `message_delta` can restore tok/s.- */-function currentParentStreamedOutputPending(ctx: TranslateContext): boolean {- if (!ctx.rt.generation.sawSubagent) return false;- if (mainActiveSegmentHasOutput(ctx)) return false;- if (ctx.rt.generation.startedAt !== null) return true;- return Boolean(ctx.rt.activeUsageSegmentByParent.get(CLAUDE_MAIN_USAGE_PARENT));-}-function liveParentOutputTokens(ctx: TranslateContext,resultOutput?: number,@@ -294,6 +282,9 @@ function liveParentOutputTokens(return mainOutput;}if (typeof resultOutput === 'number' && Number.isFinite(resultOutput)) {+ // A first aggregate after resume may include historical output. Keep the+ // accounting total, but never divide it by this turn's generation time.+ if (!streamedOutputMatchesResult) markClaudeGenerationUnreliable(ctx.rt.generation);return Math.max(0, resultOutput);}return mainOutput;@@ -309,9 +300,9 @@ function ccLiveStatus(status,...attachLiveGeneration(ctx.tracker.snapshot(), {outputTokens: mainTurnOutputTokens(ctx.tracker),- closedDurationMs: ctx.rt.generation.durationMs,+ durationMs: ctx.rt.generation.outputDurationMs,openStartedAt: ctx.rt.generation.startedAt,- reliable: ctx.rt.generation.reliable && !currentParentStreamedOutputPending(ctx),+ reliable: ctx.rt.generation.reliable,}),isRunning,};@@ -852,7 +843,7 @@ export function translateSdkMessage(}}for (const toolUseId of completedToolUseIds) {- resumeClaudeGeneration(ctx.rt.generation, toolUseId);+ if (!parentToolUseId) resumeClaudeGeneration(ctx.rt.generation, toolUseId);ctx.rt.toolUseIdToName.delete(toolUseId);}if (completedToolUseIds.size > 0) {@@ -1515,7 +1506,7 @@ function handleAssistant(const toolUseId = rememberClaudeToolUseId(ctx, block.id, block.name);if (toolUseId) {// 完整 assistant 消息已带工具参数,即使没有 stream_event 也可在此停表。- pauseClaudeGenerationForToolUse(ctx, toolUseId);+ if (!parentToolUseId) pauseClaudeGenerationForToolUse(ctx, toolUseId);ctx.onToolUseStart?.(toolUseId, block.name, block.input, parentToolUseId);}queue.push({@@ -1764,6 +1755,7 @@ function handleStreamEvent('cache_read_input_tokens','cache_creation_input_tokens',].every((field) => Object.prototype.hasOwnProperty.call(usage, field));+ const previousOutput = ctx.tracker.getTurnUsage().output;ctx.tracker.upsertApiCallUsage(segmentId, {id: segmentId,model: streamModel ?? ctx.getModel(),@@ -1775,6 +1767,14 @@ function handleStreamEvent(complete: hasCompleteUsageSnapshot,});if (parentToolUseId) noteClaudeSubagent(ctx.rt.generation);+ else if (ctx.tracker.getTurnUsage().output > previousOutput) {+ // Upserts retain the largest output count. Input-only, duplicate, and+ // older usage must not advance the paired denominator on their own.+ ctx.rt.generation.outputDurationMs = sampleGenerationDuration(+ ctx.rt.generation.durationMs,+ ctx.rt.generation.startedAt,+ );+ }// 每次 API 回合的 token 增量打一行 —— 一个 turn 可能多个 message_delta(工具循环),// 让人看日志能直观看到 token 是怎么涨上去的, 而不是只在 turn end 看到一个总数。ctx.log.debug('SDK ▷ token usage (message_delta)', {@@ -2381,7 +2381,7 @@ function handleResult(status: 'Done',...attachLiveGeneration(endSnapshot, {outputTokens: liveTurnOutput,- closedDurationMs: liveGeneration.durationMs,+ durationMs: liveGeneration.outputDurationMs,openStartedAt: null,reliable: liveGeneration.reliable,}),diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 90f80b189e..57b2de5c68 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -17024,6 +17024,87 @@ describe('CodexAgent MCP thread context hooks', () => {}});+ it.each([0, 10])('keeps output paired through input-only usage (cached=%s) and resets next turn', async (cachedInputTokens) => {+ let now = 1_000;+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);+ const agent = new CodexAgent(createDeps());+ let turnSeq = 0;+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) return { turn: { id: `turn-${++turnSeq}` } };+ if (method === Method.TurnInterrupt) return {};+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: 'session-paired-generation-sample', model: 'gpt-5.4', workingDir: '/repo',+ });+ try {+ const handlers = host.getThreadHandlers()!;+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ await handle.send({ type: 'user', content: 'two requests' });+ handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });+ now = 2_000;+ handlers.tokenUsageUpdated!({+ threadId: 'start-thread-id', turnId: 'turn-1', tokenUsage: {+ total: { totalTokens: 110, inputTokens: 10, outputTokens: 100, cachedInputTokens: 0 },+ last: { inputTokens: 10, outputTokens: 100, cachedInputTokens: 0 },+ },+ });+ const expectSample = (outputTokens: number, generationDurationMs: number) =>+ expect(handle.getUsageSnapshot()).toMatchObject({+ outputTokens, generationDurationMs, generationReliable: true,+ });+ expectSample(100, 1_000);+ const tool = { id: 'tool-1', type: 'mcpToolCall', server: 'test', tool: 'read', arguments: {} };+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'turn-1', item: tool });+ now = 6_000;+ handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'turn-1', item: tool });+ now = 10_000;+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'turn-1',+ item: { id: 'reasoning-2', type: 'reasoning', summary: [], content: [] } });+ // No second usage yet: 100 / 1s, never 100 / 5s.+ expectSample(100, 1_000);+ handlers.tokenUsageUpdated!({+ threadId: 'start-thread-id', turnId: 'turn-1', tokenUsage: {+ total: { totalTokens: 120, inputTokens: 20, outputTokens: 100, cachedInputTokens },+ last: { inputTokens: 10, outputTokens: 0, cachedInputTokens },+ },+ });+ expectSample(100, 1_000);+ expect(handle.getUsageSnapshot().tokenUsage).toBe(120 - cachedInputTokens);+ handlers.tokenUsageUpdated!({+ threadId: 'start-thread-id', turnId: 'turn-1', tokenUsage: {+ total: { totalTokens: 530, inputTokens: 30, outputTokens: 500, cachedInputTokens },+ last: { inputTokens: 10, outputTokens: 400, cachedInputTokens: 0 },+ },+ });+ expectSample(500, 5_000);+ now = 11_000;+ handlers.tokenUsageUpdated!({+ threadId: 'start-thread-id', turnId: 'turn-1', tokenUsage: {+ total: { totalTokens: 540, inputTokens: 40, outputTokens: 500, cachedInputTokens },+ last: { inputTokens: 10, outputTokens: 0, cachedInputTokens: 0 },+ },+ });+ expectSample(500, 5_000);+ expect(handle.getUsageSnapshot().tokenUsage).toBe(540 - cachedInputTokens);+ handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: 'turn-1', status: 'completed' } });+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));+ expect(events.find((event) => event.type === 'done')?.data.usage.durationMs).toBe(5_000);+ expect(events.filter((event) => event.type === 'status').at(-1)?.data).toMatchObject({+ status: 'Done', outputTokens: 500, generationDurationMs: 5_000,+ });+ await handle.send({ type: 'user', content: 'next turn' });+ expect(handle.getUsageSnapshot().outputTokens).toBe(0);+ expect(handle.getUsageSnapshot()).not.toHaveProperty('generationDurationMs');+ } finally {+ await handle.close();+ nowSpy.mockRestore();+ }+ });+it('attaches throttled token usage to the Done snapshot without an extra running frame', async () => {let now = 1_000;const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);@@ -17083,7 +17164,7 @@ describe('CodexAgent MCP thread context hooks', () => {expect(doneStatus?.data).toMatchObject({isRunning: false,outputTokens: 40,- generationDurationMs: 250,+ generationDurationMs: 150,});await handle.close();diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 51eb8a187a..1dc119ebce 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -99,7 +99,7 @@ import {} from '../shared/auto-review-decision.js';import { reviewAction, type ReviewableAction } from '../shared/auto-review.js';import { UsageTracker } from '../shared/usage-tracker.js';-import { attachLiveGeneration } from '../shared/live-generation-snapshot.js';+import { attachLiveGeneration, sampleGenerationDuration } from '../shared/live-generation-snapshot.js';import { getDefaultImageResizer } from '../shared/image-resizer.js';import { formatManagedImageReferences } from '../shared/managed-image-reference.js';import { REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS } from '../shared/sensitive-credential-paths.js';@@ -3178,7 +3178,7 @@ export class CodexAgent extends BaseAgent {const translatorRt: CodexRuntimeState = newCodexRuntimeState();const liveUsageSnapshot = () => attachLiveGeneration(usageTracker.snapshot(), {outputTokens: usageTracker.getTurnUsage().output,- closedDurationMs: translatorRt.generationDurationMs,+ durationMs: translatorRt.generationOutputDurationMs,openStartedAt: translatorRt.generationStartedAt,reliable: translatorRt.generationTimingReliable,});@@ -9448,7 +9448,13 @@ export class CodexAgent extends BaseAgent {),cachedTokens: realTurnUsage.cacheRead,segments: realTurnUsageSegments,- ...(generationDurationMs !== undefined ? { durationMs: generationDurationMs } : {}),+ // With usage, exclude post-output finalization. Without usage, retain+ // the measured duration metadata (zero output cannot produce a rate).+ ...(generationDurationMs !== undefined ? {+ durationMs: realTurnUsage.output > 0+ ? translatorRt.generationOutputDurationMs || undefined+ : generationDurationMs,+ } : {}),...(typeof turn.durationMs === 'number' && Number.isFinite(turn.durationMs)? { turnDurationMs: turn.durationMs }: {}),@@ -9648,7 +9654,7 @@ export class CodexAgent extends BaseAgent {status: 'Done',...attachLiveGeneration(endSnap, {outputTokens: realTurnUsage.output,- closedDurationMs: translatorRt.generationDurationMs,+ durationMs: translatorRt.generationOutputDurationMs,openStartedAt: null,reliable: translatorRt.generationTimingReliable,}),@@ -10743,6 +10749,14 @@ export class CodexAgent extends BaseAgent {? 'priority': 'standard',});+ // Input/cache-only segments still belong in the ledger, but cannot+ // pair already reported output with a later generation denominator.+ if (last.outputTokens > 0) {+ translatorRt.generationOutputDurationMs = sampleGenerationDuration(+ translatorRt.generationDurationMs,+ translatorRt.generationStartedAt,+ );+ }maybePushUsageRefresh();// Maker Memory flush 观察 (A 轻版: 只打日志). makerMemoryEnabled 关时 controller 为 null。if (memoryFlushController) {diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex dc1dd0619f..2bd66ece7a 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -85,6 +85,8 @@ export interface CodexRuntimeState {generationPendingToolIds: Set<string>;/** Sum of model-active intervals for the current turn, including TTFT and thinking. */generationDurationMs: number;+ /** Model time sampled with the latest accepted output usage. */+ generationOutputDurationMs: number;generationTurnId: string | null;/** False when a tool boundary is incomplete/out of order; unreliable TPS is omitted. */generationTimingReliable: boolean;@@ -130,6 +132,7 @@ export function newCodexRuntimeState(): CodexRuntimeState {generationStartedAt: null,generationPendingToolIds: new Set(),generationDurationMs: 0,+ generationOutputDurationMs: 0,generationTurnId: null,generationTimingReliable: true,generationHeartbeatAt: null,@@ -181,6 +184,7 @@ export function resetCodexGenerationTiming(rt: CodexRuntimeState): void {rt.generationStartedAt = null;rt.generationPendingToolIds.clear();rt.generationDurationMs = 0;+ rt.generationOutputDurationMs = 0;rt.generationTurnId = null;rt.generationTimingReliable = true;}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.tsindex 3ceb53ba4b..5479a67ce0 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@@ -1325,7 +1325,43 @@ describe('pi translator', () => {]);});- it('marks generation active on message_start so the UI can tick live TPS', () => {+ it('retains the completed output/time pair throughout the next streamed message', () => {+ const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(1_000);+ const ctx = createPiTranslateContext(noopLogger);+ const { queue } = makeQueue();+ try {+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ translatePiEvent(ev({ type: 'message_start', message: { role: 'assistant' } }), queue, ctx);+ nowSpy.mockReturnValue(11_000);+ translatePiEvent(ev({ type: 'message_end', message: {+ role: 'assistant', content: [], usage: { input: 10, output: 1_000 }, duration: 10_000,+ } }), queue, ctx);+ nowSpy.mockReturnValue(21_000);+ translatePiEvent(ev({ type: 'message_start', message: { role: 'assistant' } }), queue, ctx);+ nowSpy.mockReturnValue(31_000);+ translatePiEvent(ev({ type: 'message_update', assistantMessageEvent: {+ type: 'text_delta', contentIndex: 0, delta: 'still generating',+ } }), queue, ctx);+ expect(usageSnapshotOf(ctx)).toMatchObject({+ outputTokens: 1_000, generationDurationMs: 10_000, generationActive: true,+ });+ translatePiEvent(ev({ type: 'message_end', message: {+ role: 'assistant', content: [], usage: { input: 10, output: 1_000 }, duration: 10_000,+ } }), queue, ctx);+ expect(usageSnapshotOf(ctx)).toMatchObject({+ outputTokens: 2_000, generationDurationMs: 20_000, generationActive: false,+ });+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ expect(usageSnapshotOf(ctx).outputTokens).toBe(0);+ expect(usageSnapshotOf(ctx)).not.toHaveProperty('generationDurationMs');+ } finally {+ disposePiTranslateContext(ctx);+ nowSpy.mockRestore();+ }+ });++ it('marks generation active on message_start without advancing sampled usage', () => {const ctx = createPiTranslateContext(noopLogger);const { queue, events } = makeQueue();translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex 7af0a8314d..139f1b528f 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -339,7 +339,8 @@ export function usageSnapshotOf(ctx: PiTranslateContext): UsageSnapshot {},{outputTokens: ctx.turnOutput,- closedDurationMs: ctx.generationDurationMs,+ // Pi reports output only at message_end, alongside the closed duration.+ durationMs: ctx.generationDurationMs,openStartedAt: ctx.generationOpenAt > 0 ? ctx.generationOpenAt : null,reliable: ctx.generationTimingReliable && ctx.generationHeartbeatReliable,},@@ -675,8 +676,7 @@ export function translatePiEvent(const bridgedPriceVariant = priceVariantFromServiceTier(message?.usage?.service_tier);ctx.pendingPriceVariants.push(bridgedPriceVariant ?? ctx.getPriceVariant?.() ?? 'standard');startPiGenerationHeartbeat(ctx);- // Tell the UI generation is active so it can tick the TPS denominator- // locally between sparse message_end usage reports.+ // Activity may advance before usage; the rate retains the last completed sample.pushStatus(queue, ctx, 'Working…', true);return;}diff --git a/packages/maker-core/src/agents/shared/live-generation-snapshot.test.ts b/packages/maker-core/src/agents/shared/live-generation-snapshot.test.tsindex 8f09468a6b..a892a714b3 100644--- a/packages/maker-core/src/agents/shared/live-generation-snapshot.test.ts+++ b/packages/maker-core/src/agents/shared/live-generation-snapshot.test.ts@@ -1,6 +1,6 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { attachLiveGeneration } from './live-generation-snapshot.js';+import { attachLiveGeneration, sampleGenerationDuration } from './live-generation-snapshot.js';const base = {tokenUsage: 120,@@ -14,7 +14,7 @@ describe('attachLiveGeneration', () => {expect(attachLiveGeneration(base, {outputTokens: 40,- closedDurationMs: 1_000,+ durationMs: 1_000,openStartedAt: 10_000,reliable: false,}),@@ -26,14 +26,13 @@ describe('attachLiveGeneration', () => {});});- it('adds closed duration plus the open interval', () => {+ it('captures closed duration plus the open interval when usage arrives', () => {expect(attachLiveGeneration(base, {outputTokens: 50,- closedDurationMs: 1_000,+ durationMs: sampleGenerationDuration(1_000, 8_000, 8_250),openStartedAt: 8_000,reliable: true,- now: 8_250,}),).toEqual({...base,@@ -48,10 +47,9 @@ describe('attachLiveGeneration', () => {expect(attachLiveGeneration(base, {outputTokens: 0,- closedDurationMs: 0,+ durationMs: 0,openStartedAt: 5_000,reliable: true,- now: 5_000,}),).toEqual({...base,@@ -60,4 +58,26 @@ describe('attachLiveGeneration', () => {generationActive: true,});});++ it('retains the paired usage duration while a later request is in flight', () => {+ const timing = {+ outputTokens: 100,+ durationMs: 1_000,+ openStartedAt: 8_000,+ reliable: true,+ };+ const nowSpy = vi.spyOn(Date, 'now');+ try {+ for (const now of [8_000, 12_000, 18_000]) {+ nowSpy.mockReturnValue(now);+ expect(attachLiveGeneration(base, timing)).toMatchObject({+ outputTokens: 100,+ generationDurationMs: 1_000,+ generationActive: true,+ });+ }+ } finally {+ nowSpy.mockRestore();+ }+ });});diff --git a/packages/maker-core/src/agents/shared/live-generation-snapshot.ts b/packages/maker-core/src/agents/shared/live-generation-snapshot.tsindex 9ccaa75544..be8802c8a0 100644--- a/packages/maker-core/src/agents/shared/live-generation-snapshot.ts+++ b/packages/maker-core/src/agents/shared/live-generation-snapshot.ts@@ -3,13 +3,12 @@ import type { UsageSnapshot } from '../../types/events.js';export interface LiveGenerationTiming {/** Turn-cumulative output tokens, including reasoning. */outputTokens: number;- /** Closed model-active intervals for this turn. */- closedDurationMs: number;+ /** Duration captured with outputTokens; sparse usage must not include later in-flight time. */+ durationMs: number;/** Open interval start, or null while tools/user waits own the turn. */openStartedAt: number | null;/** False when any output lacks a compatible generation-only denominator. */reliable: boolean;- now?: number;}/**@@ -36,22 +35,24 @@ export function attachLiveGeneration(};}- const now = timing.now ?? Date.now();- const closed =- typeof timing.closedDurationMs === 'number' && Number.isFinite(timing.closedDurationMs)- ? Math.max(0, timing.closedDurationMs)- : 0;- const openMs =- timing.openStartedAt != null && Number.isFinite(timing.openStartedAt)- ? Math.max(0, now - timing.openStartedAt)- : 0;- const generationDurationMs = closed + openMs;+ const generationDurationMs = timing.durationMs;const generationActive = timing.openStartedAt != null && Number.isFinite(timing.openStartedAt);return {...next,generationReliable: true,generationActive,- ...(generationDurationMs > 0 ? { generationDurationMs } : {}),+ ...(Number.isFinite(generationDurationMs) && generationDurationMs > 0+ ? { generationDurationMs }+ : {}),};}++/** Capture the cumulative model time at the same boundary as an output-usage update. */+export function sampleGenerationDuration(+ closedDurationMs: number,+ openStartedAt: number | null,+ now = Date.now(),+): number {+ return closedDurationMs + (openStartedAt === null ? 0 : Math.max(0, now - openStartedAt));+}