Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): pair speed counters across native continuations
Chris4020ec7e7aaa
diff --git a/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts b/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.tsindex a3f8100bdc..3b5be28109 100644--- a/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts+++ b/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts@@ -96,7 +96,7 @@ describe('running speed history', () => {expect(next.samples.at(-1)?.rate).toBe(50);});- it('bounds samples and excludes evicted samples from the observed peak', () => {+ it('bounds chart samples without losing the turn peak', () => {let history = recordRunningTokenRate(begin(), {...input,outputTokens: 1000,@@ -110,7 +110,7 @@ describe('running speed history', () => {});}expect(history.samples).toHaveLength(60);- expect(history.peak).toBe(1);+ expect(history.peak).toBe(1000);expect(history.samples[0].durationMs).toBe(141000);});});@@ -343,7 +343,7 @@ describe('host token speed (Pi extension algorithm)', () => {expect(history.samples.map((sample) => sample.durationMs)).toEqual([1200]);history = recordTokenSpeed(history, { startedAt: 1, speed: speed(70, 2300), now: 40 });expect(history.samples.map((sample) => sample.rate)).toEqual([90, 70]);- expect(history.peak).toBe(90);+ expect(history.peak).toBe(95);expect(history.latestRate).toBe(70);});@@ -364,6 +364,21 @@ describe('host token speed (Pi extension algorithm)', () => {expect(recordTokenSpeed(measured, { startedAt: 2, speed: speed(0, 100) }).latestRate).toBeNull();});+ it('restores the host peak after reconnect and resets it with a new product turn', () => {+ const snapshot = readTokenSpeedSnapshot({ ...speed(37.7, 10_000), peak: 100 })!;+ let history = recordTokenSpeed(emptyRateHistory(null), { startedAt: 1, speed: snapshot });+ expect(history.peak).toBe(100);+ for (let i = 2; i <= 70; i++) {+ history = recordTokenSpeed(history, { startedAt: 1, speed: speed(37.7, i * 10_000) });+ }+ expect(history.samples).toHaveLength(60);+ expect(history.peak).toBe(100);+ saveCachedRateHistory('continuation-peak', history);+ history = recordTokenSpeed(loadCachedRateHistory('continuation-peak')!, { startedAt: 2, speed: speed(20, 1_000) });+ expect(history.peak).toBe(20);+ clearRateHistoryCache();+ });+it('accepts only well-formed host snapshots', () => {expect(readTokenSpeedSnapshot(speed(10, 1000))).toEqual(speed(10, 1000));expect(readTokenSpeedSnapshot({ rate: 10 })).toBeUndefined();diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex a5b7f0fc39..17da2262a4 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -348,6 +348,14 @@ schema、数据库或 Mobile 原生指纹。完整管理需要两端客户端更`generationReliable: false`,客户端据此丢弃已保留的速度。无需服务端更新、新通道、权限或数据库 migration。+Codex 的速度累计独立于计费桶:同一产品轮次中的原生接续保留已配对的输出与时长,+用户新消息同时清零;原生 turn 的测速源计数从零开始。计时未增加但输出增加的区间不进入+速度分子或分母,暂时发 `generationReliable: false`,下一个有效区间恢复;费用仍完整记账。+旧客户端使用的 `outputTokens` / `generationDurationMs` 与速度快照同源,不能用计费桶+补速度分子。若某个原生 turn 丢失过配对区间,其结束用量不附完整输出的生成时长。+`tokenSpeed.peak` 是新增可选字段,保存产品轮次内已测最近速度的峰值;新端跨重连读取,+曲线裁剪不再丢峰值。旧主机没有它时使用客户端已观察到的峰值,旧客户端忽略此字段。+## 任务列表提前同步聊天正文同账号控制端声明 `session-list-messages-v1` 后,`sessions` 订阅同时接收普通用户/助手diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex b6e7472837..a3d2114aba 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -19104,6 +19104,80 @@ describe('CodexAgent MCP thread context hooks', () => {}});+ // Regression: native turn activation reset time while the ledger could still+ // contain prior output; tool-paused usage could inflate its numerator alone.+ // Unit through CodexAgent: public status and billing totals must stay distinct.+ it('pairs native continuation output and recovers frozen-clock samples without changing billing', async () => {+ 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-speed-continuation', 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: 'work' });+ const usage = (turnId: string, output: number, total: number) => handlers.tokenUsageUpdated!({+ threadId: 'start-thread-id', turnId, tokenUsage: {+ last: { inputTokens: 10, cachedInputTokens: 0, outputTokens: output },+ total: { totalTokens: total, inputTokens: 10, cachedInputTokens: 0, outputTokens: total - 10 },+ },+ });+ handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });+ now = 11_000;+ usage('turn-1', 1_000, 1_010);+ expect(handle.getUsageSnapshot().tokenSpeed).toMatchObject({ tokens: 1_000, elapsedMs: 10_000 });+ const yielded = { id: 'yielded-tool', type: 'commandExecution', command: 'test', status: 'inProgress' };+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'turn-1', item: yielded });+ handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'turn-1', item: {+ ...yielded, status: 'completed', aggregatedOutput: 'Script running with cell ID 226\nWall time 1.0 seconds\nOutput:\n',+ } });+ handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: 'turn-1', status: 'completed' } });+ await waitForExpectation(() => expect(events.some(event => event.type === 'done')).toBe(true));+ expect(handle.beginTurnContinuationWait?.(events.find(event => event.type === 'done')?.turnContinuationId)).toBe('active');+ await waitForExpectation(() => expect(turnSeq).toBe(2));+ handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'turn-2' } });+ expect(handle.getUsageSnapshot().generationReliable).toBe(false);+ now = 13_000;+ usage('turn-2', 200, 1_220);+ expect(handle.getUsageSnapshot()).toMatchObject({+ outputTokens: 1_200, generationDurationMs: 12_000,+ tokenSpeed: { tokens: 1_200, elapsedMs: 12_000, average: 100 },+ });+ const tool = { id: 'background-tool', type: 'mcpToolCall', server: 'test', tool: 'wait', arguments: {} };+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'turn-2', item: tool });+ now = 15_000;+ usage('turn-2', 2_000_000, 2_001_230);+ expect(handle.getUsageSnapshot().tokenSpeed).toBeUndefined();+ expect(handle.getUsageSnapshot().generationReliable).toBe(false);+ handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'turn-2', item: tool });+ now = 25_000;+ usage('turn-2', 377, 2_001_617);+ expect(handle.getUsageSnapshot()).toMatchObject({+ outputTokens: 1_577, generationDurationMs: 22_000, generationReliable: true,+ tokenSpeed: { tokens: 1_577, elapsedMs: 22_000, rate: 37.7, peak: 100 },+ });+ expect(handle.getUsageSnapshot().tokenUsage).toBe(2_000_607);+ handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: 'turn-2', status: 'completed' } });+ await handle.send({ type: 'user', content: 'new user turn' });+ handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'turn-3' } });+ now = 35_000;+ usage('turn-3', 377, 2_002_004);+ expect(handle.getUsageSnapshot().tokenSpeed).toMatchObject({ tokens: 377, elapsedMs: 10_000, average: 37.7, peak: 37.7 });+ } 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);diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 11e22dc2b0..5a5c3e37b6 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -3784,13 +3784,18 @@ assertRouteCurrent();const eventQueue: AsyncQueue<AgentEvent> = createAsyncQueue<AgentEvent>();const usageTracker = new UsageTracker();const translatorRt: CodexRuntimeState = newCodexRuntimeState();- const liveUsageSnapshot = () => attachLiveGeneration(usageTracker.snapshot(), {- tokenSpeed: translatorRt.generationTimingReliable ? translatorRt.tokenSpeed.snapshot() : undefined,- outputTokens: usageTracker.getTurnUsage().output,- durationMs: translatorRt.generationOutputDurationMs,- openStartedAt: translatorRt.generationStartedAt,- reliable: translatorRt.generationTimingReliable,- });+ const liveUsageSnapshot = () => {+ const speed = translatorRt.generationTimingReliable ? translatorRt.tokenSpeed.snapshot() : undefined;+ return attachLiveGeneration(usageTracker.snapshot(), {+ tokenSpeed: speed,+ // Legacy clients use these fields: they must share the speed snapshot's+ // measured numerator/denominator, never the billing ledger's lifetime.+ outputTokens: speed?.tokens ?? translatorRt.generationOutputTokens,+ durationMs: speed?.elapsedMs ?? 0,+ openStartedAt: translatorRt.generationStartedAt,+ reliable: speed !== undefined,+ });+ };/*** 本 turn 用于**目录查找**的模型 id, 在构造 turnParams 时快照(取 mutableCatalogModel,* 不是送上游的 wire 值 —— 见该变量注释)。@@ -8730,7 +8735,7 @@ assertRouteCurrent();}}- resetCodexGenerationTiming(translatorRt);+ resetCodexGenerationTiming(translatorRt, true);turnDiffSnapshots.clear();translatorRt.samplingSegments.clear();proposedPlanText = null;@@ -11189,7 +11194,8 @@ assertRouteCurrent();const realTurnUsageSegments = usageTracker.getTurnUsageSegments();finalizeCodexGenerationTurn(translatorRt, turn.id);translatorRt.tokenSpeed.stop();- const generationDurationMs = codexGenerationDurationMs(translatorRt);+ const generationDurationMs = translatorRt.tokenSpeed.isSegmentComplete()+ ? codexGenerationDurationMs(translatorRt) : undefined;const codexDoneUsage = {promptTokens: realTurnUsage.input,completionTokens: realTurnUsage.output,@@ -11414,13 +11420,7 @@ assertRouteCurrent();type: 'status',data: {status: 'Done',- ...attachLiveGeneration(endSnap, {- tokenSpeed: translatorRt.generationTimingReliable ? translatorRt.tokenSpeed.snapshot() : undefined,- outputTokens: realTurnUsage.output,- durationMs: translatorRt.generationOutputDurationMs,- openStartedAt: null,- reliable: translatorRt.generationTimingReliable,- }),+ ...liveUsageSnapshot(),isRunning: false,},source: 'codex',@@ -12477,13 +12477,14 @@ assertRouteCurrent();// 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.generationOutputTokens += last.outputTokens;translatorRt.generationOutputDurationMs = sampleGenerationDuration(translatorRt.generationDurationMs,translatorRt.generationStartedAt,);if (translatorRt.generationTimingReliable) {translatorRt.tokenSpeed.recordUsage(- usageTracker.getTurnUsage().output,+ translatorRt.generationOutputTokens,translatorRt.generationOutputDurationMs,);} else {@@ -13328,6 +13329,7 @@ assertRouteCurrent();// 不再影响判定, 也不会再被别的 turn(含被 Stop 的旧 send 的孤儿)污染。const mySendGen = ++sendGeneration;isTurnStartPending = true;+ if (!isContinuation) translatorRt.tokenSpeed.reset();usageTracker.beginTurn();log.debug('send ▶ user message', {model: mutableModel,diff --git a/packages/maker-core/src/agents/codex/token-speed.native.test.ts b/packages/maker-core/src/agents/codex/token-speed.native.test.tsnew file mode 100644index 0000000000..1980706e2c--- /dev/null+++ b/packages/maker-core/src/agents/codex/token-speed.native.test.ts@@ -0,0 +1,244 @@+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { createServer } from 'node:http';+import assert from 'node:assert/strict';+import { it } from 'vitest';+import { CodexAgent } from './index.js';+import type { AgentSessionHandle } from '../base-agent.js';+import type { Logger } from '../../interfaces/logger.js';+import type { AgentEvent, UsageSnapshot } from '../../types/events.js';+// Integration tier: real Codex process + local Responses server, private home, no account.+// Existing unit handlers cannot verify native timing boundaries and tool execution.+it.skipIf(!process.env.CINDY_CODEX_TEST_BINARY)(+ 'measures real native tool turns and resets on a new user send',+ async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'cindy-speed-native-'));+ const home = path.join(root, 'codex');+ const workdir = path.join(root, 'work');+ await mkdir(home);+ await mkdir(workdir);+ const warnings: unknown[] = [];+ const logger: Logger = {+ trace() {},+ debug() {},+ info() {},+ warn(...a: unknown[]) {+ warnings.push(a);+ },+ error(...a: unknown[]) {+ warnings.push(a);+ },+ fatal() {},+ child() {+ return logger;+ },+ };+ let requests = 0;+ const server = createServer(async (req, res) => {+ for await (const _ of req) {+ /* drain local request */+ }+ if (!req.url?.endsWith('/responses')) {+ res.writeHead(404).end();+ return;+ }+ const n = ++requests;+ const item =+ n === 1+ ? {+ type: 'function_call',+ id: 'fc-1',+ call_id: 'tool-1',+ name: 'exec_command',+ arguments: JSON.stringify({+ cmd: 'node -e "setTimeout(()=>{},1000)"',+ yield_time_ms: 1000,+ }),+ status: 'completed',+ }+ : {+ type: 'message',+ id: `msg-${n}`,+ role: 'assistant',+ status: 'completed',+ content: [+ {+ type: 'output_text',+ text: 'Speed validation complete.',+ annotations: [],+ },+ ],+ };+ res.writeHead(200, {+ 'content-type': 'text/event-stream',+ connection: 'close',+ });+ const send = (event: unknown) =>+ res.write(`data: ${JSON.stringify(event)}\n\n`);+ send({+ type: 'response.created',+ response: { id: `r-${n}`, status: 'in_progress', output: [] },+ });+ // real-wait: integration tier measures native wall-clock generation against a local SSE server.+ await new Promise((r) => setTimeout(r, 1100));+ send({ type: 'response.output_item.done', output_index: 0, item });+ send({+ type: 'response.completed',+ response: {+ id: `r-${n}`,+ status: 'completed',+ output: [item],+ usage: { input_tokens: 10, output_tokens: 100, total_tokens: 110 },+ },+ });+ res.end();+ });+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));+ const address = server.address();+ assert(address && typeof address !== 'string');+ const endpoint = `http://127.0.0.1:${address.port}/v1`;+ const agent = new CodexAgent({+ binaryPath: process.env.CINDY_CODEX_TEST_BINARY!,+ logger,+ runtimeConfig: {},+ prepareCodexExtraSpawnConfig: async () => ({+ extraArgs: [+ '-c',+ 'model_provider="fixture"',+ '-c',+ `model_providers.fixture={name="Local speed validation",base_url="${endpoint}",wire_api="responses",requires_openai_auth=false,request_max_retries=0,supports_websockets=false}`,+ '-c',+ 'check_for_update_on_startup=false',+ '-c',+ 'analytics.enabled=false',+ '-c',+ 'features.code_mode=false',+ // Fresh profile: keep the adapter-disabled MCP transport syntactically valid.+ '-c',+ 'mcp_servers.cindy_memory={command="false",enabled=false}',+ ],+ extraEnv: {},+ }),+ auth: {+ getState: async () => ({ authenticated: true }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({+ HOME: root,+ USERPROFILE: root,+ CODEX_HOME: home,+ OPENAI_API_KEY: '',+ CODEX_API_KEY: '',+ NO_PROXY: '127.0.0.1,localhost',+ }),+ },+ });+ let handle: AgentSessionHandle | undefined;+ const events: AgentEvent[] = [];+ try {+ handle = await agent.startSession({+ sessionId: 'speed-native',+ model: 'gpt-6-astra',+ workingDir: workdir,+ permissionMode: 'bypassPermissions',+ makerMemoryEnabled: false,+ });+ let doneResolve: () => void = () => {};+ void (async () => {+ for await (const e of handle!.events()) {+ if (+ e.type === 'status' ||+ e.type === 'done' ||+ e.type === 'error' ||+ e.type === 'tool_use' ||+ e.type === 'tool_result'+ )+ events.push(e);+ if (e.type === 'done') doneResolve();+ }+ })();+ const run = async () => {+ const done = new Promise<void>((r) => (doneResolve = r));+ await handle!.send(+ { type: 'user', content: 'Run the tool and finish.' },+ { throwOnStartFailure: true },+ );+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ done,+ new Promise((_, reject) => {+ // real-wait: failure deadline for the native subprocess; successful runs cancel it.+ timer = setTimeout(+ () => reject(new Error('native turn timeout')),+ 20000,+ );+ }),+ ]);+ } finally {+ clearTimeout(timer);+ }+ };+ const startedAt = Date.now();+ await run();+ const firstWallMs = Date.now() - startedAt;+ const readings = () =>+ events.flatMap((e) => {+ const speed =+ e.type === 'status'+ ? (e.data as UsageSnapshot).tokenSpeed+ : undefined;+ return speed ? [speed] : [];+ });+ const first = readings().at(-1);+ assert(+ first && first.tokens === 200,+ JSON.stringify({ first, events, warnings }),+ );+ assert(+ first.elapsedMs >= 2000 && first.elapsedMs < 5000,+ JSON.stringify(first),+ );+ assert(+ firstWallMs - first.elapsedMs >= 800,+ 'tool wait must be excluded from generation time',+ );+ assert.equal(events.filter((e) => e.type === 'tool_use').length, 1);+ await run();+ const second = readings().at(-1);+ assert(second);+ assert.equal(second.tokens, 100);+ const evidence = {+ requests,+ first,+ second,+ tools: events.filter((e) => e.type === 'tool_use').map((e) => e.data),+ statuses: events.filter((e) => e.type === 'status').map((e) => e.data),+ errors: events.filter((e) => e.type === 'error'),+ warnings,+ };+ if (process.env.CINDY_SPEED_EVIDENCE)+ await writeFile(+ process.env.CINDY_SPEED_EVIDENCE,+ JSON.stringify(evidence, null, 2),+ );+ console.log(+ JSON.stringify({+ requests,+ first,+ second,+ toolCount: evidence.tools.length,+ errors: evidence.errors,+ }),+ );+ } finally {+ await handle?.close();+ await agent.dispose();+ server.closeAllConnections();+ await new Promise<void>((r) => server.close(() => r()));+ await rm(root, { recursive: true, force: true });+ }+ },+ 40_000,+);diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex c6993dbbbd..c071ed2708 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -93,6 +93,8 @@ export interface CodexRuntimeState {generationDurationMs: number;/** Model time sampled with the latest accepted output usage. */generationOutputDurationMs: number;+ /** Native-turn output for speed, independent of the billing ledger lifecycle. */+ generationOutputTokens: number;generationTurnId: string | null;/** False when a tool boundary is incomplete/out of order; unreliable TPS is omitted. */generationTimingReliable: boolean;@@ -142,6 +144,7 @@ export function newCodexRuntimeState(): CodexRuntimeState {generationPendingToolIds: new Set(),generationDurationMs: 0,generationOutputDurationMs: 0,+ generationOutputTokens: 0,generationTurnId: null,generationTimingReliable: true,generationHeartbeatAt: null,@@ -190,13 +193,15 @@ function startCodexGenerationHeartbeat(rt: CodexRuntimeState): void {}/** Reset per-turn model-generation timing; turn wall-clock is tracked separately by the host. */-export function resetCodexGenerationTiming(rt: CodexRuntimeState): void {+export function resetCodexGenerationTiming(rt: CodexRuntimeState, preserveSpeed = false): void {stopCodexGenerationHeartbeat(rt);- rt.tokenSpeed.reset();+ if (preserveSpeed) rt.tokenSpeed.startSegment();+ else rt.tokenSpeed.reset();rt.generationStartedAt = null;rt.generationPendingToolIds.clear();rt.generationDurationMs = 0;rt.generationOutputDurationMs = 0;+ rt.generationOutputTokens = 0;rt.generationTurnId = null;rt.generationTimingReliable = true;}@@ -221,7 +226,7 @@ export function beginCodexGenerationTurn(startedAt = Date.now(),): void {if (rt.generationTurnId !== turnId) {- resetCodexGenerationTiming(rt);+ resetCodexGenerationTiming(rt, true);rt.generationTurnId = turnId;}if (rt.generationStartedAt === null && rt.generationPendingToolIds.size === 0) {diff --git a/packages/maker-core/src/agents/shared/token-speed.test.ts b/packages/maker-core/src/agents/shared/token-speed.test.tsindex 46ceebf611..1fae29283a 100644--- a/packages/maker-core/src/agents/shared/token-speed.test.ts+++ b/packages/maker-core/src/agents/shared/token-speed.test.ts@@ -168,6 +168,32 @@ describe('TokenSpeedMeter (pi-token-speed algorithm)', () => {});describe('UsageTokenSpeedMeter', () => {+ // Regression: a long Codex run can report more output while tool-paused+ // generation time is frozen. Existing tests only covered backwards clocks.+ // Unit: the public snapshot must withdraw the bad interval and recover.+ it('excludes output without elapsed time and resumes from the next paired interval', () => {+ const meter = new UsageTokenSpeedMeter();+ meter.recordUsage(100, 1_000);+ meter.recordUsage(2_122_500, 1_000);+ expect(meter.snapshot()).toBeUndefined();+ meter.recordUsage(2_122_877, 11_000);+ expect(meter.snapshot()).toMatchObject({ tokens: 477, elapsedMs: 11_000, rate: 37.7 });+ expect(meter.snapshot()?.average).toBeCloseTo(477 / 11);+ });++ it('keeps paired totals and peak across native continuations but resets a new user turn', () => {+ const meter = new UsageTokenSpeedMeter();+ meter.recordUsage(1_000, 10_000);+ meter.stop();+ meter.startSegment();+ expect(meter.snapshot()).toBeUndefined();+ meter.recordUsage(377, 10_000);+ expect(meter.snapshot()).toMatchObject({ tokens: 1_377, elapsedMs: 20_000, average: 68.85, peak: 100 });+ meter.reset();+ meter.recordUsage(377, 10_000);+ expect(meter.snapshot()).toMatchObject({ tokens: 377, elapsedMs: 10_000, average: 37.7, peak: 37.7 });+ });+it('uses the last three paired intervals weighted by duration, including hidden output', () => {const meter = new UsageTokenSpeedMeter();expect(meter.snapshot()).toBeUndefined();diff --git a/packages/maker-core/src/agents/shared/token-speed.ts b/packages/maker-core/src/agents/shared/token-speed.tsindex 3dc46d3ed5..c420cd4229 100644--- a/packages/maker-core/src/agents/shared/token-speed.ts+++ b/packages/maker-core/src/agents/shared/token-speed.ts@@ -186,18 +186,42 @@ export class TokenSpeedMeter {export class UsageTokenSpeedMeter {private tokens = 0;private elapsedMs = 0;+ private peak = 0;+ private source = { tokens: 0, elapsedMs: 0 };private baseline = { tokens: 0, elapsedMs: 0 };private intervals: { tokens: number; elapsedMs: number }[] = [];private streaming = true;private invalid = false;+ private paired = true;+ private observed = false;+ /** A native turn with missing timing cannot attach its full billed output to a duration. */+ private completeSegment = true;reset(): void {this.tokens = 0;this.elapsedMs = 0;- this.baseline = { tokens: 0, elapsedMs: 0 };+ this.peak = 0;this.intervals = [];+ this.startSegment();+ }++ /** Native continuation: its counters restart together; measured product-turn totals remain. */+ startSegment(): void {+ this.source = { tokens: 0, elapsedMs: 0 };+ this.baseline = { tokens: this.tokens, elapsedMs: this.elapsedMs };this.streaming = true;this.invalid = false;+ this.paired = true;+ this.observed = false;+ this.completeSegment = true;+ }++ isReliable(): boolean {+ return !this.invalid && this.paired;+ }++ isSegmentComplete(): boolean {+ return this.completeSegment && !this.invalid;}invalidate(): void {@@ -207,31 +231,52 @@ export class UsageTokenSpeedMeter {recordUsage(tokens: number, elapsedMs: number): void {if (this.invalid || !this.streaming) return;if (!Number.isFinite(tokens) || !Number.isFinite(elapsedMs) ||- tokens < this.tokens || elapsedMs < this.elapsedMs) {+ tokens < this.source.tokens || elapsedMs < this.source.elapsedMs) {this.invalidate();return;}// Repeated usage cannot pair old tokens with a newer clock.- if (tokens === this.tokens) return;- this.tokens = tokens;- this.elapsedMs = elapsedMs;- const duration = elapsedMs - this.baseline.elapsedMs;+ if (tokens === this.source.tokens) return;+ const tokenDelta = tokens - this.source.tokens;+ const durationDelta = elapsedMs - this.source.elapsedMs;+ this.source = { tokens, elapsedMs };+ if (durationDelta === 0) {+ // Code-mode/background tools can leave the generation clock paused while+ // output keeps arriving. Drop this unpaired interval from BOTH statistics;+ // never attach its tokens to the next interval's time or to the average.+ this.paired = false;+ this.completeSegment = false;+ this.intervals = [];+ this.baseline = { tokens: this.tokens, elapsedMs: this.elapsedMs };+ return;+ }+ this.paired = true;+ this.observed = true;+ this.tokens += tokenDelta;+ this.elapsedMs += durationDelta;+ const duration = this.elapsedMs - this.baseline.elapsedMs;if (duration < 1_000) return;- this.intervals.push({ tokens: tokens - this.baseline.tokens, elapsedMs: duration });+ this.intervals.push({ tokens: this.tokens - this.baseline.tokens, elapsedMs: duration });this.intervals = this.intervals.slice(-3);- this.baseline = { tokens, elapsedMs };+ this.baseline = { tokens: this.tokens, elapsedMs: this.elapsedMs };+ const total = this.recentTotal();+ this.peak = Math.max(this.peak, total.tokens * 1_000 / total.elapsedMs);}stop(): void {this.streaming = false;}- snapshot(): TokenSpeedSnapshot | undefined {- if (this.invalid || this.tokens <= 0 || this.elapsedMs <= 0) return undefined;- const total = this.intervals.reduce((sum, interval) => ({+ private recentTotal(): { tokens: number; elapsedMs: number } {+ return this.intervals.reduce((sum, interval) => ({tokens: sum.tokens + interval.tokens,elapsedMs: sum.elapsedMs + interval.elapsedMs,}), { tokens: 0, elapsedMs: 0 });+ }++ snapshot(): TokenSpeedSnapshot | undefined {+ if (!this.isReliable() || !this.observed || this.tokens <= 0 || this.elapsedMs <= 0) return undefined;+ const total = this.recentTotal();const average = this.tokens * 1_000 / this.elapsedMs;return {rate: this.streaming ? (total.elapsedMs > 0 ? total.tokens * 1_000 / total.elapsedMs : 0) : average,@@ -239,6 +284,7 @@ export class UsageTokenSpeedMeter {tokens: this.tokens,elapsedMs: this.elapsedMs,streaming: this.streaming,+ peak: this.peak,};}}diff --git a/packages/maker-shared/src/runningTokenRateHistory.ts b/packages/maker-shared/src/runningTokenRateHistory.tsindex aaeca82025..bcdc93a2e7 100644--- a/packages/maker-shared/src/runningTokenRateHistory.ts+++ b/packages/maker-shared/src/runningTokenRateHistory.ts@@ -66,6 +66,7 @@ export function recordRunningTokenRate(? {...history,startedAt,+ peak: history.startedAt !== startedAt ? 0 : history.peak,baseline: null,lastReport: null,latestRate: null,@@ -126,7 +127,7 @@ export function recordRunningTokenRate(...observed,baseline,samples,- peak: Math.max(...samples.map((sample) => sample.rate)),+ peak: Math.max(current.peak, rate),latestRate: rate,latestSampleAt: input.now ?? Date.now(),};@@ -183,6 +184,8 @@ export interface TokenSpeedSnapshot {/** Generation time excluding tool pauses. */elapsedMs: number;streaming: boolean;+ /** Highest measured recent speed in this product turn; old hosts omit it. */+ peak?: number;}export function readTokenSpeedSnapshot(value: unknown): TokenSpeedSnapshot | undefined {@@ -192,7 +195,8 @@ export function readTokenSpeedSnapshot(value: unknown): TokenSpeedSnapshot | undif (!finite(speed.rate) || !finite(speed.average) || !finite(speed.tokens) ||!finite(speed.elapsedMs) || typeof speed.streaming !== 'boolean') return undefined;return { rate: speed.rate, average: speed.average, tokens: speed.tokens,- elapsedMs: speed.elapsedMs, streaming: speed.streaming };+ elapsedMs: speed.elapsedMs, streaming: speed.streaming,+ ...(finite(speed.peak) ? { peak: speed.peak } : {}) };}/** Record a host speed snapshot into the same chart model as counter samples. */@@ -213,6 +217,8 @@ export function recordTokenSpeed(lastReport: null,speedOffsetMs: offset,speedElapsedMs: speed.elapsedMs,+ peak: Math.max(history.startedAt !== startedAt ? 0 : history.peak, speed.peak ?? 0,+ speed.streaming ? speed.rate : 0),// The final average has its own UI field. It is not a new recent-speed sample.// Without a live reading this turn, keep showing the token count.latestRate: speed.streaming && speed.rate > 0 ? speed.rate : (reset ? null : history.latestRate),@@ -226,5 +232,5 @@ export function recordTokenSpeed(...history.samples.slice(-(MAX_RATE_SAMPLES - 1)),{ durationMs: at, outputTokens: speed.tokens, rate: speed.rate },];- return { ...next, samples, peak: Math.max(...samples.map((sample) => sample.rate)) };+ return { ...next, samples };}