Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(usage): measure live tok/s with the pi-token-speed algorithm
Chris9908706ab42c
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.tsindex 27ec716536..57467885fd 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts@@ -12,6 +12,7 @@ function applyStatus(generationDurationMs?: number;generationActive?: boolean;generationReliable?: boolean;+ tokenSpeed?: unknown;},): void {makerChatStore.__applyStatusUpdateForTest(sessionId, {@@ -31,6 +32,9 @@ function applyStatus(...(partial.generationReliable !== undefined? { generationReliable: partial.generationReliable }: {}),+ ...(partial.tokenSpeed !== undefined+ ? { tokenSpeed: partial.tokenSpeed as never }+ : {}),});}@@ -80,4 +84,21 @@ describe('makerChatStore live generation at turn start', () => {makerChatStore.purgeSession(sessionId);}});++ it('keeps the host speed across statuses without it and drops it on the next turn', () => {+ const sessionId = `live-gen-speed-${Math.random().toString(36).slice(2, 8)}`;+ const tokenSpeed = { rate: 42, average: 40, tokens: 120, elapsedMs: 3_000, streaming: true };+ try {+ applyStatus(sessionId, { isRunning: true, status: 'Generating...', tokenSpeed });+ applyStatus(sessionId, { isRunning: true, status: 'Running tool' });+ expect(makerChatStore.getSnapshot(sessionId).agentStatus.tokenSpeed).toEqual(tokenSpeed);+ applyStatus(sessionId, { isRunning: true, tokenSpeed: { rate: 'fast' } });+ expect(makerChatStore.getSnapshot(sessionId).agentStatus.tokenSpeed).toEqual(tokenSpeed);+ applyStatus(sessionId, { isRunning: false, status: 'Done' });+ applyStatus(sessionId, { isRunning: true, status: 'Working' });+ expect(makerChatStore.getSnapshot(sessionId).agentStatus.tokenSpeed).toBeUndefined();+ } finally {+ makerChatStore.purgeSession(sessionId);+ }+ });});diff --git a/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts b/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.tsindex 90e9e02e78..5144e88452 100644--- a/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts+++ b/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts@@ -4,8 +4,10 @@ import {emptyRateHistory,loadCachedRateHistory,recordRunningTokenRate,+ recordTokenSpeed,saveCachedRateHistory,} from '@/features/cc-agent/lib/runningTokenRateHistory';+import { readTokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';const input = { startedAt: 1, outputTokens: 0, generationDurationMs: 0, generationReliable: true };const begin = () => recordRunningTokenRate(emptyRateHistory(null), input);@@ -322,3 +324,50 @@ it('re-establishes the same report after reliability returns and preserves complexpect(next.latestRate).toBe(50);expect(next.samples.map((sample) => sample.durationMs)).toEqual([1000, 2000]);});++describe('host token speed (Pi extension algorithm)', () => {+ const speed = (rate: number, elapsedMs: number, streaming = true) => ({+ rate,+ average: rate,+ tokens: Math.round((rate * elapsedMs) / 1000),+ elapsedMs,+ streaming,+ });++ it('shows the host rate as the latest speed and charts one point per second of generation', () => {+ let history = recordTokenSpeed(emptyRateHistory(null), { startedAt: 1, speed: speed(80, 300), now: 10 });+ expect(history.latestRate).toBe(80);+ expect(history.samples).toEqual([]);+ history = recordTokenSpeed(history, { startedAt: 1, speed: speed(90, 1200), now: 20 });+ history = recordTokenSpeed(history, { startedAt: 1, speed: speed(95, 1500), now: 30 });+ 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.latestRate).toBe(70);+ });++ it('reports the final average without adding a chart point, and continues the axis next turn', () => {+ let history = recordTokenSpeed(emptyRateHistory(null), { startedAt: 1, speed: speed(100, 1500) });+ history = recordTokenSpeed(history, { startedAt: 1, speed: speed(60, 2000, false) });+ expect(history.latestRate).toBe(60);+ expect(history.samples).toHaveLength(1);+ history = recordTokenSpeed(history, { startedAt: 2, speed: speed(50, 1100) });+ expect(history.samples.map((sample) => sample.durationMs)).toEqual([1500, 2600]);+ });++ it('has no current speed until the host has a reading, instead of showing 0 tok/s', () => {+ const first = recordTokenSpeed(emptyRateHistory(null), { startedAt: 1, speed: speed(0, 400) });+ expect(first.latestRate).toBeNull();+ const measured = recordTokenSpeed(first, { startedAt: 1, speed: speed(50, 900) });+ expect(measured.latestRate).toBe(50);+ expect(recordTokenSpeed(measured, { startedAt: 2, speed: speed(0, 100) }).latestRate).toBeNull();+ });++ it('accepts only well-formed host snapshots', () => {+ expect(readTokenSpeedSnapshot(speed(10, 1000))).toEqual(speed(10, 1000));+ expect(readTokenSpeedSnapshot({ rate: 10 })).toBeUndefined();+ expect(readTokenSpeedSnapshot({ ...speed(10, 1000), rate: Number.NaN })).toBeUndefined();+ expect(readTokenSpeedSnapshot(null)).toBeUndefined();+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex ad46527ed2..6313691abe 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -278,6 +278,7 @@ import {resolveRunningUsageMeta,} from './lib/runningTokenUsage';import { RunningTokenRatePopover, useRunningTokenRateHistory } from './RunningTokenRatePopover';+import type { TokenSpeedSnapshot } from './lib/runningTokenRateHistory';import { matchNavigationCommandName, tryHandleNavigationCommand } from '@/lib/navigationCommands';import { extractIpcError } from '@/utils/ipcError';import { listActiveRunsForSession } from '@/features/learn/useLearnRun';@@ -5155,6 +5156,7 @@ export function CCAgentSessionView({outputTokens={agentStatus.outputTokens ?? 0}generationDurationMs={agentStatus.generationDurationMs ?? 0}generationReliable={agentStatus.generationReliable ?? true}+ tokenSpeed={agentStatus.tokenSpeed}startedAt={agentStatus.startedAt}visible={composerRuntimeVisible || (!pendingPlanReview && activeReconnect !== null)}inputWidth={inputWidth}@@ -6040,6 +6042,7 @@ function RunningStatusBar({outputTokens = 0,generationDurationMs = 0,generationReliable = true,+ tokenSpeed,startedAt,visible,inputWidth,@@ -6061,6 +6064,8 @@ function RunningStatusBar({outputTokens?: number;generationDurationMs?: number;generationReliable?: boolean;+ /** Host-measured live tok/s; replaces the usage-counter estimate when present. */+ tokenSpeed?: TokenSpeedSnapshot;startedAt: number | null;visible: boolean;inputWidth?: CSSProperties['width'];@@ -6223,13 +6228,18 @@ function RunningStatusBar({const tokenCountText = t('chat.runningStatus.tokenCount', {tokens: formatRunningTokenCount(animatedTokens),});+ // Host speed counts and times generation itself; usage counters stay the fallback.+ const rateOutputTokens = tokenSpeed?.tokens ?? outputTokens;+ const rateDurationMs = tokenSpeed?.elapsedMs ?? generationDurationMs;+ const rateReliable = tokenSpeed ? true : generationReliable;const rateHistory = useRunningTokenRateHistory({sessionKey,startedAt,outputTokens,generationDurationMs,+ tokenSpeed,generationReliable:- generationReliable &&+ rateReliable &&!reconnecting &&!sideTaskRunning &&!backgroundTasksRunning &&@@ -6237,9 +6247,9 @@ function RunningStatusBar({});const latestRate = rateHistory.latestRate;const usageMeta = resolveRunningUsageMeta({- outputTokens,- generationDurationMs,- generationReliable,+ outputTokens: rateOutputTokens,+ generationDurationMs: rateDurationMs,+ generationReliable: rateReliable,tokenUsage,latestRate,});@@ -6352,7 +6362,7 @@ function RunningStatusBar({}isTokenCount={usageMeta.kind === 'tokens'}averageRate={usageMeta.kind === 'rate' ? usageMeta.rate : null}- outputTokens={outputTokens}+ outputTokens={rateOutputTokens}history={rateHistory}onPinnedChange={setRatePanelPinned}/>diff --git a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsxindex 665e3ddf13..f2953c3004 100644--- a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx@@ -8,9 +8,11 @@ import {emptyRateHistory,loadCachedRateHistory,recordRunningTokenRate,+ recordTokenSpeed,saveCachedRateHistory,RATE_SAMPLE_FRESH_MS,type RateHistory,+ type TokenSpeedSnapshot,} from './lib/runningTokenRateHistory';export function useRunningTokenRateHistory(input: {@@ -20,8 +22,10 @@ export function useRunningTokenRateHistory(input: {outputTokens: number;generationDurationMs: number;generationReliable: boolean;+ /** Host-measured speed (Pi extension algorithm); old hosts omit it. */+ tokenSpeed?: TokenSpeedSnapshot;}) {- const { sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable } = input;+ const { sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, tokenSpeed } = input;// 挂载时从按会话的进程内缓存播种:RunningStatusBar 以 sessionId 为 key,// 切走再切回是全新挂载,历史从缓存恢复而不是从零开始。const [history, setHistory] = useState<RateHistory>(() => {@@ -33,14 +37,16 @@ export function useRunningTokenRateHistory(input: {});useEffect(() => {setHistory((previous) =>- recordRunningTokenRate(previous, {- startedAt,- outputTokens,- generationDurationMs,- generationReliable,- }),+ tokenSpeed && generationReliable+ ? recordTokenSpeed(previous, { startedAt, speed: tokenSpeed })+ : recordRunningTokenRate(previous, {+ startedAt,+ outputTokens,+ generationDurationMs,+ generationReliable,+ }),);- }, [startedAt, outputTokens, generationDurationMs, generationReliable]);+ }, [startedAt, outputTokens, generationDurationMs, generationReliable, tokenSpeed]);useEffect(() => {if (sessionKey) saveCachedRateHistory(sessionKey, history);}, [sessionKey, history]);diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts b/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.tsindex 5ef3efa6a1..06f92386d1 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts@@ -3,8 +3,10 @@ export {emptyRateHistory,loadCachedRateHistory,recordRunningTokenRate,+ recordTokenSpeed,saveCachedRateHistory,RATE_SAMPLE_FRESH_MS,type RateHistory,type RateSample,+ type TokenSpeedSnapshot,} from '@cindy/maker-shared/usage-format';diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 8967850772..eeeb1b9291 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -1,4 +1,5 @@import { readBotTaskResults } from '@cindy/maker-shared/botCollaboration';+import { readTokenSpeedSnapshot, type TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';import { remotePluginSetupErrorCode, type PluginSetupCommandError } from './pluginSetupCommandError';export type { PluginSetupCommandError } from './pluginSetupCommandError';import { emitTaskTagCatalog } from '@/features/task-tags/taskTagEvents';@@ -735,6 +736,8 @@ export interface AgentStatus {generationActive?: boolean;/** False hides live TPS. Omitted on placeholder status frames. */generationReliable?: boolean;+ /** Host-measured live tok/s; absent from old hosts and before the first output. */+ tokenSpeed?: TokenSpeedSnapshot;/*** Side-channel running (mivo MJ 按钮等不走 LLM 的后台任务)。* RunningStatusBar 据此把 token 计数行隐藏掉, 避免显示"上一轮残留 718 tokens"@@ -7045,8 +7048,12 @@ function mergeLiveGenerationStatus(previous: AgentStatus,): Pick<AgentStatus,- 'outputTokens' | 'generationDurationMs' | 'generationActive' | 'generationReliable'+ 'outputTokens' | 'generationDurationMs' | 'generationActive' | 'generationReliable' | 'tokenSpeed'> {+ // Speed belongs to the turn that produced it: a new turn drops the old value,+ // frames without the field keep the latest one (including the final average).+ const tokenSpeed = readTokenSpeedSnapshot(update.tokenSpeed)+ ?? (isTurnStart ? undefined : previous.tokenSpeed);// Turn start drops leftover metrics from the previous turn, then keeps any// live fields carried by this same status. A reconnect-shaped first event// (isRunning false→true with output / duration already present) must not@@ -7070,6 +7077,7 @@ function mergeLiveGenerationStatus(generationDurationMs: baseline.generationDurationMs,generationActive: update.isRunning ? baseline.generationActive : false,generationReliable: baseline.generationReliable,+ tokenSpeed,};}const merged = {@@ -7087,6 +7095,7 @@ function mergeLiveGenerationStatus(typeof update.generationReliable === 'boolean'? update.generationReliable: baseline.generationReliable,+ tokenSpeed,};if (!update.isRunning) {return { ...merged, generationActive: false };diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex b66ee6b98e..5725e77bdb 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -816,6 +816,8 @@ interface CCAgentStatusUpdate {generationDurationMs?: number;generationActive?: boolean;generationReliable?: boolean;+ /** Host-measured live tok/s (Pi extension algorithm); old hosts omit it. */+ tokenSpeed?: import('@cindy/maker-shared/usage-format').TokenSpeedSnapshot;isRunning: boolean;/** Host-owned SDK boundary claim; a claimed `status(false)` is not product idle. */turnContinuationId?: number;diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex b6e2080701..3e1d600a5e 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -18,6 +18,7 @@ import { nativeComposerAvailable } from '@/session/ComposerNativeInput';import { getActiveMobileSessionRealm } from '@/config/env';import { FailedScheduleNotice } from '@/session/FailedScheduleNotice';import { shouldShowFailedScheduleNotice, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';+import type { TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';import { CompanionHeader } from '@/session/CompanionHeader';import { useHiddenHistoryChase } from '@/session/hiddenHistoryChase';import { collectCompanionPluginInvocations } from '@/session/pluginInvocations';@@ -10299,6 +10300,7 @@ export default function SessionScreen() {outputTokens={remoteSessionRunStatus.outputTokens}generationDurationMs={remoteSessionRunStatus.generationDurationMs}generationReliable={remoteSessionRunStatus.generationReliable}+ tokenSpeed={remoteSessionRunStatus.tokenSpeed}generationActive={remoteSessionRunStatus.generationActive}visible={showComposerActivity}slowSendPhase={creationSlowPhase}@@ -12189,9 +12191,10 @@ function ComposerActivityStatus({rateStartedAt = startedAt,streaming = false,tokenUsage,- outputTokens,- generationDurationMs,- generationReliable,+ outputTokens: reportedOutputTokens,+ generationDurationMs: reportedGenerationDurationMs,+ generationReliable: reportedGenerationReliable,+ tokenSpeed,generationActive,visible,slowSendPhase = null,@@ -12209,11 +12212,17 @@ function ComposerActivityStatus({outputTokens: number;generationDurationMs: number;generationReliable: boolean;+ /** Host-measured live tok/s; replaces the usage-counter estimate when present. */+ tokenSpeed?: TokenSpeedSnapshot;generationActive: boolean;visible: boolean;/** Set once a new task's creation has waited past the slow-send delay. */slowSendPhase?: SlowSendPhase | null;}) {+ // Host speed counts and times generation itself; usage counters stay the fallback.+ const outputTokens = tokenSpeed?.tokens ?? reportedOutputTokens;+ const generationDurationMs = tokenSpeed?.elapsedMs ?? reportedGenerationDurationMs;+ const generationReliable = tokenSpeed ? true : reportedGenerationReliable;const styles = useThemedStyles(makeStyles);const pillStyles = useThemedStyles(makeComposerActivityPillStyles);const { colors } = useTheme();@@ -12242,6 +12251,7 @@ function ComposerActivityStatus({outputTokens,generationDurationMs,generationReliable: generationReliable && visible && !reconnectAttempt && !sideTaskRunning,+ tokenSpeed,streaming,});diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex 07103c6503..9e55ff4bfb 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -3294,6 +3294,20 @@ describe('remoteSessionStore', () => {});});+ it('carries the host tok/s across statuses without it and clears it for the next turn', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const tokenSpeed = { rate: 42, average: 40, tokens: 120, elapsedMs: 3_000, streaming: true };+ pushMakerStatus('s1', { isRunning: true, status: 'Generating...', tokenSpeed });+ pushMakerStatus('s1', { isRunning: true, status: 'Running tool' });+ expect(remoteSessionStore.getSessionRunStatus('s1').tokenSpeed).toEqual(tokenSpeed);+ pushMakerStatus('s1', { isRunning: false });+ remoteSessionStore.applySessionActivity('dev-1', { sessionId: 's1', phase: 'running' });+ expect(remoteSessionStore.getSessionRunStatus('s1').tokenSpeed).toBeUndefined();+ pushMakerStatus('s1', { isRunning: false });+ pushMakerStatus('s1', { isRunning: true, status: 'Thinking' });+ expect(remoteSessionStore.getSessionRunStatus('s1').tokenSpeed).toBeUndefined();+ });+it('clears leftover task updates on a real turn start, scoped to that session', () => {// Turn 1 on s1 spawns a sub-agent, then the turn ends — the live update lingers.pushMakerStatus('s1', { isRunning: true });diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 8b23ac79d6..cc0c48dfb2 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1,3 +1,4 @@+import { readTokenSpeedSnapshot, type TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';import { normalizeTaskTags, reconcileTaskTags } from '@cindy/maker-shared';import {createContext,@@ -151,6 +152,8 @@ export interface RemoteSessionRunStatus {generationDurationMs: number;generationActive: boolean;generationReliable: boolean;+ /** 电脑端测得的实时速度(Pi 扩展算法);旧版电脑不发。 */+ tokenSpeed?: TokenSpeedSnapshot;}export interface RemoteSessionReconnectAttempt {@@ -5008,6 +5011,9 @@ export const remoteSessionStore = {const generationReliable = typeof data?.generationReliable === 'boolean'? data.generationReliable: (isTurnStart ? true : current.generationReliable);+ // 速度属于产生它的那一轮:新一轮清掉,没带字段的帧沿用最近一次(含收尾平均)。+ const tokenSpeed = readTokenSpeedSnapshot(data?.tokenSpeed)+ ?? (isTurnStart ? undefined : current.tokenSpeed);// maker turn 边界 false→true 时清掉上一轮残留的 live task updates:它们是 turn 级// live 状态,残留到下一轮会被渲染层的孤儿兜底当作"仍在运行的子 agent"追加到消息流// 末尾(桌面端靠 idle demote / clear 清,手机 store 是常驻单例,只能在 turn 边界收口)。@@ -5037,6 +5043,7 @@ export const remoteSessionStore = {generationDurationMs,generationActive,generationReliable,+ tokenSpeed,};if (writeSessionRunStatus(sessionId, next)@@ -5615,6 +5622,7 @@ function clearLiveGenerationOnWideRunStart(return {...next,outputTokens: 0,+ tokenSpeed: undefined,generationDurationMs: 0,generationActive: false,generationReliable: true,diff --git a/apps/mobile/src/session/useRunningTokenRateHistory.ts b/apps/mobile/src/session/useRunningTokenRateHistory.tsindex 2fbcca018b..aa2f5b9f76 100644--- a/apps/mobile/src/session/useRunningTokenRateHistory.ts+++ b/apps/mobile/src/session/useRunningTokenRateHistory.ts@@ -3,9 +3,11 @@ import {emptyRateHistory,loadCachedRateHistory,recordRunningTokenRate,+ recordTokenSpeed,saveCachedRateHistory,RATE_SAMPLE_FRESH_MS,type RateHistory,+ type TokenSpeedSnapshot,} from '@cindy/maker-shared';export function useRunningTokenRateHistory(input: {@@ -15,6 +17,8 @@ export function useRunningTokenRateHistory(input: {outputTokens: number;generationDurationMs: number;generationReliable: boolean;+ /** 电脑端按 Pi 扩展算法测得的速度;旧版电脑不发,回落到用量计数。 */+ tokenSpeed?: TokenSpeedSnapshot;/** 本地发送或队列已让活动条出现,但远端本轮 startedAt 可能仍是 null。 */streaming?: boolean;}) {@@ -24,6 +28,7 @@ export function useRunningTokenRateHistory(input: {outputTokens,generationDurationMs,generationReliable,+ tokenSpeed,streaming = false,} = input;// 挂载时从按会话的进程内缓存播种:ComposerActivityStatus 以账号、设备和任务身份为 key,@@ -51,12 +56,14 @@ export function useRunningTokenRateHistory(input: {: startedAt === null? { ...cached, baseline: null, lastReport: null, latestRate: null }: cached;- const recorded = recordRunningTokenRate(seeded, {- startedAt,- outputTokens,- generationDurationMs,- generationReliable,- });+ const recorded = tokenSpeed && generationReliable+ ? recordTokenSpeed(seeded, { startedAt, speed: tokenSpeed })+ : recordRunningTokenRate(seeded, {+ startedAt,+ outputTokens,+ generationDurationMs,+ generationReliable,+ });// 同一挂载在 600ms 收尾粘滞内再次发送时不会重新播种。本地活动已开始而// 远端 startedAt 仍为 null 时,上一轮速率不能继续当作当前速度。if (@@ -68,7 +75,7 @@ export function useRunningTokenRateHistory(input: {}return recorded;});- }, [sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, streaming]);+ }, [sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, tokenSpeed, streaming]);useEffect(() => {if (sessionKey) saveCachedRateHistory(sessionKey, history);}, [sessionKey, history]);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 95b02b92a6..ed0abf07e1 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@@ -2011,3 +2011,82 @@ describe('claude generation pause boundaries', () => {vi.useRealTimers();});});++describe('claude live token speed', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('counts main-thread deltas, pauses on non-writing tools and reports the real average at the end', async () => {+ vi.useFakeTimers();+ const ctx = createTranslatorCtx();+ const queue = createAsyncQueue<AgentEvent>();+ const stream = (event: Record<string, unknown>, at: number, parent?: string) => {+ vi.setSystemTime(at);+ translateSdkMessage(+ { type: 'stream_event', event, ...(parent ? { parent_tool_use_id: parent } : {}) },+ queue,+ ctx,+ );+ };+ stream({ type: 'message_start', message: { model: 'claude-sonnet-4.5', usage: { input_tokens: 10 } } }, 1_000);+ stream({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, 1_000);+ stream({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'one two three four' } }, 1_500);+ stream({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'Bash', input: {} } }, 1_600);+ stream({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{"command":"ls -la"}' } }, 1_700);+ stream({ type: 'content_block_stop', index: 1 }, 2_000);+ stream({ type: 'message_delta', usage: { output_tokens: 12 } }, 2_000);+ // Subagent output is not the main thread's speed.+ stream({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'x y z' } }, 5_000, 'toolu_1');+ expect(ctx.rt.generation.tokenSpeed.snapshot(5_000)).toMatchObject({ tokens: 4, elapsedMs: 1_000 });+ stream({ type: 'message_start', message: { model: 'claude-sonnet-4.5', usage: { input_tokens: 10 } } }, 12_000);+ stream({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, 12_000);+ stream({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'five six' } }, 12_000);+ stream({ type: 'message_delta', usage: { output_tokens: 18 } }, 12_500);+ vi.setSystemTime(12_500);+ translateSdkMessage(+ {+ type: 'result',+ stop_reason: 'end_turn',+ total_cost_usd: 0,+ num_turns: 2,+ // A session aggregate turned into a wrong turn delta must not drive the snap.+ usage: { input_tokens: 20, output_tokens: 5 },+ },+ queue,+ ctx,+ );+ queue.end();+ const events: AgentEvent[] = [];+ for await (const event of queue) events.push(event);+ const statuses = events.filter((event) => event.type === 'status');+ const liveSpeed = statuses+ .map((event) => (event.data as { tokenSpeed?: unknown }).tokenSpeed)+ .find(Boolean);+ expect(liveSpeed).toMatchObject({ streaming: true, tokens: 4, elapsedMs: 500 });+ const done = statuses.find((event) => (event.data as { status?: string }).status === 'Done');+ // 11.5s wall clock minus the 10s tool pause, estimate snapped to the streamed 12 + 18 tokens.+ expect((done?.data as { tokenSpeed?: unknown }).tokenSpeed).toMatchObject({+ streaming: false,+ tokens: 30,+ elapsedMs: 1_500,+ average: 20,+ rate: 20,+ });+ resetClaudeGenerationTiming(ctx.rt.generation);+ expect(ctx.rt.generation.tokenSpeed.snapshot()).toBeUndefined();+ });++ it('counts Write tool arguments as generated output', () => {+ const ctx = createTranslatorCtx();+ const queue = createAsyncQueue<AgentEvent>();+ const stream = (event: Record<string, unknown>) =>+ translateSdkMessage({ type: 'stream_event', event }, queue, ctx);+ stream({ type: 'message_start', message: { model: 'claude-sonnet-4.5', usage: { input_tokens: 10 } } });+ stream({ type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu_w', name: 'Write', input: {} } });+ stream({ type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{"content":"a b c"}' } });+ expect(ctx.rt.generation.tokenSpeed.snapshot()?.tokens).toBeGreaterThan(0);+ resetClaudeGenerationTiming(ctx.rt.generation);+ queue.end();+ });+});diff --git a/packages/maker-core/src/agents/claude-code/generation-timing.ts b/packages/maker-core/src/agents/claude-code/generation-timing.tsindex ec16960afb..3a461e5e3e 100644--- a/packages/maker-core/src/agents/claude-code/generation-timing.ts+++ b/packages/maker-core/src/agents/claude-code/generation-timing.ts@@ -1,7 +1,13 @@+import { TokenSpeedMeter } from '../shared/token-speed.js';+const CLAUDE_GENERATION_HEARTBEAT_MS = 5_000;const CLAUDE_GENERATION_SUSPEND_GAP_MS = 30_000;export interface ClaudeGenerationState {+ /** Live tok/s for the main thread (Pi extension algorithm). */+ tokenSpeed: TokenSpeedMeter;+ /** Main-thread content block index → tool name, for argument-delta counting. */+ tokenSpeedToolByIndex: Map<number, string>;startedAt: number | null;durationMs: number;/** Model time sampled with the latest parent output usage. */@@ -31,6 +37,8 @@ export interface ClaudeGenerationState {export function newClaudeGenerationState(): ClaudeGenerationState {return {+ tokenSpeed: new TokenSpeedMeter(),+ tokenSpeedToolByIndex: new Map(),startedAt: null,durationMs: 0,outputDurationMs: 0,@@ -84,6 +92,8 @@ function closeInterval(state: ClaudeGenerationState, endedAt: number): void {export function resetClaudeGenerationTiming(state: ClaudeGenerationState): void {stopHeartbeat(state);+ state.tokenSpeed.reset();+ state.tokenSpeedToolByIndex.clear();state.startedAt = null;state.pendingToolIds.clear();state.settledPauseIds.clear();diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.tsindex 9f55212e04..3488051308 100644--- a/packages/maker-core/src/agents/claude-code/translator.ts+++ b/packages/maker-core/src/agents/claude-code/translator.ts@@ -38,6 +38,7 @@ import {import type { UsageTracker } from '../shared/usage-tracker.js';import { isModelAccessDenied } from './model-access-error.js';import { attachLiveGeneration, sampleGenerationDuration } from '../shared/live-generation-snapshot.js';+import { isFileWritingTool } from '../shared/token-speed.js';import {beginClaudeGeneration,beginClaudeGenerationAtRequestStart,@@ -343,6 +344,7 @@ function ccLiveStatus(return {status,...attachLiveGeneration(ctx.tracker.snapshot(), {+ tokenSpeed: ctx.rt.generation.tokenSpeed.snapshot(),outputTokens: mainTurnOutputTokens(ctx.tracker),durationMs: ctx.rt.generation.outputDurationMs,openStartedAt: ctx.rt.generation.startedAt,@@ -1666,6 +1668,44 @@ function observeClaudeSubagentStream(// ── stream_event 子分支(content_block_delta / message_delta / message_start) ──+/** Main-thread live tok/s, mirroring pi-token-speed's message_update handlers. */+function observeClaudeTokenSpeed(+ event: {+ type?: string;+ index?: number;+ delta?: Record<string, unknown>;+ content_block?: { type?: string; name?: string };+ },+ queue: EventQueue,+ ctx: TranslateContext,+): void {+ const speed = ctx.rt.generation.tokenSpeed;+ const tools = ctx.rt.generation.tokenSpeedToolByIndex;+ const index = typeof event.index === 'number' ? event.index : 0;+ switch (event.type) {+ case 'message_start':+ tools.clear();+ return;+ case 'content_block_start':+ if (event.content_block?.type === 'tool_use') tools.set(index, event.content_block.name ?? '');+ speed.start();+ return;+ case 'content_block_delta': {+ const delta = event.delta;+ const text = delta?.type === 'input_json_delta'+ ? (isFileWritingTool(tools.get(index)) ? delta.partial_json : undefined)+ : delta?.text ?? delta?.thinking;+ if (typeof text === 'string' && speed.recordDelta(text)) {+ queue.push({ type: 'status', data: ccLiveStatus(ctx, 'Generating...', true), source: 'claude-code' });+ }+ return;+ }+ case 'content_block_stop':+ if (tools.has(index) && !isFileWritingTool(tools.get(index))) speed.pause();+ return;+ }+}+function handleStreamEvent(msg: {event?: Record<string, unknown>;@@ -1688,6 +1728,8 @@ function handleStreamEvent(? msg.parent_tool_use_id: undefined;+ if (!parentToolUseId) observeClaudeTokenSpeed(event, queue, ctx);+// 冗余 add: 防 SDK 顺序契约变化 (stream_event 先于 assistant message yield), Set 幂等。if (event.type === 'content_block_start') {const cb = event.content_block;@@ -2196,6 +2238,9 @@ function handleResult(resultUsage != null && segmentTotals.outputTokens === resultUsage.outputTokens,);const liveGeneration = ctx.rt.generation;+ // Snap to this turn's streamed main-thread usage: the result aggregate can be+ // a session total turned into a wrong delta, and a bad snap is worse than the estimate.+ liveGeneration.tokenSpeed.stop(mainTurnOutputTokens(ctx.tracker));const endSnapshot = ctx.tracker.endTurn(resultUsage? {@@ -2477,6 +2522,7 @@ function handleResult(data: {status: 'Done',...attachLiveGeneration(endSnapshot, {+ tokenSpeed: liveGeneration.tokenSpeed.snapshot(),outputTokens: liveTurnOutput,durationMs: liveGeneration.outputDurationMs,openStartedAt: null,diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex b3281c9911..1c3145b46f 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -3708,6 +3708,7 @@ assertRouteCurrent();const usageTracker = new UsageTracker();const translatorRt: CodexRuntimeState = newCodexRuntimeState();const liveUsageSnapshot = () => attachLiveGeneration(usageTracker.snapshot(), {+ tokenSpeed: translatorRt.tokenSpeed.snapshot(),outputTokens: usageTracker.getTurnUsage().output,durationMs: translatorRt.generationOutputDurationMs,openStartedAt: translatorRt.generationStartedAt,@@ -10994,6 +10995,7 @@ assertRouteCurrent();const realTurnUsage = usageTracker.getTurnUsage();const realTurnUsageSegments = usageTracker.getTurnUsageSegments();finalizeCodexGenerationTurn(translatorRt, turn.id);+ translatorRt.tokenSpeed.stop(realTurnUsage.output);const generationDurationMs = codexGenerationDurationMs(translatorRt);const codexDoneUsage = {promptTokens: realTurnUsage.input,@@ -11214,6 +11216,7 @@ assertRouteCurrent();data: {status: 'Done',...attachLiveGeneration(endSnap, {+ tokenSpeed: translatorRt.tokenSpeed.snapshot(),outputTokens: realTurnUsage.output,durationMs: translatorRt.generationOutputDurationMs,openStartedAt: null,@@ -12581,6 +12584,7 @@ assertRouteCurrent();producedOutputTurnIds.add(params.turnId);noteRecoveryModelWork(params.turnId);translateAgentMessageDelta(params, eventQueue, { rt: translatorRt, log });+ maybePushUsageRefresh();},turnPlanUpdated: (params) => {if (enqueueIfBufferedTurn(params.turnId, () => handlers.turnPlanUpdated?.(params))) return;@@ -12596,6 +12600,7 @@ assertRouteCurrent();producedOutputTurnIds.add(params.turnId);noteRecoveryModelWork(params.turnId);translateReasoningSummaryTextDelta(params, eventQueue, { rt: translatorRt, log });+ maybePushUsageRefresh();},reasoningSummaryPartAdded: (params) => {// thinking 流同样算产出(与非缓冲路径一致)。@@ -12612,6 +12617,7 @@ assertRouteCurrent();producedOutputTurnIds.add(params.turnId);noteRecoveryModelWork(params.turnId);translateReasoningTextDelta(params, eventQueue, { rt: translatorRt, log });+ maybePushUsageRefresh();},accountRateLimitsUpdated: (params) =>translateAccountRateLimitsUpdated(params, eventQueue, { rt: translatorRt, log }),diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.tsindex 65c7ef70c4..46dca43f00 100644--- a/packages/maker-core/src/agents/codex/translator.test.ts+++ b/packages/maker-core/src/agents/codex/translator.test.ts@@ -2480,3 +2480,24 @@ it('carries the provider final phase from item start onto the first delta', asyntranslateAgentMessageDelta({ threadId: 'thread', turnId: 'turn', itemId: 'final', delta: 'Visible now' }, q, ctx);expect(await collect(q)).toContainEqual({ type: 'text', source: 'codex', data: { text: 'Visible now', isFinal: false, agentMessageId: 'final', phase: 'final_answer' } });});++it('measures live tok/s from visible deltas and pauses while a command runs', () => {+ vi.useFakeTimers();+ try {+ const rt = newCodexRuntimeState(), q = createAsyncQueue<AgentEvent>(), ctx = makeCtx(rt);+ vi.setSystemTime(1_000);+ beginCodexGenerationTurn(rt, 'turn', 1_000);+ translateItemNotification('started', { threadId: 'thread', turnId: 'turn', item: { type: 'agentMessage', id: 'm1', text: '' } }, q, ctx);+ vi.setSystemTime(1_500);+ translateAgentMessageDelta({ threadId: 'thread', turnId: 'turn', itemId: 'm1', delta: 'one two three four' }, q, ctx);+ expect(rt.tokenSpeed.snapshot()).toMatchObject({ streaming: true, tokens: 4, elapsedMs: 500 });+ translateItemNotification('started', { threadId: 'thread', turnId: 'turn', item: { type: 'commandExecution', id: 'c1', command: 'ls' } }, q, ctx);+ vi.setSystemTime(9_500);+ // The command is still running: its time is not generation time.+ expect(rt.tokenSpeed.snapshot()?.elapsedMs).toBe(500);+ rt.tokenSpeed.stop(20);+ expect(rt.tokenSpeed.snapshot()).toMatchObject({ streaming: false, tokens: 20, elapsedMs: 500, average: 40 });+ } finally {+ vi.useRealTimers();+ }+});diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex 9f6739c6d8..2f5ff46150 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -32,6 +32,7 @@ import {stripInternalWebCitations,} from '@cindy/maker-shared/internal-citation';+import { TokenSpeedMeter } from '../shared/token-speed.js';import type { AgentEvent, AgentTaskStatus, AgentTaskUpdateEventData } from '../../types/events.js';import { normalizeAccountRateLimitSnapshot } from '../../types/account-rate-limits.js';import type { AsyncQueue } from '../shared/async-queue.js';@@ -79,6 +80,8 @@ export interface CodexRuntimeState {reasoningTextLen: Map<string, number>;/** item.id → agentMessage 已 emit 文本字符长度(citation 归一化后的空间,见 handleAgentMessage)。 */itemTextLen: Map<string, number>;+ /** Live tok/s shown in the status bar (Pi extension algorithm). */+ tokenSpeed: TokenSpeedMeter;/** 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. */@@ -130,6 +133,7 @@ export function newCodexRuntimeState(): CodexRuntimeState {reasoningStartedAt: new Map(),reasoningTextLen: new Map(),itemTextLen: new Map(),+ tokenSpeed: new TokenSpeedMeter(),generationStartedAt: null,generationPendingToolIds: new Set(),generationDurationMs: 0,@@ -183,6 +187,7 @@ 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 {stopCodexGenerationHeartbeat(rt);+ rt.tokenSpeed.reset();rt.generationStartedAt = null;rt.generationPendingToolIds.clear();rt.generationDurationMs = 0;@@ -312,6 +317,9 @@ function noteCodexGenerationBoundary(// for pause pairing but fail closed for TPS.rt.generationTimingReliable = false;}+ if (phase === 'started' && (item.type === 'reasoning' || item.type === 'agentMessage')) {+ rt.tokenSpeed.start();+ }if (typeof item.type !== 'string' ||!CODEX_GENERATION_PAUSE_ITEM_TYPES.has(item.type)@@ -324,6 +332,8 @@ function noteCodexGenerationBoundary(}const pauseId = `item:${item.id}`;if (phase === 'started') {+ // The model finished emitting this call; its execution is not generation time.+ rt.tokenSpeed.pause(receivedAt);pauseCodexGeneration(rt, turnId, pauseId, receivedAt);return;}@@ -1106,6 +1116,7 @@ function emitAgentMessageProgress(ctx.rt.itemRawText.set(itemId, rawText);ctx.rt.itemTextLen.set(itemId, emitted.length);if (delta.length === 0) return;+ ctx.rt.tokenSpeed.recordDelta(delta);queue.push({type: 'text',data: { text: delta, isFinal: false, agentMessageId: itemId,@@ -1321,6 +1332,7 @@ export function translateReasoningSummaryTextDelta(ctx: CodexTranslateContext,): void {if (!params.delta) return;+ ctx.rt.tokenSpeed.recordDelta(params.delta);ensureReasoningStarted(params.itemId, queue, ctx);const prevLen = ctx.rt.reasoningTextLen.get(params.itemId) ?? 0;ctx.rt.reasoningTextLen.set(params.itemId, prevLen + params.delta.length);@@ -1355,6 +1367,7 @@ export function translateReasoningTextDelta(ctx: CodexTranslateContext,): void {if (!params.delta) return;+ ctx.rt.tokenSpeed.recordDelta(params.delta);ensureReasoningStarted(params.itemId, queue, ctx);const prevLen = ctx.rt.reasoningTextLen.get(params.itemId) ?? 0;ctx.rt.reasoningTextLen.set(params.itemId, prevLen + params.delta.length);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 b56625510c..ea94547a48 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@@ -2239,3 +2239,67 @@ describe('pi translator', () => {});});});++describe('pi translator live token speed', () => {+ const speedOf = (event: AgentEvent | undefined) =>+ (event?.data as { tokenSpeed?: Record<string, unknown> } | undefined)?.tokenSpeed;++ it('counts streamed text, pauses on non-writing tools and snaps to real output at the end', () => {+ vi.useFakeTimers();+ try {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();+ const update = (assistantMessageEvent: Record<string, unknown>, at: number) => {+ vi.setSystemTime(at);+ translatePiEvent(ev({ type: 'message_update', assistantMessageEvent }), queue, ctx);+ };+ vi.setSystemTime(1_000);+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ translatePiEvent(ev({ type: 'message_start', message: { role: 'assistant' } }), queue, ctx);+ update({ type: 'text_start', contentIndex: 0 }, 1_000);+ update({ type: 'text_delta', contentIndex: 0, delta: 'one two three four five six' }, 1_500);+ const live = speedOf(events.filter((e) => e.type === 'status').at(-1));+ expect(live).toMatchObject({ streaming: true, tokens: 6, elapsedMs: 500 });+ expect(live?.rate).toBeGreaterThan(0);++ // A bash call: its arguments are not counted and its execution is paused out.+ update({ type: 'toolcall_start', contentIndex: 1, toolCall: { name: 'bash' } }, 1_600);+ update({ type: 'toolcall_delta', contentIndex: 1, delta: '{"command":"ls -la"}', toolCall: { name: 'bash' } }, 1_700);+ update({ type: 'toolcall_end', contentIndex: 1, toolCall: { name: 'bash' } }, 2_000);+ update({ type: 'text_delta', contentIndex: 0, delta: 'seven eight' }, 12_000);++ vi.setSystemTime(12_500);+ translatePiEvent(ev({ type: 'message_end', message: {+ role: 'assistant', content: [{ type: 'text', text: 'one two three four five six' }], stopReason: 'stop',+ usage: { input: 10, output: 30 },+ } }), queue, ctx);+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);+ const final = speedOf(events.filter((e) => e.type === 'status').at(-1));+ // 11.5s wall clock minus the 10s tool pause; estimate replaced by the real 30 tokens.+ expect(final).toMatchObject({ streaming: false, tokens: 30, elapsedMs: 1_500, average: 20, rate: 20 });+ } finally {+ vi.useRealTimers();+ }+ });++ it('counts file-writing tool arguments and starts each turn fresh', () => {+ vi.useFakeTimers();+ try {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();+ vi.setSystemTime(1_000);+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ translatePiEvent(ev({ type: 'message_update', assistantMessageEvent: {+ type: 'toolcall_delta', contentIndex: 0, delta: 'a b c',+ partial: { content: [{ type: 'toolCall', name: 'write' }] },+ } }), queue, ctx);+ expect(speedOf(events.filter((e) => e.type === 'status').at(-1))).toMatchObject({ tokens: 3 });+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);+ events.length = 0;+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ expect(usageSnapshotOf(ctx).tokenSpeed).toBeUndefined();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex 17064889fa..4a98df8398 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -32,6 +32,7 @@ import {import type { AgentEvent, AgentTaskUpdateEventData, UsageSnapshot } from '../../types/index.js';import type { AsyncQueue } from '../shared/async-queue.js';import { attachLiveGeneration } from '../shared/live-generation-snapshot.js';+import { TokenSpeedMeter, isFileWritingTool } from '../shared/token-speed.js';import type { UsageSegment } from '../shared/usage-tracker.js';import {UPSTREAM_OVERLOAD_REASON,@@ -160,6 +161,10 @@ export interface PiTranslateContext {terminalAssistantErrorEmitted: boolean;/** 整轮 wall-clock 起点;只用于诊断,不参与 TPS。 */turnWallClockStartedAt: number;+ /** Live tok/s shown in the status bar (Pi extension algorithm). */+ tokenSpeed: TokenSpeedMeter;+ /** Last running status text, reused by speed-only refreshes. */+ lastRunningStatus: string;generationDurationMs: number;/** Open generation interval start; 0 while tools/user waits own the turn. */generationOpenAt: number;@@ -224,6 +229,8 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {finalAssistantText: '',finalAssistantStopReason: null,turnWallClockStartedAt: 0,+ tokenSpeed: new TokenSpeedMeter(),+ lastRunningStatus: 'Working…',generationDurationMs: 0,generationOpenAt: 0,generationTimingReliable: true,@@ -364,6 +371,7 @@ export function usageSnapshotOf(ctx: PiTranslateContext): UsageSnapshot {costUsd: ctx.costUsd,},{+ tokenSpeed: ctx.tokenSpeed.snapshot(),outputTokens: ctx.turnOutput,// Pi reports output only at message_end, alongside the closed duration.durationMs: ctx.generationDurationMs,@@ -380,6 +388,7 @@ function pushStatus(isRunning: boolean,extras?: Pick<AgentEvent, 'turnScope'>,): void {+ if (isRunning) ctx.lastRunningStatus = text;queue.push({type: 'status',data: { status: text, ...usageSnapshotOf(ctx), isRunning },@@ -684,6 +693,7 @@ export function translatePiEvent(ctx.pendingAssistantError = null;ctx.terminalAssistantErrorEmitted = false;ctx.turnWallClockStartedAt = Date.now();+ ctx.tokenSpeed.reset();ctx.generationDurationMs = 0;ctx.generationTimingReliable = true;stopPiGenerationHeartbeat(ctx);@@ -717,6 +727,7 @@ export function translatePiEvent(case 'message_update': {const delta = event.assistantMessageEvent as Record<string, unknown> | undefined;if (!delta || typeof delta.type !== 'string') return;+ observePiTokenSpeed(delta, queue, ctx);handleAssistantDelta(delta, queue, ctx);return;}@@ -956,6 +967,7 @@ export function translatePiEvent(ctx.turnSettled = true;ctx.isStreaming = false;ctx.pendingPriceVariants = [];+ ctx.tokenSpeed.stop(ctx.turnOutput);stopPiGenerationHeartbeat(ctx);const hostAbortRequested = isCurrentTurnHostAbortRequested(ctx);const pendingAssistantError = hostAbortRequested ? null : ctx.pendingAssistantError;@@ -1200,6 +1212,43 @@ export function translatePiEvent(}}+/** Mirrors pi-token-speed's message_update handlers. */+function observePiTokenSpeed(+ delta: Record<string, unknown>,+ queue: AsyncQueue<AgentEvent>,+ ctx: PiTranslateContext,+): void {+ if (!ctx.isStreaming) return;+ switch (delta.type) {+ case 'text_start':+ case 'thinking_start':+ case 'toolcall_start':+ ctx.tokenSpeed.start();+ return;+ case 'toolcall_delta':+ if (!isFileWritingTool(piDeltaToolName(delta))) return;+ // falls through+ case 'text_delta':+ case 'thinking_delta':+ if (typeof delta.delta === 'string' && ctx.tokenSpeed.recordDelta(delta.delta)) {+ pushStatus(queue, ctx, ctx.lastRunningStatus, true);+ }+ return;+ case 'toolcall_end':+ if (!isFileWritingTool(piDeltaToolName(delta))) ctx.tokenSpeed.pause();+ return;+ }+}++function piDeltaToolName(delta: Record<string, unknown>): unknown {+ const toolCall = delta.toolCall as { name?: unknown } | undefined;+ if (toolCall?.name !== undefined) return toolCall.name;+ const partial = delta.partial as { content?: Array<{ type?: unknown; name?: unknown }> } | undefined;+ const index = typeof delta.contentIndex === 'number' ? delta.contentIndex : 0;+ const block = partial?.content?.[index];+ return block?.type === 'toolCall' ? block.name : undefined;+}+function handleAssistantDelta(delta: Record<string, unknown>,queue: AsyncQueue<AgentEvent>,diff --git a/packages/maker-core/src/agents/shared/live-generation-snapshot.ts b/packages/maker-core/src/agents/shared/live-generation-snapshot.tsindex be8802c8a0..2405679a9c 100644--- a/packages/maker-core/src/agents/shared/live-generation-snapshot.ts+++ b/packages/maker-core/src/agents/shared/live-generation-snapshot.ts@@ -1,6 +1,9 @@+import type { TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';import type { UsageSnapshot } from '../../types/events.js';export interface LiveGenerationTiming {+ /** Pi-extension speed measurement; independent of the usage-paired timing below. */+ tokenSpeed?: TokenSpeedSnapshot;/** Turn-cumulative output tokens, including reasoning. */outputTokens: number;/** Duration captured with outputTokens; sparse usage must not include later in-flight time. */@@ -26,7 +29,11 @@ export function attachLiveGeneration(typeof timing.outputTokens === 'number' && Number.isFinite(timing.outputTokens)? Math.max(0, timing.outputTokens): 0;- const next: UsageSnapshot = { ...snapshot, outputTokens };+ const next: UsageSnapshot = {+ ...snapshot,+ outputTokens,+ ...(timing.tokenSpeed ? { tokenSpeed: timing.tokenSpeed } : {}),+ };if (!timing.reliable) {return {...next,diff --git a/packages/maker-core/src/agents/shared/token-speed.test.ts b/packages/maker-core/src/agents/shared/token-speed.test.tsnew file mode 100644index 0000000000..cd385845b5--- /dev/null+++ b/packages/maker-core/src/agents/shared/token-speed.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it } from 'vitest';+import { estimateDeltaTokens, isFileWritingTool, TokenSpeedMeter } from './token-speed.js';++describe('TokenSpeedMeter (pi-token-speed algorithm)', () => {+ it('counts deltas with the word/punctuation estimate, one token per CJK character', () => {+ expect(estimateDeltaTokens('Hello, world!')).toBe(4);+ expect(estimateDeltaTokens('你好世界')).toBe(4);+ expect(estimateDeltaTokens(' ')).toBe(0);+ });++ it('reports tokens in the last second over the time since the token before them', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ // 10 tokens every 100ms → 100 tok/s.+ for (let t = 100; t <= 2_000; t += 100) meter.recordDelta('a b c d e f g h i j', t);+ const speed = meter.snapshot(2_000)!;+ expect(speed.streaming).toBe(true);+ // Window [1000, 2000] holds 11 events (110 tokens), generated since the token at 900.+ expect(speed.rate).toBeCloseTo(100, 5);+ expect(speed.tokens).toBe(200);+ });++ it('keeps the last rate during a stall, like the extension status bar', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ for (let t = 100; t <= 1_000; t += 100) meter.recordDelta('a b c d e', t);+ const before = meter.snapshot(1_000)!.rate;+ expect(meter.snapshot(9_000)!.rate).toBe(before);+ });++ it('extends a single-timestamp burst back to the previous token', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ meter.recordDelta('a', 0);+ // 5s stall, then 500 tokens flushed at once.+ meter.recordDelta(Array.from({ length: 500 }, () => 'w').join(' '), 5_000);+ expect(meter.snapshot(5_000)!.rate).toBeCloseTo(100, 5);+ });++ it('reads output flushed as several deltas after hidden thinking at its real pace', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ meter.recordDelta('a b c d e f g h i j', 1_000);+ meter.pause(1_000);+ // The tool ran for 9s, then the model thought for 10s without streaming anything.+ meter.start(10_000);+ const chunk = Array.from({ length: 250 }, () => 'w').join(' ');+ meter.recordDelta(chunk, 20_000);+ meter.recordDelta(chunk, 20_100);+ meter.recordDelta(chunk, 20_250);+ const live = meter.snapshot(20_250)!;+ expect(live.rate).toBeCloseTo(750 / 10.25, 5);+ meter.stop(1_200, 20_250);+ // 1s before the tool + 10.25s after it; the tool's 9s are excluded.+ expect(meter.snapshot()!).toMatchObject({ elapsedMs: 11_250, tokens: 1_200 });+ });++ it('keeps the previous reading while the window holds only a stray token', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ meter.recordDelta('a', 50);+ expect(meter.snapshot(50)!.rate).toBe(0);+ meter.recordDelta('a b c d e f g h i j', 1_000);+ const reading = meter.snapshot(1_000)!.rate;+ expect(reading).toBeGreaterThan(0);+ meter.pause(1_000);+ meter.start(3_000);+ meter.recordDelta('x', 5_500);+ expect(meter.snapshot(5_500)!.rate).toBe(reading);+ });++ it('excludes tool pauses from elapsed time and resumes on the next delta', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ meter.recordDelta('a b c d e f g h i j', 1_000);+ meter.pause(1_000);+ meter.recordDelta('a b c d e f g h i j', 31_000);+ meter.stop(undefined, 32_000);+ const speed = meter.snapshot(40_000)!;+ expect(speed.elapsedMs).toBe(2_000);+ expect(speed.average).toBe(10);+ });++ it('never lets elapsed time run backwards across an open pause', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ meter.recordDelta('a b c d e f g h i j', 1_000);+ meter.pause(1_000);+ expect(meter.snapshot(20_000)!.elapsedMs).toBe(1_000);+ meter.recordDelta('a', 30_000);+ expect(meter.snapshot(30_000)!.elapsedMs).toBe(1_000);+ meter.pause(30_500);+ meter.stop(undefined, 60_000);+ expect(meter.snapshot(90_000)!.elapsedMs).toBe(1_500);+ });++ it('snaps to the real output at the end and reports the average', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ meter.recordDelta('a b c', 500);+ meter.stop(400, 2_000);+ const speed = meter.snapshot(5_000)!;+ expect(speed).toMatchObject({ streaming: false, tokens: 400, elapsedMs: 2_000, average: 200, rate: 200 });+ });++ it('keeps the estimate when the provider reported no output', () => {+ const meter = new TokenSpeedMeter();+ meter.start(0);+ meter.recordDelta('a b c d', 1_000);+ meter.stop(0, 2_000);+ expect(meter.snapshot()!.tokens).toBe(4);+ });++ it('has nothing to show before the first token and after reset', () => {+ const meter = new TokenSpeedMeter();+ expect(meter.snapshot()).toBeUndefined();+ meter.start(0);+ expect(meter.snapshot(10)).toBeUndefined();+ meter.recordDelta('a', 20);+ meter.reset();+ expect(meter.snapshot()).toBeUndefined();+ });++ it('throttles refresh signals to four per second', () => {+ const meter = new TokenSpeedMeter();+ const due = [0, 50, 100, 260, 300, 520].map((t) => meter.recordDelta('a b c d e', t));+ expect(due).toEqual([true, false, false, true, false, true]);+ });++ it('counts only file-writing tool arguments', () => {+ expect(['edit', 'write', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit'].every(isFileWritingTool)).toBe(true);+ expect(['bash', 'Read', 'Grep', undefined].some(isFileWritingTool)).toBe(false);+ });+});diff --git a/packages/maker-core/src/agents/shared/token-speed.ts b/packages/maker-core/src/agents/shared/token-speed.tsnew file mode 100644index 0000000000..357cd9ca92--- /dev/null+++ b/packages/maker-core/src/agents/shared/token-speed.ts@@ -0,0 +1,173 @@+import type { TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';++/**+ * Live tok/s, ported from the Pi `pi-token-speed` extension (MIT, gsanhueza)+ * with its `estimate` count strategy and `average` end-of-stream behaviour:+ *+ * - one measurement per turn, started by the first content block;+ * - each text / thinking delta (and file-writing tool argument delta) is+ * counted with the word-boundary estimate `/\w+|[^\s\w]/g`;+ * - current speed = tokens in the last 1s window / time since the token+ * before them, or since generation resumed (min 100ms); a window with+ * fewer than 5 tokens keeps the previous reading;+ * - the clock pauses when a non file-writing tool call ends and resumes when+ * the next content block starts or the next counted delta arrives;+ * - at turn end the count is snapped to the provider's real output and the+ * speed becomes total tokens / elapsed generation time.+ *+ * Display only: never feeds billing, cache or context accounting.+ */+const WINDOW_MS = 1_000;+const MIN_SPAN_MS = 100;+/** A window with fewer tokens than this is noise (e.g. one stray token before a summary). */+const MIN_WINDOW_TOKENS = 5;+const COMPACTION_THRESHOLD = 5_000;+const PUBLISH_INTERVAL_MS = 250;+const TOKEN_REGEX = /\w+|[^\s\w]/g;++export function estimateDeltaTokens(text: string): number {+ return text ? (text.match(TOKEN_REGEX)?.length ?? 0) : 0;+}++export class TokenSpeedMeter {+ private started = false;+ private streaming = false;+ private paused = false;+ private tokenCount = 0;+ private startTime = 0;+ private endTime = 0;+ private startPause = 0;+ private pausedMs = 0;+ /** Where the generation clock last (re)started: turn start or the end of a tool pause. */+ private resumedAt = 0;+ private tps = 0;+ private events: { time: number; tokens: number }[] = [];+ private windowStartIndex = 0;+ private lastPublishAt = -Infinity;++ /** New turn: forget the previous measurement. */+ reset(): void {+ this.started = false;+ this.streaming = false;+ this.paused = false;+ this.tokenCount = 0;+ this.startTime = 0;+ this.endTime = 0;+ this.pausedMs = 0;+ this.resumedAt = 0;+ this.tps = 0;+ this.events = [];+ this.windowStartIndex = 0;+ this.lastPublishAt = -Infinity;+ }++ /**+ * A content block started. The first one starts the turn's measurement; a+ * later one ends a tool pause, because the model is generating again even+ * when it streams nothing yet (e.g. thinking that is only summarised later).+ */+ start(now = Date.now()): void {+ if (this.started) {+ this.resume(now);+ return;+ }+ this.started = true;+ this.streaming = true;+ this.startTime = now;+ this.endTime = now;+ this.resumedAt = now;+ }++ /** Records one streamed delta. Returns true when a status refresh is due. */+ recordDelta(text: string, now = Date.now()): boolean {+ this.start(now);+ if (!this.streaming) return false;+ const tokens = estimateDeltaTokens(text);+ if (tokens <= 0) return false;+ this.tokenCount += tokens;+ this.events.push({ time: now, tokens });+ if (this.windowStartIndex >= COMPACTION_THRESHOLD) {+ this.events.splice(0, this.windowStartIndex);+ this.windowStartIndex = 0;+ }+ this.tps = this.windowTps(now) ?? this.tps;+ if (now - this.lastPublishAt < PUBLISH_INTERVAL_MS) return false;+ this.lastPublishAt = now;+ return true;+ }++ /** A tool call finished generating; its execution is not generation time. */+ pause(now = Date.now()): void {+ if (!this.streaming || this.paused) return;+ this.paused = true;+ this.startPause = now;+ }++ private resume(now: number): void {+ if (!this.streaming || !this.paused) return;+ this.paused = false;+ this.pausedMs += now - this.startPause;+ this.resumedAt = now;+ }++ /** Turn end. `realOutputTokens` replaces the estimate when the provider reported it. */+ stop(realOutputTokens?: number, now = Date.now()): void {+ if (this.streaming) {+ this.streaming = false;+ // Ending inside a tool pause: the pause is not generation time either.+ this.endTime = this.paused ? this.startPause : now;+ this.events = [];+ this.windowStartIndex = 0;+ }+ if (realOutputTokens !== undefined && Number.isFinite(realOutputTokens) && realOutputTokens > 0) {+ this.tokenCount = realOutputTokens;+ }+ }++ snapshot(now = Date.now()): TokenSpeedSnapshot | undefined {+ if (!this.started || this.tokenCount <= 0) return undefined;+ const elapsedMs = this.elapsedMs(now);+ const average = elapsedMs > 0 ? (this.tokenCount * 1_000) / elapsedMs : 0;+ return {+ rate: this.streaming ? this.tps : average,+ average,+ tokens: Math.round(this.tokenCount),+ elapsedMs,+ streaming: this.streaming,+ };+ }++ private elapsedMs(now: number): number {+ if (!this.started) return 0;+ // An open tool pause is excluded too, so elapsed time never runs backwards on resume.+ const end = !this.streaming ? this.endTime : this.paused ? this.startPause : now;+ return Math.max(0, end - this.startTime - this.pausedMs);+ }++ /** Undefined when the window holds too little to measure; the last reading stays. */+ private windowTps(now: number): number | undefined {+ const windowStart = now - WINDOW_MS;+ while (this.windowStartIndex < this.events.length && this.events[this.windowStartIndex].time < windowStart) {+ this.windowStartIndex += 1;+ }+ if (this.windowStartIndex >= this.events.length) return undefined;+ let windowTokens = 0;+ for (let i = this.windowStartIndex; i < this.events.length; i += 1) windowTokens += this.events[i].tokens;+ if (windowTokens < MIN_WINDOW_TOKENS) return undefined;+ // The first token in the window was generated after the token before it (or after+ // generation resumed), not at its arrival. Pi extends the span this way only when the+ // whole window shares one timestamp; providers also flush stalled or summarised+ // output as several deltas a few ms apart, which would otherwise read as thousands+ // of tok/s.+ const previous = this.windowStartIndex > 0 ? this.events[this.windowStartIndex - 1].time : this.startTime;+ const spanStart = Math.max(previous, this.resumedAt);+ return (1_000 * windowTokens) / Math.max(now - spanStart, MIN_SPAN_MS);+ }+}++/** Pi counts argument deltas of tools that write the model's output into files. */+const FILE_WRITING_TOOLS = new Set(['edit', 'write', 'multiedit', 'notebookedit']);++export function isFileWritingTool(name: unknown): boolean {+ return typeof name === 'string' && FILE_WRITING_TOOLS.has(name.toLowerCase());+}diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex d2df179d45..5724a6471e 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -10,6 +10,7 @@*/import type { WorkflowProgressEntry } from '@cindy/maker-shared/agent-task';+import type { TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';import type { SubagentObservation } from '@cindy/maker-shared/subagent-observation';import {parseToolLoopErrorDetails,@@ -418,6 +419,8 @@ export interface UsageSnapshot {generationActive?: boolean;/** False when live TPS must be hidden. Omitted on placeholder status frames. */generationReliable?: boolean;+ /** Host-measured live tok/s (Pi extension algorithm). Display only. */+ tokenSpeed?: TokenSpeedSnapshot;/*** Host/bridge 自动 compact 已确定性失败,下次 send 应换干净原生窗口。* 只由 Claude Code / Pi 的 AutoCompactController 锁存。diff --git a/packages/maker-shared/src/runningTokenRateHistory.ts b/packages/maker-shared/src/runningTokenRateHistory.tsindex c40497e66e..6bd1a90f8e 100644--- a/packages/maker-shared/src/runningTokenRateHistory.ts+++ b/packages/maker-shared/src/runningTokenRateHistory.ts@@ -22,6 +22,9 @@ export interface RateHistory {peak: number;latestRate: number | null;latestSampleAt?: number;+ /** Host speed mode: chart x-offset of the current turn and its last elapsed time. */+ speedOffsetMs?: number;+ speedElapsedMs?: number;}export function emptyRateHistory(startedAt: number | null): RateHistory {@@ -66,6 +69,8 @@ export function recordRunningTokenRate(baseline: null,lastReport: null,latestRate: null,+ speedOffsetMs: undefined,+ speedElapsedMs: undefined,}: history;if (@@ -163,3 +168,61 @@ export function saveCachedRateHistory(export function clearRateHistoryCache(): void {rateHistoryBySession.clear();}++/**+ * Host-measured tok/s (Pi `pi-token-speed` algorithm, see maker-core+ * `token-speed.ts`). Optional additive status field: old hosts omit it and the+ * counter-based history above stays in charge.+ */+export interface TokenSpeedSnapshot {+ /** Sliding-window rate while streaming; final average once the turn ended. */+ rate: number;+ /** Tokens / elapsed generation time (snapped to real output at turn end). */+ average: number;+ tokens: number;+ /** Generation time excluding tool pauses. */+ elapsedMs: number;+ streaming: boolean;+}++export function readTokenSpeedSnapshot(value: unknown): TokenSpeedSnapshot | undefined {+ if (!value || typeof value !== 'object') return undefined;+ const speed = value as Partial<TokenSpeedSnapshot>;+ const finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0;+ if (!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 };+}++/** Record a host speed snapshot into the same chart model as counter samples. */+export function recordTokenSpeed(+ history: RateHistory,+ input: { startedAt: number | null; speed: TokenSpeedSnapshot; now?: number },+): RateHistory {+ const { speed } = input;+ const startedAt = input.startedAt ?? history.startedAt;+ // A new turn restarts the host clock; keep earlier points and continue the axis after them.+ const reset = history.startedAt !== startedAt || history.speedOffsetMs === undefined ||+ speed.elapsedMs < (history.speedElapsedMs ?? 0);+ const offset = reset ? (history.samples.at(-1)?.durationMs ?? 0) : (history.speedOffsetMs ?? 0);+ const next: RateHistory = {+ ...history,+ startedAt,+ baseline: null,+ lastReport: null,+ speedOffsetMs: offset,+ speedElapsedMs: speed.elapsedMs,+ // No reading yet this turn: keep showing the token count rather than "0 tok/s".+ latestRate: speed.streaming && speed.rate <= 0 ? (reset ? null : history.latestRate) : speed.rate,+ latestSampleAt: input.now ?? Date.now(),+ };+ const at = offset + speed.elapsedMs;+ const lastAt = reset ? offset : (history.samples.at(-1)?.durationMs ?? offset);+ if (!speed.streaming || speed.rate <= 0 || at - lastAt < MIN_SAMPLE_DURATION_MS) return next;+ const samples = [+ ...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)) };+}