Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
revert: restore pre-#5734 response speed experience
Chris5a9437e6cc86
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 60f4c7332e..f556c5229e 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -1060,8 +1060,8 @@ describe('maker:event hot path ordering', () => {const claudeCostFallback = claudeDoneSource.slice(claudeDoneSource.indexOf("} else if (typeof cumulative === 'number' && cumulative >= 0)"),);- expect(claudeCostFallback).not.toMatch(- /buildClaudeTurnUsageDetails\(\s*doneData\??\.usage/,+ expect(claudeCostFallback).toMatch(+ /buildClaudeTurnUsageDetails\(\s*undefined,\s*undefined,\s*resolvedModel,/,);expect(claudeCostFallback).toContain("if (route !== 'provider-api' || turnContext.accessKind === 'managed')",diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionClaudeTurnUsage.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionClaudeTurnUsage.test.tsdeleted file mode 100644index 87b0ded265..0000000000--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionClaudeTurnUsage.test.ts+++ /dev/null@@ -1,107 +0,0 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { createSourceFile, isFunctionDeclaration, ScriptKind, ScriptTarget, transpileModule } from 'typescript';-import { describe, expect, it, vi } from 'vitest';-import { calibratedResponseDuration } from '@cindy/maker-shared/usage-format';-import type { AgentEvent, Session } from '@cindy/maker-core';-import type { RecordSessionClaudeTurnUsageDeps } from '../sessionClaudeTurnUsage.js';-import { buildClaudeTurnUsageDetails, normalizeTurnUsageSegments } from '../../usage/turnCostCalculator.js';-import { ClaudeOutputLagTimingGuard, computeModelUsageDeltas } from '../../usage/modelUsageDelta.js';--// Execute the production sink with database/network effects isolated, retaining-// real usage normalization, timing validation and message-detail construction.-const source = readFileSync(resolve(__dirname, '../sessionClaudeTurnUsage.ts'), 'utf8').replace(/\r\n?/g, '\n');-const ast = createSourceFile('sessionClaudeTurnUsage.ts', source, ScriptTarget.Latest, true, ScriptKind.TS);-const declaration = ast.statements.find(node => isFunctionDeclaration(node) && node.name?.text === 'recordSessionClaudeTurnUsage');-if (!declaration) throw new Error('recordSessionClaudeTurnUsage not found');-const compiled = transpileModule(declaration.getText(ast), {- compilerOptions: { target: ScriptTarget.ES2022 },-}).outputText.replace('export function ', 'function ');--function harness() {- const record = vi.fn<(value: { turnUsageDetails: unknown }) => Promise<void>>().mockResolvedValue(undefined);- const guard = new ClaudeOutputLagTimingGuard();- const recordSpend = vi.fn();- const runtime = {- calibratedResponseDuration, normalizeTurnUsageSegments, buildClaudeTurnUsageDetails, computeModelUsageDeltas,- captureTurnUsageContext: () => ({ providerId: null }),- recordTurnUsageOnMessage: record,- triggerClaudeAccountUsageRefresh: vi.fn(), triggerClaudeSubscriptionUsageRefresh: vi.fn(),- getSessionProvider: () => undefined,- CHATGPT_MODEL_PREFIX: 'chatgpt/', isExclusiveXaiModelId: () => false,- detectClaudeModelMismatch: () => null,- billingRouteForExplicitProvider: () => null, readClaudeSessionRoute: () => 'subscription',- readClaudeApiKey: () => undefined, getReferenceModelPricing: () => null,- CURRENT_CINDY_REGION: 'global',- resolveClaudeTurnCostSinks: () => ({ turnMoney: null, estimatedTurnMoney: null, perModel: [] }),- recordTurnSpend: recordSpend,- };- const wire = new Function('runtime', `const {${Object.keys(runtime).join(',')}} = runtime; ${compiled}; return recordSessionClaudeTurnUsage;`)(runtime) as- typeof import('../sessionClaudeTurnUsage.js').recordSessionClaudeTurnUsage;- const deps: RecordSessionClaudeTurnUsageDeps = {- turnUsageContextBySession: new Map(), turnModelPromiseBySession: new Map(),- readSessionModelForUsage: async () => 'claude-sonnet-4.5',- lastReportedModelUsageBySession: new Map(), claudeOutputLagTimingGuard: guard,- lastReportedCostUsdBySession: new Map(), log: { warn: vi.fn() },- unpricedSubscriptionValueMarker: () => ({ amount: 0, currency: 'USD', kind: 'value-estimate', approximate: true }),- };- const send = (data: unknown) => wire(deps, { id: 'task' } as Session,- { type: 'done', source: 'claude-code', data } as AgentEvent, 'assistant', 9_000, false);- return { send, record, guard, deps, recordSpend };-}--function done(output = 60, cumulative = 160, durationMs = 3_000) {- return {- total_cost_usd: 0, usage: { input_tokens: 500, output_tokens: cumulative, cache_read_input_tokens: 200 },- turnUsage: { input_tokens: 15, output_tokens: output, cache_read_input_tokens: 5, cache_creation_input_tokens: 2 },- responseSpeed: { phase: 'complete', waitOrigin: 'stream', firstResponseMs: 1000, waitingMs: 0,- durationMs, outputTokens: output, estimated: false, averageRate: output * 1000 / durationMs,- recentRate: output * 1000 / durationMs, samples: [], sampledAt: 10_000 },- };-}--describe('Claude completed usage without modelUsage', () => {- it('persists current-turn TPS across cumulative results without charging or copying aggregate tokens', async () => {- const h = harness();- h.send(done(100, 100, 2_000));- await vi.waitFor(() => expect(h.record).toHaveBeenCalledTimes(1));- h.send(done());- await vi.waitFor(() => expect(h.record).toHaveBeenCalledTimes(2));- const first = h.record.mock.calls[0][0].turnUsageDetails;- const second = h.record.mock.calls[1][0].turnUsageDetails;- expect(first).toMatchObject({ outputTokens: 100, durationMs: 2_000 });- expect(second).toMatchObject({ inputTokens: 15, outputTokens: 60, cacheReadTokens: 5,- cacheCreateTokens: 2, durationMs: 3_000, turnDurationMs: 9_000 });- expect(h.deps.lastReportedCostUsdBySession.get('task')).toBe(0);- expect(h.recordSpend).not.toHaveBeenCalled();- });-- it('uses the normalized delta when partial request metadata has no priced model rows', async () => {- const h = harness();- h.send({ ...done(), usageSegments: [{ model: 'claude-sonnet-4.5', inputTokens: 5, outputTokens: 10 }],- usageSegmentsComplete: false });- await vi.waitFor(() => expect(h.record).toHaveBeenCalledTimes(1));- expect(h.record.mock.calls[0][0].turnUsageDetails).toMatchObject({ inputTokens: 15,- outputTokens: 60, cacheReadTokens: 5, cacheCreateTokens: 2, durationMs: 3_000 });- expect(h.recordSpend).not.toHaveBeenCalled();- });-- it.each([undefined, { output_tokens: 160 }, { output_tokens: Number.NaN }, { output_tokens: -1 }])(- 'omits timing when the normalized provider count is unavailable or mismatched (%j)', async (turnUsage) => {- const h = harness(); h.send({ ...done(), turnUsage });- await vi.waitFor(() => expect(h.record).toHaveBeenCalledTimes(1));- expect(h.record.mock.calls[0][0].turnUsageDetails).toMatchObject({ outputTokens: 0 });- expect(h.record.mock.calls[0][0].turnUsageDetails).not.toHaveProperty('durationMs');- },- );-- it('keeps a real zero and respects output-lag suppression', async () => {- const h = harness(); h.send(done(0, 160));- await vi.waitFor(() => expect(h.record).toHaveBeenCalledTimes(1));- expect(h.record.mock.calls[0][0].turnUsageDetails).toMatchObject({ outputTokens: 0, durationMs: 3_000 });- vi.spyOn(h.guard, 'evaluate').mockReturnValue({ detected: false, suppressTiming: true });- h.send(done());- await vi.waitFor(() => expect(h.record).toHaveBeenCalledTimes(2));- expect(h.record.mock.calls[1][0].turnUsageDetails).not.toHaveProperty('durationMs');- });-});diff --git a/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts b/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.tsindex af54783afa..a9621fd9ce 100644--- a/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts+++ b/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts@@ -1,4 +1,3 @@-import { calibratedResponseDuration } from '@cindy/maker-shared/usage-format';import { captureTurnUsageContext, type TurnUsageContext } from './turnUsageContext.js';import { isOpenAiSubscriptionProviderId } from '../maker-host/codex-account-auth.js';import type { AgentEvent, Session } from '@cindy/maker-core';@@ -100,13 +99,6 @@ export function recordSessionClaudeTurnUsage(total_cost_usd?: unknown;duration_ms?: unknown;duration_api_ms?: unknown;- responseSpeed?: unknown;- turnUsage?: {- input_tokens?: number;- output_tokens?: number;- cache_read_input_tokens?: number;- cache_creation_input_tokens?: number;- };usage?: {input_tokens?: number;output_tokens?: number;@@ -175,18 +167,11 @@ export function recordSessionClaudeTurnUsage(: undefined,doneData?.is_error !== true,);- const claudeTurnOutputTokens = modelUsageDeltas?.length- ? modelUsageDeltas.reduce((sum, delta) => sum + delta.outputTokensDelta, 0)- : typeof doneData?.turnUsage?.output_tokens === 'number' ? doneData.turnUsage.output_tokens : undefined;const claudeGenerationDurationMs = outputLagTiming.suppressTiming? undefined- : doneData?.responseSpeed !== undefined- ? claudeTurnOutputTokens !== undefined- ? calibratedResponseDuration(doneData.responseSpeed, claudeTurnOutputTokens)- : undefined- : typeof doneData?.duration_api_ms === 'number'- ? doneData.duration_api_ms- : undefined;+ : typeof doneData?.duration_api_ms === 'number'+ ? doneData.duration_api_ms+ : undefined;// total_cost_usd 累计基线: 主路径不靠它算钱, 但仍跟住, 以便万一某轮缺 modelUsage// 走兜底时累计差才准。先取"更新前"基线给兜底用, 再写入本轮累计。const prevReportedCost = deps.lastReportedCostUsdBySession.get(session.id);@@ -344,7 +329,7 @@ export function recordSessionClaudeTurnUsage(// deltas 非空 → buildClaudeTurnUsageDetails 用 deltas 里的 model, fallbackModel 不取用。// 传 perModel → 落「按模型成本明细」(含 subagent 跑的模型, 如 Haiku)。const turnUsageDetails = buildClaudeTurnUsageDetails(- doneData?.turnUsage ?? doneData?.usage,+ doneData?.usage,resolvedUsageDeltas,'unknown',perModel,@@ -378,7 +363,7 @@ export function recordSessionClaudeTurnUsage(const turnEstimatedValue =estimatedValues.length > 0 ? addRegionalMoney(estimatedValues) : null;const turnUsageDetails = buildClaudeTurnUsageDetails(- doneData?.turnUsage ?? doneData?.usage,+ doneData?.usage,resolvedUsageDeltas,'unknown',perModel,@@ -423,11 +408,9 @@ export function recordSessionClaudeTurnUsage(}// `doneData.usage` can be the same process-lifetime cumulative snapshot as// `total_cost_usd`. Without model deltas or request segments it is not a reliable- // per-turn token fact. Persist the normalized provider delta only when- // its output matches the calibrated measurement; never the aggregate.+ // per-turn token fact, so retain only model/timing metadata in this fallback.const turnUsageDetails = buildClaudeTurnUsageDetails(- claudeGenerationDurationMs !== undefined && claudeTurnOutputTokens !== undefined- ? doneData?.turnUsage : undefined,+ undefined,undefined,resolvedModel,undefined,@@ -435,7 +418,7 @@ export function recordSessionClaudeTurnUsage(claudeTurnDurationMs,);// 本分支有三个"记不了钱"的出口(本轮 cost 未增长 / 订阅直连 / 非明确- // provider-api 路由)。只保留可证明的模型、输出与时长;进程累计 usage 不能冒充本轮 token。+ // provider-api 路由)。只保留可证明的模型与时长;进程累计 usage 不能冒充本轮 token。const recordUsageOnly = async () => {if (!turnAssistantPersistId) return;await recordTurnUsageOnMessage({diff --git a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.tsindex fe492d3175..82edb97886 100644--- a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts+++ b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts@@ -56,7 +56,7 @@ describe('controlled banner placement', () => {'const controlledBannerMaxWidth = `min(${inputHalfWidth}, ${CONTROLLED_BANNER_MAX_WIDTH}px)`;',);expect(sessionViewSource).toContain(- 'if (!rightLeadingSlot && (suppressContent || (isHidden && !ratePanelPinned && !completedSpeed))) return null;',+ 'if (!rightLeadingSlot && (suppressContent || (isHidden && !ratePanelPinned))) return null;',);expect(controlledBannerSource).toContain("placement?: 'floating' | 'inline' | 'composer';");expect(controlledBannerSource).toContain(diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.tsindex 458d6b3cdf..27ec716536 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts@@ -1,11 +1,6 @@-import { describe, expect, it, vi } from 'vitest';--vi.mock('@/lib/makerTransport', () => ({- makerApiFor: () => ({ input: { stop: vi.fn(async () => ({ queue: [], paused: false })) } }),-}));+import { describe, expect, it } from 'vitest';import { makerChatStore } from '@/lib/makerChatStore';-import type { ResponseSpeedSnapshot } from '@cindy/maker-shared/usage-format';function applyStatus(sessionId: string,@@ -17,7 +12,6 @@ function applyStatus(generationDurationMs?: number;generationActive?: boolean;generationReliable?: boolean;- responseSpeed?: ResponseSpeedSnapshot;},): void {makerChatStore.__applyStatusUpdateForTest(sessionId, {@@ -27,7 +21,6 @@ function applyStatus(contextTokens: 0,contextWindow: 0,isRunning: partial.isRunning,- ...(partial.responseSpeed ? { responseSpeed: partial.responseSpeed } : {}),...(partial.outputTokens !== undefined ? { outputTokens: partial.outputTokens } : {}),...(partial.generationDurationMs !== undefined? { generationDurationMs: partial.generationDurationMs }@@ -42,26 +35,6 @@ function applyStatus(}describe('makerChatStore live generation at turn start', () => {- it('retains an interrupted measurement across stop and task switching, then resets on the next turn', () => {- const sessionId = `live-gen-stop-${Math.random().toString(36).slice(2, 8)}`;- const speed: ResponseSpeedSnapshot = { phase: 'generating', waitOrigin: 'turn', firstResponseMs: 1000,- waitingMs: 0, outputTokens: 50, durationMs: 2000, estimated: true, recentRate: 30,- averageRate: 25, samples: [{ durationMs: 2000, outputTokens: 50, rate: 30 }], sampledAt: Date.now() };- try {- applyStatus(sessionId, { isRunning: true, responseSpeed: speed });- makerChatStore.stopSession(sessionId);- makerChatStore.getSnapshot('another-task');- expect(makerChatStore.getSnapshot(sessionId).agentStatus).toMatchObject({- isRunning: false, generationActive: false,- responseSpeed: { phase: 'complete', estimated: true, recentRate: null, outcome: 'cancelled', samples: speed.samples },- });- applyStatus(sessionId, { isRunning: true });- expect(makerChatStore.getSnapshot(sessionId).agentStatus.responseSpeed).toBeUndefined();- } finally {- makerChatStore.purgeSession(sessionId);- makerChatStore.purgeSession('another-task');- }- });it('keeps live fields when the first running status already carries them', () => {const sessionId = `live-gen-keep-${Math.random().toString(36).slice(2, 8)}`;try {@@ -108,35 +81,3 @@ describe('makerChatStore live generation at turn start', () => {}});});--it('keeps a response speed failure through done/status tails and uses only actual retry events', () => {- const id = 'speed-error-retry-lifecycle';- const speed: ResponseSpeedSnapshot = { phase: 'generating', waitOrigin: 'turn', firstResponseMs: 1000,- waitingMs: 0, outputTokens: 50, durationMs: 2000, estimated: true, recentRate: 30,- averageRate: 25, samples: [{ durationMs: 2000, outputTokens: 50, rate: 30 }], sampledAt: Date.now() };- const event = (type: 'error' | 'done' | 'text', data: Record<string, unknown>) =>- makerChatStore.__applyStreamEventForTest(id, { sessionId: id, type, source: 'pi', data });- try {- applyStatus(id, { isRunning: true, responseSpeed: speed });- event('error', { message: 'API unavailable', reason: 'api-error', isTerminal: false });- expect(makerChatStore.getSnapshot(id).agentStatus.responseSpeed?.retrying).not.toBe(true);- event('error', { message: 'API unavailable; retrying', reason: 'api-error', willRetry: true, isTerminal: false });- expect(makerChatStore.getSnapshot(id).agentStatus.responseSpeed).toMatchObject({ retrying: true, recentRate: null });- applyStatus(id, { isRunning: true, responseSpeed: speed });- expect(makerChatStore.getSnapshot(id).agentStatus.responseSpeed?.retrying).toBe(true);- event('text', { text: 'recovered', isFinal: false });- expect(makerChatStore.getSnapshot(id).agentStatus.responseSpeed?.retrying).toBe(false);- event('error', { message: 'API unavailable', reason: 'api-error', isTerminal: true });- expect(makerChatStore.getSnapshot(id)).toMatchObject({ error: 'API unavailable', errorReason: 'api-error',- agentStatus: { isRunning: false, responseSpeed: { phase: 'complete', outcome: 'failed', recentRate: null, samples: speed.samples } } });- event('done', {});- applyStatus(id, { isRunning: false, responseSpeed: { ...speed, phase: 'complete', estimated: false } });- expect(makerChatStore.getSnapshot(id).agentStatus.responseSpeed?.outcome).toBe('failed');- applyStatus(id, { isRunning: true });- expect(makerChatStore.getSnapshot(id).agentStatus.responseSpeed).toBeUndefined();- applyStatus(id, { isRunning: true, responseSpeed: speed });- event('done', { type: 'pi/agent_settled', status: 'cancelled' });- expect(makerChatStore.getSnapshot(id)).toMatchObject({ error: null,- agentStatus: { responseSpeed: { outcome: 'cancelled', recentRate: null } } });- } finally { makerChatStore.purgeSession(id); }-});diff --git a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsxindex cf1c222146..0857964e55 100644--- a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx+++ b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx@@ -2,9 +2,8 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import React, { useCallback, useEffect, useRef, useState } from 'react';-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';import ts from 'typescript';-import { responseSpeedActivity } from '@cindy/maker-shared/usage-format';import { afterEach, expect, it, vi } from 'vitest';import { formatSessionDuration } from '@/lib/sessionDurationFormat';import {@@ -17,9 +16,7 @@ import {resolveRunningUsageMeta,} from '@/features/cc-agent/lib/runningTokenUsage';-vi.mock('react-i18next', () => ({ useTranslation: () => ({- t: (key: string, values?: { value?: unknown; rate?: unknown }) => `${key}${values?.value ?? values?.rate ?? ''}`,-}) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));// Execute the actual status bar without loading the entire session view's IPC/store graph.const source = readFileSync(@@ -43,14 +40,11 @@ const compiled = ts.transpileModule(component.getText(ast), {const Icon = () => null;const deps = {React,- responseSpeedActivity,useCallback,useEffect,useRef,useState,- useTranslation: () => ({- t: (key: string, values?: { value?: unknown; rate?: unknown }) => `${key}${values?.value ?? values?.rate ?? ''}`,- }),+ useTranslation: () => ({ t: (key: string) => key }),useReducedMotion: () => true,useAnimatedNumber: (value: number) => value,localizeAgentStatus: (status: string) => status,@@ -75,40 +69,19 @@ const RunningStatusBar = new Function(`const {${Object.keys(deps).join(',')}} = deps; ${compiled}; return RunningStatusBar;`,)(deps) as React.ComponentType<{visible: boolean;- responseSpeed?: import('@cindy/maker-shared/usage-format').ResponseSpeedSnapshot;suppressContent?: boolean;rightLeadingSlot?: React.ReactNode;status: string;reconnectStatus?: string | null;- startedAt: number | null;+ startedAt: number;tokenUsage: number;outputTokens: number;generationDurationMs: number;- generationActive?: boolean;generationReliable?: boolean;}>;afterEach(cleanup);-it('clears an older host recent interval immediately when native generation pauses, keeping history', () => {- const props = { visible: true, status: 'Generating...', startedAt: Date.now(), tokenUsage: 0,- outputTokens: 0, generationDurationMs: 0, generationReliable: true, generationActive: true };- const view = render(<RunningStatusBar {...props} />);- const measured = { ...props, outputTokens: 370, generationDurationMs: 1000 };- view.rerender(<RunningStatusBar {...measured} />);- const trigger = () => view.container.querySelector('[data-running-status-meta] button')!;- expect(trigger().textContent).toContain('chat.runningStatus.tokenRate');- fireEvent.click(trigger());- view.rerender(<RunningStatusBar {...measured} generationActive={false} status="Running bash…" />);- expect(trigger().textContent).not.toContain('chat.runningStatus.tokenRate');- expect(screen.getByRole('dialog').textContent).toContain('370');- expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.observedPeak');- view.rerender(<RunningStatusBar {...measured} generationActive />);- expect(trigger().textContent).not.toContain('chat.runningStatus.tokenRate');- view.rerender(<RunningStatusBar {...measured} generationActive outputTokens={470} generationDurationMs={2000} />);- expect(trigger().textContent).toContain('chat.runningStatus.tokenRate');-});-it.each([false, true])('reconnect hides stale speed and pinned history, then waits for fresh samples (pinned=%s)', (pinned) => {const props = {visible: true, status: 'Generating...', startedAt: 1, tokenUsage: 1000,@@ -183,15 +156,9 @@ it('opens measured zero history and restores fallback across reliability and turexpect(trigger()).not.toBeNull();});-it.each(['running', 'stopped', 'completed'] as const)(- 'plan review preserves the collapsed indicator and suppresses a pinned panel (%s)',- (state) => {- const visible = state === 'running';- const responseSpeed = state === 'completed' ? {- phase: 'complete' as const, waitOrigin: 'turn' as const, firstResponseMs: 1000, waitingMs: 0,- durationMs: 1000, outputTokens: 100, estimated: false, averageRate: 100, recentRate: 100,- samples: [{ durationMs: 1000, outputTokens: 100, rate: 100 }], sampledAt: Date.now(),- } : undefined;+it.each([true, false])(+ 'plan review preserves the collapsed indicator and suppresses a pinned panel (running=%s)',+ (visible) => {const props = {visible: true,status: 'Thinking',@@ -211,7 +178,6 @@ it.each(['running', 'stopped', 'completed'] as const)(<RunningStatusBar{...props}visible={visible}- responseSpeed={responseSpeed}suppressContentrightLeadingSlot={indicator}/>,@@ -221,102 +187,7 @@ it.each(['running', 'stopped', 'completed'] as const)(expect(screen.queryByRole('button', { name: 'titleBar.close' })).toBeNull();// Explicit suppression without an independent indicator leaves no row behind.- rerender(<RunningStatusBar {...props} visible={visible} responseSpeed={responseSpeed} suppressContent />);+ rerender(<RunningStatusBar {...props} visible={visible} suppressContent />);expect(container.childElementCount).toBe(0);},);--it('keeps the control indicator before completed speed metadata but leaves an idle row empty', () => {- const props = { visible: false, status: 'Done', startedAt: null,- tokenUsage: 0, outputTokens: 0, generationDurationMs: 0 };- const view = render(<RunningStatusBar {...props} />);- expect(view.container.childElementCount).toBe(0);- const indicator = <button aria-label="Controlled session">Device</button>;- view.rerender(<RunningStatusBar {...props} rightLeadingSlot={indicator} />);- const control = screen.getByRole('button', { name: 'Controlled session' });- expect(view.container.querySelector('[data-running-status-meta]')).toBeNull();- view.rerender(<RunningStatusBar {...props} rightLeadingSlot={indicator}- responseSpeed={{ phase: 'complete', waitOrigin: 'turn', firstResponseMs: 1000, waitingMs: 0,- durationMs: 1000, outputTokens: 100, estimated: false, averageRate: 100, recentRate: 100,- samples: [{ durationMs: 1000, outputTokens: 100, rate: 100 }], sampledAt: Date.now() }} />);- const meta = view.container.querySelector('[data-running-status-meta]')!;- expect(meta.textContent).toContain('chat.runningStatus.lastGeneration');- expect(control.compareDocumentPosition(meta) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();- fireEvent.click(meta.querySelector('button')!);- expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.finalAverage');-});--it('retains a completed response after fade, navigation/remount, then replaces it at the next turn', () => {- vi.useFakeTimers();- try {- const speed = { phase: 'complete', waitOrigin: 'turn', firstResponseMs: 2000, waitingMs: 0,- durationMs: 4000, outputTokens: 300, estimated: false, averageRate: 75, recentRate: 75,- samples: [{ durationMs: 1000, outputTokens: 100, rate: 100 }], sampledAt: Date.now() } as const;- const props = { visible: false, status: 'Done', startedAt: null, tokenUsage: 500,- outputTokens: 300, generationDurationMs: 4000, responseSpeed: { ...speed, samples: [...speed.samples] } };- const view = render(<RunningStatusBar {...props} />);- act(() => vi.advanceTimersByTime(60_000));- const trigger = () => view.container.querySelector('[data-running-status-meta] button');- expect(trigger()?.textContent).toContain('chat.runningStatus.lastGeneration');- fireEvent.click(trigger()!);- expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.finalAverage');- expect(screen.getByRole('dialog').textContent).toContain('75');- view.unmount();- const restored = render(<RunningStatusBar {...props} />);- expect(restored.container.textContent).toContain('chat.runningStatus.lastGeneration');- restored.rerender(<RunningStatusBar {...props} visible startedAt={Date.now()}- responseSpeed={{ ...props.responseSpeed, phase: 'waiting', firstResponseMs: null, waitingMs: 0,- outputTokens: 0, durationMs: 0, recentRate: null, averageRate: null, samples: [] }} />);- expect(restored.container.textContent).not.toContain('chat.runningStatus.lastGeneration');- expect(restored.container.textContent).toContain('chat.runningStatus.responseWaiting');- } finally { vi.useRealTimers(); }-});--it('expires a stalled live rate while preserving an inspectable curve, and distinguishes tool pause', () => {- vi.useFakeTimers();- try {- const speed = { phase: 'generating', waitOrigin: 'turn', firstResponseMs: 1000, waitingMs: 0,- durationMs: 2000, outputTokens: 80, estimated: true, averageRate: 40, recentRate: 370,- samples: [{ durationMs: 2000, outputTokens: 80, rate: 370 }], sampledAt: Date.now() } as const;- const props = { visible: true, status: 'Generating...', startedAt: Date.now(), tokenUsage: 500,- outputTokens: 0, generationDurationMs: 0, responseSpeed: { ...speed, samples: [...speed.samples] } };- const view = render(<RunningStatusBar {...props} />);- fireEvent.click(view.container.querySelector('[data-running-status-meta] button')!);- expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.currentRate');- act(() => vi.advanceTimersByTime(1000));- expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.responsePending');- expect(view.container.querySelector('[data-running-status-meta] button')?.textContent)- .not.toContain('chat.runningStatus.estimatedTokenRate');- view.rerender(<RunningStatusBar {...props} status="Tool running"- responseSpeed={{ ...props.responseSpeed, phase: 'paused', recentRate: null }} />);- expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.generationPaused');- view.rerender(<RunningStatusBar {...props} status="Running bash…"- responseSpeed={{ ...props.responseSpeed, phase: 'paused', toolActive: true, recentRate: null }} />);- expect(view.container.textContent).toContain('chat.runningStatus.toolRunning');- expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.toolRunning');- view.rerender(<RunningStatusBar {...props}- responseSpeed={{ ...props.responseSpeed, phase: 'waiting', waitingMs: 1000, recentRate: null }} />);- expect(view.container.textContent).toContain('chat.runningStatus.responsePending');- expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.responsePending');- } finally { vi.useRealTimers(); }-});--it.each(['failed', 'cancelled', 'retrying'] as const)('shows %s consistently in the retained entry and card', (activity) => {- const terminal = activity !== 'retrying';- const key = activity === 'failed' ? 'responseFailed' : activity === 'cancelled' ? 'responseCancelled' : 'responseRetrying';- const speed: import('@cindy/maker-shared/usage-format').ResponseSpeedSnapshot = {- phase: terminal ? 'complete' : 'paused', waitOrigin: 'turn', firstResponseMs: 1000, waitingMs: 0,- durationMs: 2000, outputTokens: 80, estimated: true, recentRate: null, averageRate: 40,- samples: [{ durationMs: 2000, outputTokens: 80, rate: 40 }], sampledAt: Date.now(),- ...(terminal ? { outcome: activity as 'failed' | 'cancelled' } : { retrying: true }),- };- const view = render(<RunningStatusBar visible={!terminal} status="Done" startedAt={null}- tokenUsage={500} outputTokens={80} generationDurationMs={2000} responseSpeed={speed} />);- const trigger = view.container.querySelector('[data-running-status-meta] button')!;- expect(trigger.textContent).toContain(`chat.runningStatus.${key}`);- expect(trigger.textContent).not.toContain('chat.runningStatus.tokenRate');- fireEvent.click(trigger);- expect(screen.getByRole('dialog').textContent).toContain(`chat.runningStatus.${key}`);- expect(screen.getByRole('dialog').textContent).not.toContain('chat.runningStatus.finalAverage');- expect(screen.getByRole('dialog').textContent).toContain('40');-});diff --git a/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx b/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsxindex 8d8176257f..258f619711 100644--- a/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx+++ b/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx@@ -32,7 +32,7 @@ it('expires the displayed rate without losing history, including after remount',const view = render(<Probe tokens={0} />);view.rerender(<Probe tokens={100} />);expect(screen.getByTestId('rate').textContent).toBe('100:1');- act(() => vi.advanceTimersByTime(999));+ act(() => vi.advanceTimersByTime(59_999));expect(screen.getByTestId('rate').textContent).toBe('100:1');act(() => vi.advanceTimersByTime(1));expect(screen.getByTestId('rate').textContent).toBe('waiting:1');diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex f05b923b61..ad46527ed2 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -1,4 +1,3 @@-import { responseSpeedActivity, type ResponseSpeedSnapshot } from "@cindy/maker-shared/usage-format";import { formatSessionDuration } from '@/lib/sessionDurationFormat';import { shouldShowOpenPathError } from '../../../shared/openPathResult';import { shouldShowFailedScheduleNotice } from '@cindy/maker-shared/schedule-model';@@ -5154,9 +5153,7 @@ export function CCAgentSessionView({reconnectStatus={reconnectStatus}tokenUsage={agentStatus.tokenUsage}outputTokens={agentStatus.outputTokens ?? 0}- responseSpeed={agentStatus.responseSpeed}generationDurationMs={agentStatus.generationDurationMs ?? 0}- generationActive={agentStatus.generationActive}generationReliable={agentStatus.generationReliable ?? true}startedAt={agentStatus.startedAt}visible={composerRuntimeVisible || (!pendingPlanReview && activeReconnect !== null)}@@ -6041,9 +6038,7 @@ function RunningStatusBar({reconnectStatus = null,tokenUsage,outputTokens = 0,- responseSpeed,generationDurationMs = 0,- generationActive,generationReliable = true,startedAt,visible,@@ -6064,9 +6059,7 @@ function RunningStatusBar({reconnectStatus?: string | null;tokenUsage: number;outputTokens?: number;- responseSpeed?: ResponseSpeedSnapshot;generationDurationMs?: number;- generationActive?: boolean;generationReliable?: boolean;startedAt: number | null;visible: boolean;@@ -6153,23 +6146,13 @@ function RunningStatusBar({const isHidden = suppressContent || (!showContent && !visible);const workflowWaiting = workflowStatus !== undefined;- const completedSpeed = !visible && responseSpeed?.phase === 'complete'- && !reconnecting && !sideTaskRunning && !backgroundTasksRunning && !workflowWaiting;// side-task / 后台子任务运行中永远当成进行态 (即便上一轮 LLM 留下的 status 文案// 是 "Done", 此时任务还在跑, 显示 ✓ 完成图标会让用户以为已经做完)。- const isDone = status === 'Done' && !responseSpeed?.outcome && !responseSpeed?.retrying && !reconnecting && !sideTaskRunning && !backgroundTasksRunning;+ const isDone = status === 'Done' && !reconnecting && !sideTaskRunning && !backgroundTasksRunning;// 后台子任务模式的左段文案:上一轮残留的 status(多半是 "Done")在此语义下是// 误导信息,整体替换为后台运行提示。仅后台 Bash 时用带数量的专属文案 ——// 「模型用量仍在消耗」对不调模型的 bash 任务是错误陈述。- const speedActivity = responseSpeed ? responseSpeedActivity(responseSpeed) : null;- const speedStatusKey = speedActivity === 'failed' ? 'responseFailed'- : speedActivity === 'cancelled' ? 'responseCancelled'- : speedActivity === 'retrying' ? 'responseRetrying'- : speedActivity === 'waiting' || speedActivity === 'quiet' ? 'responsePending'- : speedActivity === 'tool' ? 'toolRunning'- : speedActivity === 'paused' ? 'generationPaused'- : speedActivity === 'generating' ? 'responseGenerating' : null;const displayStatus =reconnectStatus ??workflowStatus ??@@ -6177,8 +6160,7 @@ function RunningStatusBar({? backgroundBashOnlyCount > 0? t('chat.backgroundActivity.bashStatus', { count: backgroundBashOnlyCount }): t('chat.backgroundActivity.status')- : speedStatusKey && !status.toLowerCase().startsWith('compact')- ? t(`chat.runningStatus.${speedStatusKey}`) : localizeAgentStatus(status, t));+ : localizeAgentStatus(status, t));// F-COMPACT-1: when SDK is auto-summarizing the conversation, give the// status bar a distinct icon so the user can tell "Compacting..." apart// from "Thinking..." — both share the shimmer animation by design, but@@ -6242,37 +6224,30 @@ function RunningStatusBar({tokens: formatRunningTokenCount(animatedTokens),});const rateHistory = useRunningTokenRateHistory({- responseSpeed,- generationActive,sessionKey,startedAt,outputTokens,generationDurationMs,generationReliable:- !responseSpeed && generationReliable &&+ generationReliable &&!reconnecting &&!sideTaskRunning &&!backgroundTasksRunning &&!workflowWaiting,});- const latestRate = !responseSpeed && generationActive === false ? null : rateHistory.latestRate;- const legacyUsageMeta = resolveRunningUsageMeta({+ const latestRate = rateHistory.latestRate;+ const usageMeta = resolveRunningUsageMeta({outputTokens,generationDurationMs,generationReliable,tokenUsage,latestRate,});- const usageMeta = responseSpeed- ? responseSpeed.averageRate !== null- ? { kind: 'rate' as const, rate: formatRecentOutputTokenRate(responseSpeed.averageRate) ?? '0' }- : { kind: 'none' as const }- : legacyUsageMeta;const latestRateText = latestRate !== null ? formatRecentOutputTokenRate(latestRate) : null;const rateText =- (!isHidden || completedSpeed) && !reconnecting && usageMeta.kind === 'rate'+ !isHidden && !reconnecting && usageMeta.kind === 'rate'? latestRateText !== null- ? t(responseSpeed && (responseSpeed.phase !== 'complete' || responseSpeed.estimated) ? 'chat.runningStatus.estimatedTokenRate' : 'chat.runningStatus.tokenRate', { rate: latestRateText })+ ? t('chat.runningStatus.tokenRate', { rate: latestRateText }): null: null;@@ -6285,19 +6260,17 @@ function RunningStatusBar({transition: isHidden ? 'none' : `opacity ${STATUS_BAR_FADE_MS}ms ease-out`,pointerEvents: isHidden ? 'none' : 'auto',};- const waitingText = responseSpeed?.phase === 'waiting'- ? t('chat.runningStatus.responseWaiting', { seconds: ((responseSpeed.waitingMs + Math.max(0, Date.now() - responseSpeed.sampledAt)) / 1000).toFixed(1) }) : null;const showRatePanel =!reconnecting &&(ratePanelPinned ||(!workflowWaiting &&!sideTaskRunning &&!backgroundTasksRunning &&- (Boolean(responseSpeed) || usageMeta.kind === 'rate')));+ usageMeta.kind === 'rate'));// A pinned panel keeps its anchor mounted through idle and subsequent turns.- // 已完成测量保留原速度入口;没有测量的空闲任务仍收起。overlay 的 ResizeObserver 会在+ // 空闲后真正收起,不再给输入框上方留下固定空行。overlay 的 ResizeObserver 会在// DOM 尺寸变化后补齐 MessageStream 的 bottomPadding,因此不靠硬编码高度制造跳变。- if (!rightLeadingSlot && (suppressContent || (isHidden && !ratePanelPinned && !completedSpeed))) return null;+ if (!rightLeadingSlot && (suppressContent || (isHidden && !ratePanelPinned))) return null;// 两段式布局:左(运行状态) / 右(elapsed·tokens)。// - 左段 min-w-0(可收缩):status 并非短枚举 —— turn-start 文案带用户名(可含中文长句)、@@ -6359,21 +6332,16 @@ function RunningStatusBar({走 LLM, 显示残留 token 计数会误导用户以为也耗了 token。 */}<div className="flex min-w-0 items-center justify-self-end gap-2">{rightLeadingSlot}- {(!suppressContent && (!isHidden || ratePanelPinned || completedSpeed)) && (+ {(!suppressContent && (!isHidden || ratePanelPinned)) && (<divdata-running-status-meta="true"className="flex min-w-0 items-center gap-[6px]"- style={ratePanelPinned || completedSpeed ? undefined : fadeStyle}- aria-hidden={isHidden && !ratePanelPinned && !completedSpeed}+ style={ratePanelPinned ? undefined : fadeStyle}+ aria-hidden={isHidden && !ratePanelPinned}>{showRatePanel && (<RunningTokenRatePopover- responseSpeed={responseSpeed}- elapsedText={completedSpeed- ? t(responseSpeed?.outcome === 'failed' ? 'chat.runningStatus.responseFailed'- : responseSpeed?.outcome === 'cancelled' ? 'chat.runningStatus.responseCancelled' : 'chat.runningStatus.lastGeneration')- : speedActivity === 'retrying' ? t('chat.runningStatus.responseRetrying')- : waitingText ?? (speedActivity === 'quiet' ? t('chat.runningStatus.responsePending') : elapsedText)}+ elapsedText={elapsedText}rate={latestRateText}rateText={workflowWaiting || sideTaskRunning || backgroundTasksRunning@@ -6384,8 +6352,8 @@ function RunningStatusBar({}isTokenCount={usageMeta.kind === 'tokens'}averageRate={usageMeta.kind === 'rate' ? usageMeta.rate : null}- outputTokens={responseSpeed?.outputTokens ?? outputTokens}- history={latestRate === rateHistory.latestRate ? rateHistory : { ...rateHistory, latestRate }}+ outputTokens={outputTokens}+ 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 b9e431524e..665e3ddf13 100644--- a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx@@ -1,5 +1,3 @@-import type { ResponseSpeedSnapshot } from "@cindy/maker-shared/usage-format";-import { responseSpeedActivity, responseSpeedHistory } from "@cindy/maker-shared/usage-format";import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { Activity, ArrowDown, X } from 'lucide-react';@@ -17,15 +15,13 @@ import {export function useRunningTokenRateHistory(input: {/** 会话身份:用于进程内缓存速度历史,切任务再切回不清零(重启应用清零)。 */- responseSpeed?: ResponseSpeedSnapshot;sessionKey: string | null;startedAt: number | null;outputTokens: number;generationDurationMs: number;generationReliable: boolean;- generationActive?: boolean;}) {- const { sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, generationActive } = input;+ const { sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable } = input;// 挂载时从按会话的进程内缓存播种:RunningStatusBar 以 sessionId 为 key,// 切走再切回是全新挂载,历史从缓存恢复而不是从零开始。const [history, setHistory] = useState<RateHistory>(() => {@@ -36,39 +32,36 @@ export function useRunningTokenRateHistory(input: {return startedAt === null ? { ...cached, baseline: null, lastReport: null } : cached;});useEffect(() => {- setHistory((previous) => {- const recorded = recordRunningTokenRate(previous, {+ setHistory((previous) =>+ recordRunningTokenRate(previous, {startedAt,outputTokens,generationDurationMs,generationReliable,- });- return generationActive === false ? { ...recorded, latestRate: null, latestSampleAt: undefined } : recorded;- });- }, [startedAt, outputTokens, generationDurationMs, generationReliable, generationActive]);+ }),+ );+ }, [startedAt, outputTokens, generationDurationMs, generationReliable]);useEffect(() => {if (sessionKey) saveCachedRateHistory(sessionKey, history);}, [sessionKey, history]);const [now, setNow] = useState(Date.now);useEffect(() => {- const timestamp = input.responseSpeed?.sampledAt ?? history.latestSampleAt;- if (timestamp === undefined || (input.responseSpeed ? input.responseSpeed.phase !== 'generating' : history.latestRate === null)) return;+ const timestamp = history.latestSampleAt;+ if (timestamp === undefined || history.latestRate === null) return;setNow(Date.now());const timer = setTimeout(() => setNow(Date.now()),Math.max(0, timestamp + RATE_SAMPLE_FRESH_MS - Date.now()));return () => clearTimeout(timer);- }, [history.latestSampleAt, history.latestRate, input.responseSpeed]);+ }, [history.latestSampleAt, history.latestRate]);const visibleHistory = history.latestSampleAt === undefined ||Math.max(now, Date.now()) - history.latestSampleAt >= RATE_SAMPLE_FRESH_MS? { ...history, latestRate: null } : history;- if (input.responseSpeed) return responseSpeedHistory(input.responseSpeed, Math.max(now, Date.now()));return startedAt === null || history.startedAt === startedAt? visibleHistory: { ...history, startedAt, baseline: null, latestRate: null };}export function RunningTokenRatePopover({- responseSpeed,elapsedText,rate,rateText,@@ -78,7 +71,6 @@ export function RunningTokenRatePopover({history,onPinnedChange,}: {- responseSpeed?: ResponseSpeedSnapshot;elapsedText: string;rate: string | null;rateText: string | null;@@ -92,8 +84,6 @@ export function RunningTokenRatePopover({const [mode, setMode] = useState<'idle' | 'hover' | 'pinned' | 'dismissed'>('idle');const open = mode === 'pinned';useEffect(() => onPinnedChange?.(open), [open, onPinnedChange]);- const approximate = (value: string | null, estimated = true) => value && estimated- ? t('chat.runningStatus.estimatedValue', { value }) : value;const samples = history.samples;const firstTime = samples[0]?.durationMs ?? 0;const span = (samples.at(-1)?.durationMs ?? 0) - firstTime;@@ -104,7 +94,6 @@ export function RunningTokenRatePopover({}));const line = points.map((point, index) => `${index ? 'L' : 'M'}${point.x},${point.y}`).join(' ');const last = points.at(-1);- const activity = responseSpeed ? responseSpeedActivity(responseSpeed) : null;const card = (<divaria-description={t('chat.runningStatus.tokenRateDescription')}@@ -114,17 +103,10 @@ export function RunningTokenRatePopover({<div className="col-start-1 row-start-1 min-w-0 self-center"><div className="mb-1 flex items-center gap-1.5 text-12 text-[var(--text-secondary)]"><Activity size={14} aria-hidden="true" />- {t(activity === 'failed' ? 'chat.runningStatus.responseFailed'- : activity === 'cancelled' ? 'chat.runningStatus.responseCancelled'- : activity === 'retrying' ? 'chat.runningStatus.responseRetrying'- : activity === 'complete' ? 'chat.runningStatus.finalAverage'- : activity === 'waiting' ? 'chat.runningStatus.responsePending'- : activity === 'tool' ? 'chat.runningStatus.toolRunning'- : activity === 'paused' ? 'chat.runningStatus.generationPaused'- : activity === 'quiet' ? 'chat.runningStatus.responsePending' : 'chat.runningStatus.currentRate')}+ {t('chat.runningStatus.currentRate')}</div><div className="flex items-baseline gap-1.5 tabular-nums">- <span className="text-28 font-medium leading-none">{approximate(rate, Boolean(responseSpeed) && (responseSpeed?.phase !== 'complete' || responseSpeed.estimated)) ?? '—'}</span>+ <span className="text-28 font-medium leading-none">{rate ?? '—'}</span><span className="text-12 text-[var(--text-secondary)]">{t('chat.runningStatus.tokenRateUnit')}</span>@@ -155,14 +137,14 @@ export function RunningTokenRatePopover({<div className="flex items-center gap-2"><dt className="text-[var(--text-secondary)]">{t('chat.runningStatus.averageRate')}</dt><dd className="font-medium">- {averageRate ? t('chat.runningStatus.tokenRate', { rate: approximate(averageRate, responseSpeed?.estimated ?? false) }) : '—'}+ {averageRate ? t('chat.runningStatus.tokenRate', { rate: averageRate }) : '—'}</dd></div><div className="flex items-center gap-2"><dt className="text-[var(--text-secondary)]">{t('chat.runningStatus.outputTotal')}</dt><dd className="font-medium">{t('chat.runningStatus.tokenCount', {- tokens: approximate(formatRunningTokenCount(outputTokens), responseSpeed?.estimated ?? false),+ tokens: formatRunningTokenCount(outputTokens),})}</dd></div>@@ -171,18 +153,12 @@ export function RunningTokenRatePopover({<dd className="font-medium">{samples.length > 0? t('chat.runningStatus.tokenRate', {- rate: approximate(formatRecentOutputTokenRate(history.peak), Boolean(responseSpeed)),+ rate: formatRecentOutputTokenRate(history.peak),}): '—'}</dd></div></dl>- {responseSpeed && (- <dl className="col-span-2 flex items-center justify-between gap-3 text-12 tabular-nums" title={t(`chat.runningStatus.${responseSpeed.waitOrigin === 'stream' ? 'streamWaitDescription' : 'turnWaitDescription'}`)}>- <dt className="text-[var(--text-secondary)]">{t(`chat.runningStatus.${responseSpeed.waitOrigin === 'stream' ? 'streamWait' : 'firstResponse'}`)}</dt>- <dd>{responseSpeed.firstResponseMs === null ? '—' : t('chat.runningStatus.waitSeconds', { seconds: (responseSpeed.firstResponseMs / 1000).toFixed(1) })}</dd>- </dl>- )}</div></div>);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7138415b47..1eaffb5c96 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10146,25 +10146,8 @@"observedPeak": "Peak","tokenRate": "{{rate}} tok/s","tokenRateUnit": "tok/s",- "tokenRateDescription": "Streaming rates and peaks are estimates. Response totals are calibrated with reported usage. Tool execution and request waits are excluded.",- "tokenCount": "{{tokens}} tok",- "estimatedValue": "≈{{value}}",- "estimatedTokenRate": "≈{{rate}} tok/s",- "responseWaiting": "Waiting {{seconds}}s",- "waitSeconds": "{{seconds}}s",- "firstResponse": "First response",- "streamWait": "Stream wait",- "turnWaitDescription": "From the local provider turn start to the first observed text, thinking or tool content. This is not network latency.",- "streamWaitDescription": "From SDK stream start to the first content block. The earlier request wait is not observable.",- "lastGeneration": "Last generation",- "finalAverage": "Final average",- "generationPaused": "Generation paused",- "responsePending": "Waiting for response",- "responseFailed": "Request failed",- "responseCancelled": "Stopped",- "responseRetrying": "Retrying",- "responseGenerating": "Generating",- "toolRunning": "Running tool"+ "tokenRateDescription": "Latest generation interval. Excludes tools and waits.",+ "tokenCount": "{{tokens}} tok"},"shareImage": {"entry": "Share as Image",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 7dc8ba3ed9..b6979335eb 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10123,25 +10123,8 @@"observedPeak": "ピーク","tokenRate": "{{rate}} tok/s","tokenRateUnit": "tok/s",- "tokenRateDescription": "リアルタイム速度とピークは推定値です。応答後に実使用量で補正し、ツール実行とリクエスト待機は除外します。",- "tokenCount": "{{tokens}} tok",- "estimatedValue": "約{{value}}",- "estimatedTokenRate": "約{{rate}} tok/s",- "responseWaiting": "待機 {{seconds}}秒",- "waitSeconds": "{{seconds}}秒",- "firstResponse": "初回応答",- "streamWait": "ストリーム内待機",- "turnWaitDescription": "ローカルでの実行開始から最初のテキスト、思考、ツール内容まで。ネットワーク遅延とは異なります。",- "streamWaitDescription": "SDK ストリーム開始から最初のコンテンツまで。それ以前のリクエスト待機は測定できません。",- "lastGeneration": "前回の生成",- "finalAverage": "最終平均",- "generationPaused": "生成を一時停止",- "responsePending": "応答待ち",- "responseFailed": "リクエスト失敗",- "responseCancelled": "停止済み",- "responseRetrying": "再試行中",- "responseGenerating": "生成中",- "toolRunning": "ツール実行中"+ "tokenRateDescription": "直近の生成区間の速度。ツール実行と待機は除きます。",+ "tokenCount": "{{tokens}} tok"},"shareImage": {"entry": "画像として共有",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 241029a59e..71ee7e90f9 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10123,25 +10123,8 @@"observedPeak": "최고","tokenRate": "{{rate}} tok/s","tokenRateUnit": "tok/s",- "tokenRateDescription": "실시간 속도와 최고 속도는 추정값입니다. 응답 후 실제 사용량으로 보정하며 도구 실행과 요청 대기는 제외합니다.",- "tokenCount": "{{tokens}} tok",- "estimatedValue": "약 {{value}}",- "estimatedTokenRate": "약 {{rate}} tok/s",- "responseWaiting": "대기 {{seconds}}초",- "waitSeconds": "{{seconds}}초",- "firstResponse": "첫 응답",- "streamWait": "스트림 내 대기",- "turnWaitDescription": "로컬 제공자 턴 시작부터 첫 텍스트, 사고 또는 도구 내용까지의 시간입니다. 네트워크 지연과는 다릅니다.",- "streamWaitDescription": "SDK 스트림 시작부터 첫 콘텐츠까지의 시간입니다. 그 이전의 요청 대기는 측정할 수 없습니다.",- "lastGeneration": "지난 생성",- "finalAverage": "최종 평균",- "generationPaused": "생성 일시 중지",- "responsePending": "응답 대기 중",- "responseFailed": "요청 실패",- "responseCancelled": "중지됨",- "responseRetrying": "다시 시도 중",- "responseGenerating": "생성 중",- "toolRunning": "도구 실행 중"+ "tokenRateDescription": "최근 생성 구간의 속도. 도구 실행과 대기는 제외합니다.",+ "tokenCount": "{{tokens}} tok"},"shareImage": {"entry": "이미지로 공유",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 34a8fd0348..fc37d0ddfd 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10123,25 +10123,8 @@"observedPeak": "峰值","tokenRate": "{{rate}} tok/s","tokenRateUnit": "tok/s",- "tokenRateDescription": "实时速度和峰值为估算。响应结束后用真实用量校准;不计工具执行和请求等待。",- "tokenCount": "{{tokens}} tok",- "estimatedValue": "约{{value}}",- "estimatedTokenRate": "约{{rate}} tok/s",- "responseWaiting": "等待 {{seconds}}秒",- "waitSeconds": "{{seconds}}秒",- "firstResponse": "首响应",- "streamWait": "流内等待",- "turnWaitDescription": "从本地收到引擎开始到首个文字、思考或工具内容,不等同于网络延迟。",- "streamWaitDescription": "从 SDK 流开始到首个内容块,之前的请求等待不可测。",- "lastGeneration": "上次生成",- "finalAverage": "最终平均",- "generationPaused": "生成暂停",- "responsePending": "等待响应",- "responseFailed": "请求失败",- "responseCancelled": "已停止",- "responseRetrying": "正在重试",- "responseGenerating": "正在生成",- "toolRunning": "执行工具中"+ "tokenRateDescription": "最近一段生成速度,不含工具执行与等待。",+ "tokenCount": "{{tokens}} tok"},"shareImage": {"entry": "分享为图片",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex c8b6c70ad0..24cfcb6100 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10122,25 +10122,8 @@"observedPeak": "峰值","tokenRate": "{{rate}} tok/s","tokenRateUnit": "tok/s",- "tokenRateDescription": "即時速度和峰值為估算。回應結束後以實際用量校準;不計工具執行和請求等待。",- "tokenCount": "{{tokens}} tok",- "estimatedValue": "約{{value}}",- "estimatedTokenRate": "約{{rate}} tok/s",- "responseWaiting": "等待 {{seconds}}秒",- "waitSeconds": "{{seconds}}秒",- "firstResponse": "首回應",- "streamWait": "流內等待",- "turnWaitDescription": "從本機收到引擎開始到首個文字、思考或工具內容,不等同於網路延遲。",- "streamWaitDescription": "從 SDK 串流開始到首個內容區塊,之前的請求等待無法測量。",- "lastGeneration": "上次生成",- "finalAverage": "最終平均",- "generationPaused": "生成暫停",- "responsePending": "等待回應",- "responseFailed": "請求失敗",- "responseCancelled": "已停止",- "responseRetrying": "正在重試",- "responseGenerating": "正在生成",- "toolRunning": "執行工具中"+ "tokenRateDescription": "最近一段生成速度,不含工具執行與等待。",+ "tokenCount": "{{tokens}} tok"},"shareImage": {"entry": "分享為圖片",diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 42a97e3887..8967850772 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -1,4 +1,3 @@-import { readResponseSpeedSnapshot, stopResponseSpeed, retryResponseSpeed, resumeResponseSpeed, mergeResponseSpeedStatus, type ResponseSpeedSnapshot } from '@cindy/maker-shared/usage-format';import { readBotTaskResults } from '@cindy/maker-shared/botCollaboration';import { remotePluginSetupErrorCode, type PluginSetupCommandError } from './pluginSetupCommandError';export type { PluginSetupCommandError } from './pluginSetupCommandError';@@ -731,7 +730,6 @@ export interface AgentStatus {/** Turn-cumulative output tokens for live TPS. */outputTokens?: number;/** Generation-only milliseconds including any open interval at emit time. */- responseSpeed?: ResponseSpeedSnapshot;generationDurationMs?: number;/** True while the model currently owns the turn. */generationActive?: boolean;@@ -5576,18 +5574,10 @@ export function handleStreamEvent(const hasCodexReconnectRecoveryOutput = isCodexReconnectRecoveryOutput(event);const shouldClearCodexReconnectPendingCard =event.type === 'error' ? !isCodexReconnectProgress : hasCodexReconnectRecoveryOutput;- const resumedSpeed = ((event.type === 'text' || event.type === 'thinking') &&- typeof (event.data as { text?: unknown })?.text === 'string' &&- Boolean((event.data as { text: string }).text)) ||- (event.type === 'tool_use' && hasCodexReconnectRecoveryOutput)- ? resumeResponseSpeed(inputState.agentStatus.responseSpeed) : inputState.agentStatus.responseSpeed;- const stateBeforeReconnectCleanup = resumedSpeed === inputState.agentStatus.responseSpeed &&- (!hasCodexReconnectRecoveryOutput || inputState.recoverableError == null) ? inputState : {- ...inputState,- recoverableError: hasCodexReconnectRecoveryOutput ? null : inputState.recoverableError,- agentStatus: resumedSpeed === inputState.agentStatus.responseSpeed ? inputState.agentStatus- : { ...inputState.agentStatus, responseSpeed: resumedSpeed },- };+ const stateBeforeReconnectCleanup =+ !hasCodexReconnectRecoveryOutput || inputState.recoverableError == null+ ? inputState+ : { ...inputState, recoverableError: null };const messagesAfterReconnectCleanup = shouldClearCodexReconnectPendingCard? removeCodexReconnectPendingCard(stateBeforeReconnectCleanup.messages): stateBeforeReconnectCleanup.messages;@@ -6240,15 +6230,14 @@ export function handleStreamEvent(});const terminalData = event.data as- | { cancelled?: unknown; status?: unknown; reason?: unknown; plan?: unknown; raw?: { id?: unknown; status?: unknown } }+ | { cancelled?: unknown; reason?: unknown; plan?: unknown; raw?: { id?: unknown; status?: unknown } }| null| undefined;const terminalTurnId = typeof terminalData?.raw?.id === 'string' ? terminalData.raw.id : null;const terminalTurnStatus =typeof terminalData?.raw?.status === 'string' ? terminalData.raw.status : null;const terminalCancelled =- terminalData?.cancelled === true || terminalData?.status === 'cancelled' ||- terminalData?.reason === 'send_cancelled_before_acceptance' ||+ terminalData?.cancelled === true ||terminalData?.reason === 'turn_continuation_cancelled' ||terminalData?.reason === 'user_stop_unconfirmed_wake_tasks';const doneMessages =@@ -6305,10 +6294,6 @@ export function handleStreamEvent(turnStoppedByUser: state.turnStoppedByUser || terminalCancelled,agentStatus: {...state.agentStatus,- responseSpeed: stopResponseSpeed(state.agentStatus.responseSpeed,- state.turnStoppedByUser || terminalCancelled ? 'cancelled'- : terminalTurnStatus === 'failed' || terminalData?.status === 'failed' || finalized.error ? 'failed' : undefined),- generationActive: false,isRunning: false,startedAt: null,},@@ -6425,8 +6410,6 @@ export function handleStreamEvent(isRunning: true,startedAt: state.agentStatus.startedAt ?? Date.now(),}),- responseSpeed: (event.data as { willRetry?: boolean })?.willRetry === true- ? retryResponseSpeed(state.agentStatus.responseSpeed) : state.agentStatus.responseSpeed,},};}@@ -6446,8 +6429,6 @@ export function handleStreamEvent(isStreaming: true,agentStatus: {...state.agentStatus,- responseSpeed: (event.data as { willRetry?: boolean })?.willRetry === true- ? retryResponseSpeed(state.agentStatus.responseSpeed) : state.agentStatus.responseSpeed,isRunning: true,startedAt: state.agentStatus.startedAt ?? Date.now(),},@@ -6540,10 +6521,6 @@ export function handleStreamEvent(// 初始 "Let's go" 文案上 shimmer 闪个不停(done 路径有同样的复位)。agentStatus: {...state.agentStatus,- responseSpeed: suppressAutoResumeBroadcastError || isPlannedUpgradeClose- ? stopResponseSpeed(state.agentStatus.responseSpeed)- : stopResponseSpeed(state.agentStatus.responseSpeed, state.turnStoppedByUser ? 'cancelled' : 'failed'),- generationActive: false,isRunning: false,startedAt: null,},@@ -7056,8 +7033,6 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatStateturnStoppedByUser: false,agentStatus: {...finalized.agentStatus,- responseSpeed: stopResponseSpeed(finalized.agentStatus.responseSpeed),- generationActive: false,isRunning: false,startedAt: null,},@@ -7070,7 +7045,7 @@ function mergeLiveGenerationStatus(previous: AgentStatus,): Pick<AgentStatus,- 'outputTokens' | 'generationDurationMs' | 'generationActive' | 'generationReliable' | 'responseSpeed'+ 'outputTokens' | 'generationDurationMs' | 'generationActive' | 'generationReliable'> {// Turn start drops leftover metrics from the previous turn, then keeps any// live fields carried by this same status. A reconnect-shaped first event@@ -7078,7 +7053,6 @@ function mergeLiveGenerationStatus(// zero the values that just arrived.const baseline = isTurnStart? {- responseSpeed: undefined,outputTokens: 0,generationDurationMs: 0,generationActive: false,@@ -7092,8 +7066,6 @@ function mergeLiveGenerationStatus(typeof update.generationReliable === 'boolean';if (!hasLiveFields) {return {- responseSpeed: mergeResponseSpeedStatus(previous.responseSpeed,- readResponseSpeedSnapshot(update.responseSpeed, Date.now()), update.isRunning, isTurnStart),outputTokens: baseline.outputTokens,generationDurationMs: baseline.generationDurationMs,generationActive: update.isRunning ? baseline.generationActive : false,@@ -7101,8 +7073,6 @@ function mergeLiveGenerationStatus(};}const merged = {- responseSpeed: mergeResponseSpeedStatus(previous.responseSpeed,- readResponseSpeedSnapshot(update.responseSpeed, Date.now()), update.isRunning, isTurnStart),outputTokens:typeof update.outputTokens === 'number' ? update.outputTokens : baseline.outputTokens,generationDurationMs:@@ -15639,8 +15609,6 @@ function stopSession(costUsd: s.agentStatus.costUsd,contextTokens: s.agentStatus.contextTokens,contextWindow: s.agentStatus.contextWindow,- responseSpeed: stopResponseSpeed(s.agentStatus.responseSpeed, 'cancelled'),- generationActive: false,isRunning: false,startedAt: null,},diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 115c0a8370..b66ee6b98e 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -806,7 +806,6 @@ interface CCAgentPermissionDismissedPayload {}interface CCAgentStatusUpdate {- responseSpeed?: import("@cindy/maker-shared/usage-format").ResponseSpeedSnapshot;sessionId: string;status: string;tokenUsage: number;diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 8e7534844e..b6e2080701 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -1,5 +1,3 @@-import { responseSpeedActivity, responseSpeedHistory } from "@cindy/maker-shared/usage-format";-import type { ResponseSpeedSnapshot } from "@cindy/maker-shared/usage-format";import { modelNeedsReselection } from '@/session/modelReselection';import { getCachedDeviceProviders } from '@/device-link/deviceProvidersCache';import { MountOnFirstOpen } from '@/session/MountOnFirstOpen';@@ -10280,7 +10278,7 @@ export default function SessionScreen() {例外:新建任务慢发送时这一行要说明卡在哪一步,不能被同步占位藏掉。判据必须带 messageCount:syncingWhileEmpty 只要 loading 就为真,而收口后还会再来几轮 load(实测日志),只看它会让已有消息的会话反复熄灭活动条。 */}- {!companionChat && (showComposerActivity || pendingRecoveryStatus || remoteSessionRunStatus.responseSpeed?.phase === 'complete') && (creationSlowPhase !== null || !(syncingWhileEmpty && !hasRenderedMessages)) ? (+ {!companionChat && (showComposerActivity || pendingRecoveryStatus) && (creationSlowPhase !== null || !(syncingWhileEmpty && !hasRenderedMessages)) ? (<Viewstyle={[styles.composerActivityFrame,@@ -10299,7 +10297,6 @@ export default function SessionScreen() {streaming={isSessionStreaming}tokenUsage={composerActivityTokenUsage}outputTokens={remoteSessionRunStatus.outputTokens}- responseSpeed={remoteSessionRunStatus.responseSpeed}generationDurationMs={remoteSessionRunStatus.generationDurationMs}generationReliable={remoteSessionRunStatus.generationReliable}generationActive={remoteSessionRunStatus.generationActive}@@ -12192,7 +12189,6 @@ function ComposerActivityStatus({rateStartedAt = startedAt,streaming = false,tokenUsage,- responseSpeed,outputTokens,generationDurationMs,generationReliable,@@ -12210,7 +12206,6 @@ function ComposerActivityStatus({rateStartedAt?: number | null;streaming?: boolean;tokenUsage: number;- responseSpeed?: ResponseSpeedSnapshot;outputTokens: number;generationDurationMs: number;generationReliable: boolean;@@ -12241,9 +12236,8 @@ function ComposerActivityStatus({// Elapsed uses the local fallback. Sampling keeps the raw remote start so a// terminal null is not a new turn, and a local send is not the previous rate.const samplerStartedAt = rateStartedAt === undefined ? startedAt : rateStartedAt;- const legacyRateHistory = useRunningTokenRateHistory({+ const rateHistory = useRunningTokenRateHistory({sessionKey,- generationActive,startedAt: samplerStartedAt,outputTokens,generationDurationMs,@@ -12251,10 +12245,6 @@ function ComposerActivityStatus({streaming,});- const rateHistory = responseSpeed ? responseSpeedHistory(responseSpeed)- : generationActive === false ? { ...legacyRateHistory, latestRate: null } : legacyRateHistory;- const completedSpeed = !visible && responseSpeed?.phase === 'complete';- const speedActivity = responseSpeed ? responseSpeedActivity(responseSpeed) : null;if (pendingRecovery && !reconnectAttempt) {// 自愈 / 换电脑进行中:只显示这一行状态,不带耗时与速率(这一轮还没有结局)。return (@@ -12273,29 +12263,22 @@ function ComposerActivityStatus({</View>);}- if (!visible && !completedSpeed) return null;-- const elapsedText = completedSpeed- ? t(responseSpeed?.outcome === 'failed' ? 'session.screen.responseFailed'- : responseSpeed?.outcome === 'cancelled' ? 'session.screen.responseCancelled' : 'session.screen.lastGeneration')- : speedActivity === 'retrying' ? t('session.screen.responseRetrying')- : responseSpeed?.phase === 'waiting'- ? t('session.screen.responseWaiting', { seconds: ((responseSpeed.waitingMs + Math.max(0, Date.now() - responseSpeed.sampledAt)) / 1000).toFixed(1) })- : speedActivity === 'quiet' ? t('session.screen.responsePending') : formatComposerActivityElapsed(elapsed);+ if (!visible) return null;++ const elapsedText = formatComposerActivityElapsed(elapsed);const tokenCount = formatComposerActivityTokenCount(tokenUsage);const tokenText = t('session.screen.tokenCount', { tokens: tokenCount });const tokenA11yText = t('session.screen.tokenCountFull', { tokens: tokenCount });const showElapsedOnly = sideTaskRunning || Boolean(reconnectAttempt);const rateValue = formatComposerActivityRateValue(showElapsedOnly ? null : rateHistory.latestRate);- const canShowRateDetails = !showElapsedOnly && (Boolean(responseSpeed) || (generationReliable+ const canShowRateDetails = !showElapsedOnly+ && generationReliable&& outputTokens > 0&& Number.isFinite(outputTokens)&& Number.isFinite(generationDurationMs)- && generationDurationMs > 0));+ && generationDurationMs > 0;const rateText = rateValue- ? responseSpeed && (responseSpeed.phase !== 'complete' || responseSpeed.estimated)- ? t('session.screen.estimatedTokenRate', { rate: rateValue })- : t('session.screen.tokenRate', { rate: rateValue })+ ? t('session.screen.tokenRate', { rate: rateValue }): null;const showUsageMeta = !showElapsedOnly && (Boolean(rateText) || tokenUsage > 0);const usageMeta = (@@ -12337,15 +12320,9 @@ function ComposerActivityStatus({? 'session.screen.rateLimitRetrying': 'session.screen.networkReconnecting',)- // 发送等待超过阈值时,同一行先说明卡在哪一步;创建完成后回到下面的「思考中」等状态。+ // 发送等待超过阈值时,同一行先说明卡在哪一步;创建完成后回到「思考中」。: slowSendPhase ? t(`session.new.slowSend.${slowSendPhase}`)- : t(speedActivity === 'failed' ? 'session.screen.responseFailed'- : speedActivity === 'cancelled' ? 'session.screen.responseCancelled'- : speedActivity === 'retrying' ? 'session.screen.responseRetrying'- : speedActivity === 'waiting' || speedActivity === 'quiet' ? 'session.screen.responsePending'- : speedActivity === 'tool' ? 'session.screen.toolRunning'- : speedActivity === 'paused' ? 'session.screen.generationPaused'- : speedActivity === 'generating' ? 'session.screen.responseGenerating' : 'session.screen.thinking');+ : t('session.screen.thinking');return (<View@@ -12353,15 +12330,14 @@ function ComposerActivityStatus({style={pillStyles.composerActivityStatus}testID="session.composerActivityStatus">- {visible && <ComposerActivityPill label={activityText} live={Boolean(slowSendPhase) && !reconnectAttempt}>+ <ComposerActivityPill label={activityText} live={Boolean(slowSendPhase) && !reconnectAttempt}>{reconnectAttempt ? (<Text style={[pillStyles.composerActivityStatusText, pillStyles.composerActivityProgressText]}>{reconnectAttempt.attempt}/{reconnectAttempt.maxAttempts}</Text>) : null}- </ComposerActivityPill>}+ </ComposerActivityPill><RunningTokenRatePopover- responseSpeed={responseSpeed}key={sessionKey}enabled={canShowRateDetails}availableRegion={availableRegion}diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex fb9a0360da..07103c6503 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -6785,60 +6785,3 @@ describe('list message reuse', () => {expect(remoteSessionStore.getMessages('s1')).toEqual([]);});});--it('retains response speed per session at completion, freezes aborts and clears the next turn', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('tps-one'), session('tps-two')]);- const speed = { phase: 'generating', waitOrigin: 'turn', firstResponseMs: 2000, waitingMs: 0,- durationMs: 3000, outputTokens: 50, estimated: true, averageRate: 16.7, recentRate: 20,- samples: [{ durationMs: 1000, outputTokens: 20, rate: 20 }], sampledAt: 1 };- pushMakerStatus('tps-one', { isRunning: true, responseSpeed: speed });- remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {- sessionId: 'tps-one', event: { type: 'error', data: { message: 'cancelled', isTerminal: true } },- });- expect(remoteSessionStore.getSessionRunStatus('tps-one').responseSpeed)- .toMatchObject({ phase: 'complete', estimated: true, outputTokens: 50 });- expect(remoteSessionStore.getSessionRunStatus('tps-two').responseSpeed).toBeUndefined();- pushMakerStatus('tps-two', { isRunning: true });- expect(remoteSessionStore.getSessionRunStatus('tps-one').responseSpeed?.outputTokens).toBe(50);- pushMakerStatus('tps-one', { isRunning: true, responseSpeed: { ...speed, phase: 'waiting',- firstResponseMs: null, outputTokens: 0, durationMs: 0, samples: [] } });- expect(remoteSessionStore.getSessionRunStatus('tps-one').responseSpeed)- .toMatchObject({ phase: 'waiting', firstResponseMs: null, outputTokens: 0, samples: [] });- pushMakerStatus('tps-one', { isRunning: false, responseSpeed: { ...speed, phase: 'complete',- outputTokens: 300, estimated: false, averageRate: 100, recentRate: 100 } });- expect(remoteSessionStore.getSessionRunStatus('tps-one').responseSpeed)- .toMatchObject({ phase: 'complete', estimated: false, outputTokens: 300 });-});--it('keeps response speed failures through terminal tails, distinguishes cancellation and actual retries', () => {- remoteSessionStore.clear();- remoteSessionStore.setDeviceSessions('dev-1', 'Host', [session('speed-errors')]);- remoteSessionStore.enterSessionMessageDetail('speed-errors');- const speed = { phase: 'generating', waitOrigin: 'turn', firstResponseMs: 1000, waitingMs: 0,- durationMs: 2000, outputTokens: 50, estimated: true, averageRate: 25, recentRate: 30,- samples: [{ durationMs: 2000, outputTokens: 50, rate: 30 }], sampledAt: Date.now() };- const event = (type: string, data: Record<string, unknown>) => remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {- sessionId: 'speed-errors', event: { type, data, source: 'pi' },- });- pushMakerStatus('speed-errors', { isRunning: true, responseSpeed: speed });- event('error', { message: 'temporary warning', isTerminal: false });- expect(remoteSessionStore.getSessionRunStatus('speed-errors').responseSpeed?.retrying).not.toBe(true);- event('error', { message: 'API unavailable', isTerminal: false, willRetry: true });- expect(remoteSessionStore.getSessionRunStatus('speed-errors').responseSpeed).toMatchObject({ retrying: true, recentRate: null });- pushMakerStatus('speed-errors', { isRunning: true, responseSpeed: speed });- expect(remoteSessionStore.getSessionRunStatus('speed-errors').responseSpeed?.retrying).toBe(true);- event('thinking', { stage: 'delta', blockId: 'recovered-thinking', text: 'reasoning resumed' });- expect(remoteSessionStore.getSessionRunStatus('speed-errors').responseSpeed?.retrying).toBe(false);- event('error', { message: 'API unavailable', isTerminal: true });- event('done', {});- pushMakerStatus('speed-errors', { isRunning: false, responseSpeed: { ...speed, phase: 'complete', estimated: false } });- expect(remoteSessionStore.getSessionRunStatus('speed-errors')).toMatchObject({ isRunning: false, hasTerminalError: true,- responseSpeed: { outcome: 'failed', recentRate: null, samples: speed.samples } });- pushMakerStatus('speed-errors', { isRunning: true, responseSpeed: speed });- expect(remoteSessionStore.getSessionRunStatus('speed-errors').responseSpeed?.outcome).toBeUndefined();- event('done', { type: 'pi/agent_settled', status: 'cancelled' });- event('error', { message: 'aborted transport', isTerminal: true });- expect(remoteSessionStore.getSessionRunStatus('speed-errors')).toMatchObject({ hasTerminalError: false,- responseSpeed: { outcome: 'cancelled', recentRate: null } });- remoteSessionStore.clear();-});diff --git a/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx b/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsxindex b1d0aca26d..2f90f5e316 100644--- a/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx+++ b/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx@@ -47,15 +47,15 @@ it('waits for a paired interval and shows its rate instead of the turn average',expect(report({ outputTokens: 1100, generationDurationMs: 12_000 })).toBe('50');// Clock ticks and time-only reports do not manufacture slower throughput.act(() => vi.advanceTimersByTime(5000));- expect(host.textContent).toBe('waiting');- expect(report({ generationDurationMs: 14_000 })).toBe('waiting');+ expect(host.textContent).toBe('50');+ expect(report({ generationDurationMs: 14_000 })).toBe('50');expect(report({ outputTokens: 1140 })).toBe('20');});-it('expires stale samples after the one-second observation window and resumes on a new paired report', () => {+it('expires stale samples after 60 seconds and resumes on a new paired report', () => {report();report({ outputTokens: 1100, generationDurationMs: 12_000 });- act(() => vi.advanceTimersByTime(999));+ act(() => vi.advanceTimersByTime(59_999));expect(host.textContent).toBe('50');act(() => vi.advanceTimersByTime(1));expect(host.textContent).toBe('waiting');diff --git a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsxindex 4acecd2a05..23841f4542 100644--- a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx+++ b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx@@ -15,9 +15,6 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";import {clearRateHistoryCache,loadCachedRateHistory,- responseSpeedActivity,- responseSpeedHistory,- type ResponseSpeedSnapshot,} from "@cindy/maker-shared/usage-format";import { useRunningTokenRateHistory } from "../session/useRunningTokenRateHistory";import { RunningTokenRatePopover } from "@/session/RunningTokenRatePopover";@@ -128,8 +125,6 @@ vi.mock("react-i18next", () => ({t: (key: string, args?: any) =>key.endsWith("tokenRate")? `${args.rate} tok/s`- : key.endsWith("estimatedValue")- ? `≈${args.value}`: key.endsWith("tokenCount")? `${args.tokens} tok`: key,@@ -200,8 +195,6 @@ const bindings = {iconStroke: {},RunningTokenRatePopover,useRunningTokenRateHistory,- responseSpeedActivity,- responseSpeedHistory,formatComposerActivityElapsed: () => "1s",formatComposerActivityTokenCount: () => "100",};@@ -210,76 +203,6 @@ const ActivityStatus = new Function(`${compiledStatus}; return ComposerActivityStatus;`,)(...Object.values(bindings));-it.each([- { outputTokens: 80, estimated: false, count: '80 tok' },- { outputTokens: 80, estimated: true, count: '≈80 tok' },- { outputTokens: 0, estimated: false, count: '0 tok' },-])('keeps the speed card on measured output instead of whole-turn usage ($count)', async ({ outputTokens, estimated, count }) => {- const responseSpeed: ResponseSpeedSnapshot = {- phase: 'complete', waitOrigin: 'turn', firstResponseMs: 100,- waitingMs: 0, durationMs: 2000, outputTokens, estimated,- recentRate: null, averageRate: outputTokens / 2,- samples: [{ durationMs: 2000, outputTokens, rate: outputTokens / 2 }],- sampledAt: Date.now(),- };- await act(async () => root.render(createElement(ActivityStatus, {- ...base, visible: false, tokenUsage: 800, outputTokens: 800,- generationDurationMs: 2000, sideTaskRunning: false,- reconnectAttempt: null, responseSpeed,- })));- await gesture('onPressIn');- await gesture('onPress');- expect(card()!.textContent).toContain(`session.screen.outputTotal${count}`);- expect(card()!.textContent).toContain(`session.screen.averageRate${estimated ? '≈' : ''}${outputTokens / 2} tok/s`);- expect(card()!.textContent).not.toContain('800 tok');- expect(card()!.textContent).not.toContain('400 tok/s');-});--it('uses whole-turn output in the legacy card when the host omits the speed snapshot', async () => {- await act(async () => root.render(createElement(ActivityStatus, {- ...base, visible: true, tokenUsage: 800, outputTokens: 800,- generationDurationMs: 2000, sideTaskRunning: false, reconnectAttempt: null,- })));- await gesture('onPressIn');- await gesture('onPress');- expect(card()!.textContent).toContain('session.screen.outputTotal800 tok');- expect(card()!.textContent).toContain('session.screen.averageRate400 tok/s');-});--it('shows waiting, execution, silent output and retained completion consistently in the status and card', async () => {- vi.useFakeTimers();- try {- const speed: ResponseSpeedSnapshot = { phase: 'waiting', waitOrigin: 'turn', firstResponseMs: null,- waitingMs: 1000, durationMs: 0, outputTokens: 0, estimated: false, recentRate: null,- averageRate: null, samples: [], sampledAt: Date.now() };- const show = async (responseSpeed: ResponseSpeedSnapshot, visible = true) => act(async () =>- root.render(createElement(ActivityStatus, { ...base, visible, tokenUsage: 0,- sideTaskRunning: false, reconnectAttempt: null, responseSpeed })),- );- await show(speed);- expect(host.textContent).toContain('session.screen.responsePending');- await gesture('onPressIn'); await gesture('onPress');- expect(card()!.textContent).toContain('session.screen.responsePending');- const generating = { ...speed, phase: 'generating' as const, firstResponseMs: 1000,- hasRecentOutput: true, durationMs: 2000, outputTokens: 80, estimated: true, recentRate: 40,- averageRate: 40, samples: [{ durationMs: 2000, outputTokens: 80, rate: 40 }] };- await show(generating);- expect(host.textContent).toContain('session.screen.responseGenerating');- await act(async () => vi.advanceTimersByTime(1000));- expect(host.textContent).toContain('session.screen.responsePending');- expect(card()!.textContent).not.toContain('40 tok/s—');- await show({ ...generating, phase: 'paused', toolActive: true, recentRate: null });- expect(host.textContent).toContain('session.screen.toolRunning');- expect(card()!.textContent).toContain('session.screen.toolRunning');- await show({ ...generating, phase: 'complete', estimated: false, recentRate: 40 }, false);- await act(async () => vi.advanceTimersByTime(60000));- expect(host.textContent).toContain('session.screen.lastGeneration');- expect(card()!.textContent).toContain('session.screen.finalAverage');- await show({ ...speed, sampledAt: Date.now() });- expect(host.textContent).not.toContain('session.screen.lastGeneration');- } finally { vi.useRealTimers(); }-});-it.each(["onPress", "onLongPress"])("records the first completed interval before enabling %s, without sampling inactive gaps",async (open) => {@@ -312,10 +235,6 @@ it.each(["onPress", "onLongPress"])(expect(loadCachedRateHistory(base.sessionKey)?.samples.map((s) => s.rate),).toEqual([100]);- await renderStatus({ startedAt: null, outputTokens: 100, generationDurationMs: 1000, generationActive: false });- expect(card()!.textContent).toContain('session.screen.currentRate—');- await renderStatus({ startedAt: null, outputTokens: 100, generationDurationMs: 1000, generationActive: true });- expect(card()!.textContent).toContain('session.screen.currentRate—');for (const inactive of [{ sideTaskRunning: true },{ reconnectAttempt: { attempt: 1, maxAttempts: 3 } },@@ -610,7 +529,7 @@ it("uses paired generation samples, expires recent speed, and isolates a differeexpect(card()!.textContent).toContain("50");expect(card()!.textContent).toContain("75 tok/s");expect(card()!.textContent).toContain("100 tok/s");- await act(async () => vi.advanceTimersByTime(1_000));+ await act(async () => vi.advanceTimersByTime(60_000));expect(card()!.textContent).toContain("—");await render({ key: "other", sessionKey: "account/device/other" });expect(card()).toBeNull();@@ -670,36 +589,13 @@ it("moves screen reader focus into the pinned card and back to the trigger, exceexpect(harness.focus).toEqual(["text:session.screen.currentRate"]);});-it.each(['failed', 'cancelled', 'retrying'] as const)('shows %s consistently in the mobile retained entry and card', async (activity) => {- const terminal = activity !== 'retrying';- const key = activity === 'failed' ? 'responseFailed' : activity === 'cancelled' ? 'responseCancelled' : 'responseRetrying';- const speed: ResponseSpeedSnapshot = { phase: terminal ? 'complete' : 'paused', waitOrigin: 'turn',- firstResponseMs: 1000, waitingMs: 0, durationMs: 2000, outputTokens: 80, estimated: true,- recentRate: null, averageRate: 40, samples: [{ durationMs: 2000, outputTokens: 80, rate: 40 }], sampledAt: Date.now(),- ...(terminal ? { outcome: activity as 'failed' | 'cancelled' } : { retrying: true }),- };- await act(async () => root.render(createElement(ActivityStatus, { ...base, visible: !terminal,- tokenUsage: 500, sideTaskRunning: false, reconnectAttempt: null, responseSpeed: speed })));- expect(host.textContent).toContain(`session.screen.${key}`);- expect(host.textContent).not.toContain('session.screen.lastGeneration');- await gesture('onPressIn'); await gesture('onPress');- expect(card()!.textContent).toContain(`session.screen.${key}`);- expect(card()!.textContent).not.toContain('session.screen.finalAverage');- expect(card()!.textContent).toContain('40');-});-it.each([{ label: 'switching computers' },{ label: 'reconnecting', attempt: 2, maxAttempts: 5 },-])('keeps $label above a retained failure and slow-send status without token metadata', async (pendingRecovery) => {- const responseSpeed: ResponseSpeedSnapshot = {- phase: 'complete', outcome: 'failed', waitOrigin: 'turn', firstResponseMs: 1000,- waitingMs: 0, durationMs: 2000, outputTokens: 80, estimated: true,- recentRate: null, averageRate: 40, samples: [], sampledAt: Date.now(),- };+])('shows only $label, without timer or token metadata, while recovery is pending', async (pendingRecovery) => {await act(async () => root.render(createElement(ActivityStatus, {- ...base, visible: false, tokenUsage: 500, sideTaskRunning: false, reconnectAttempt: null,- responseSpeed, slowSendPhase: 'sending', pendingRecovery,+ ...base, visible: true, tokenUsage: 500, sideTaskRunning: false, reconnectAttempt: null,+ slowSendPhase: 'sending', pendingRecovery,})));const progress = pendingRecovery.attempt ? `${pendingRecovery.attempt}/${pendingRecovery.maxAttempts}` : '';expect(host.textContent).toBe(pendingRecovery.label + progress);diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.tsindex 1d8571f929..4ff106fa49 100644--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts@@ -212,7 +212,7 @@ describe('mobile session composer desktop-first surface', () => {expect(source).not.toContain('testID="session.attachmentPathPanel"');expect(source).not.toContain('被控电脑上的文件路径');expect(source).toContain('testID="session.composerActivityStatus"');- expect(source).toContain("'session.screen.thinking'");+ expect(source).toContain("t('session.screen.thinking')");// 活动状态行的三种说法都要在这里出现。过载退避与传输层重连共用同一个 attempt// 字段, 但文案分开: 说「正在重新连接」会把用户引向排查自己的网络// (review #844 codex P1)。字符串按 i18n key 断言, 不断言三元表达式的写法。diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex f642add6f8..27b0b51bf7 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -190,7 +190,7 @@"outputTotal": "Output","observedPeak": "Peak","tokenRateUnit": "tok/s",- "tokenRateDescription": "Streaming rates and peaks are estimates. Response totals are calibrated with reported usage. Tool execution and request waits are excluded.",+ "tokenRateDescription": "Latest generation interval. Excludes tools and waits.","networkReconnecting": "Reconnecting…","modelBusyRetrying": "Model service busy — retrying…","rateLimitRetrying": "Request rate limited — retrying…",@@ -271,24 +271,7 @@"forkConfirmTitle": "Start a new session from here?","forkConfirmDescription": "A separate session will be created using the context at this point. The original session stays unchanged, and future messages in either session won't affect the other.","forkConfirm": "Start new session",- "forkCancel": "Cancel",- "estimatedValue": "≈{{value}}",- "estimatedTokenRate": "≈{{rate}} tok/s",- "responseWaiting": "Waiting {{seconds}}s",- "waitSeconds": "{{seconds}}s",- "firstResponse": "First response",- "streamWait": "Stream wait",- "turnWaitDescription": "From the local provider turn start to the first observed text, thinking or tool content. This is not network latency.",- "streamWaitDescription": "From SDK stream start to the first content block. The earlier request wait is not observable.",- "lastGeneration": "Last generation",- "finalAverage": "Final average",- "generationPaused": "Generation paused",- "responsePending": "Waiting for response",- "responseFailed": "Request failed",- "responseCancelled": "Stopped",- "responseRetrying": "Retrying",- "responseGenerating": "Generating",- "toolRunning": "Running tool"+ "forkCancel": "Cancel"},"shareImage": {"title": "Share Conversation",diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex 411c6ff548..db86589e79 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -190,7 +190,7 @@"outputTotal": "累計出力","observedPeak": "ピーク","tokenRateUnit": "tok/s",- "tokenRateDescription": "リアルタイム速度とピークは推定値です。応答後に実使用量で補正し、ツール実行とリクエスト待機は除外します。",+ "tokenRateDescription": "直近の生成区間の速度。ツール実行と待機は除きます。","networkReconnecting": "再接続中…","modelBusyRetrying": "モデルサービスが混雑、再試行中…","rateLimitRetrying": "リクエストがレート制限されました。再試行中…",@@ -271,24 +271,7 @@"forkConfirmTitle": "ここから新しいセッションを始めますか?","forkConfirmDescription": "この時点の会話コンテキストを使って、独立した新しいセッションを作成します。元のセッションは変更されず、以後のメッセージは互いに影響しません。","forkConfirm": "新しいセッションを始める",- "forkCancel": "キャンセル",- "estimatedValue": "約{{value}}",- "estimatedTokenRate": "約{{rate}} tok/s",- "responseWaiting": "待機 {{seconds}}秒",- "waitSeconds": "{{seconds}}秒",- "firstResponse": "初回応答",- "streamWait": "ストリーム内待機",- "turnWaitDescription": "ローカルでの実行開始から最初のテキスト、思考、ツール内容まで。ネットワーク遅延とは異なります。",- "streamWaitDescription": "SDK ストリーム開始から最初のコンテンツまで。それ以前のリクエスト待機は測定できません。",- "lastGeneration": "前回の生成",- "finalAverage": "最終平均",- "generationPaused": "生成を一時停止",- "responsePending": "応答待ち",- "responseFailed": "リクエスト失敗",- "responseCancelled": "停止済み",- "responseRetrying": "再試行中",- "responseGenerating": "生成中",- "toolRunning": "ツール実行中"+ "forkCancel": "キャンセル"},"shareImage": {"title": "会話を共有",diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex 7534ca8548..11b65d97d2 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -186,7 +186,7 @@"outputTotal": "누적 출력","observedPeak": "최고","tokenRateUnit": "tok/s",- "tokenRateDescription": "실시간 속도와 최고 속도는 추정값입니다. 응답 후 실제 사용량으로 보정하며 도구 실행과 요청 대기는 제외합니다.",+ "tokenRateDescription": "최근 생성 구간의 속도. 도구 실행과 대기는 제외합니다.","networkReconnecting": "다시 연결하는 중…","modelBusyRetrying": "모델 서비스 혼잡, 다시 시도 중…","rateLimitRetrying": "요청이 속도 제한에 걸렸습니다. 다시 시도 중…",@@ -267,24 +267,7 @@"forkConfirmTitle": "여기서 새 세션을 시작할까요?","forkConfirmDescription": "이 지점의 대화 맥락을 사용해 독립된 새 세션을 만듭니다. 원래 세션은 변경되지 않으며, 이후 두 세션의 메시지는 서로에게 영향을 주지 않습니다.","forkConfirm": "새 세션 시작",- "forkCancel": "취소",- "estimatedValue": "약 {{value}}",- "estimatedTokenRate": "약 {{rate}} tok/s",- "responseWaiting": "대기 {{seconds}}초",- "waitSeconds": "{{seconds}}초",- "firstResponse": "첫 응답",- "streamWait": "스트림 내 대기",- "turnWaitDescription": "로컬 제공자 턴 시작부터 첫 텍스트, 사고 또는 도구 내용까지의 시간입니다. 네트워크 지연과는 다릅니다.",- "streamWaitDescription": "SDK 스트림 시작부터 첫 콘텐츠까지의 시간입니다. 그 이전의 요청 대기는 측정할 수 없습니다.",- "lastGeneration": "지난 생성",- "finalAverage": "최종 평균",- "generationPaused": "생성 일시 중지",- "responsePending": "응답 대기 중",- "responseFailed": "요청 실패",- "responseCancelled": "중지됨",- "responseRetrying": "다시 시도 중",- "responseGenerating": "생성 중",- "toolRunning": "도구 실행 중"+ "forkCancel": "취소"},"shareImage": {"title": "대화 공유",diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 1a1a32fbab..99c4141196 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -186,7 +186,7 @@"outputTotal": "累计输出","observedPeak": "峰值","tokenRateUnit": "tok/s",- "tokenRateDescription": "实时速度和峰值为估算。响应结束后用真实用量校准;不计工具执行和请求等待。",+ "tokenRateDescription": "最近一段生成速度,不含工具执行与等待。","networkReconnecting": "正在重新连接…","modelBusyRetrying": "模型服务繁忙,正在重试…","rateLimitRetrying": "请求受到限流,正在重试…",@@ -267,24 +267,7 @@"forkConfirmTitle": "从这里开启一个新任务?","forkConfirmDescription": "系统会根据这里的对话上下文创建一个独立的新任务。原任务不会改变,之后两边的消息互不影响。","forkConfirm": "开启新任务",- "forkCancel": "取消",- "estimatedValue": "约{{value}}",- "estimatedTokenRate": "约{{rate}} tok/s",- "responseWaiting": "等待 {{seconds}}秒",- "waitSeconds": "{{seconds}}秒",- "firstResponse": "首响应",- "streamWait": "流内等待",- "turnWaitDescription": "从本地收到引擎开始到首个文字、思考或工具内容,不等同于网络延迟。",- "streamWaitDescription": "从 SDK 流开始到首个内容块,之前的请求等待不可测。",- "lastGeneration": "上次生成",- "finalAverage": "最终平均",- "generationPaused": "生成暂停",- "responsePending": "等待响应",- "responseFailed": "请求失败",- "responseCancelled": "已停止",- "responseRetrying": "正在重试",- "responseGenerating": "正在生成",- "toolRunning": "执行工具中"+ "forkCancel": "取消"},"shareImage": {"title": "分享对话",diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.jsonindex 2fc6cbe2af..d7d8e8d99f 100644--- a/apps/mobile/src/i18n/locales/zh-TW/session.json+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json@@ -190,7 +190,7 @@"outputTotal": "累計輸出","observedPeak": "峰值","tokenRateUnit": "tok/s",- "tokenRateDescription": "即時速度和峰值為估算。回應結束後以實際用量校準;不計工具執行和請求等待。",+ "tokenRateDescription": "最近一段生成速度,不含工具執行與等待。","networkReconnecting": "正在重新連線…","modelBusyRetrying": "模型服務繁忙,正在重試…","rateLimitRetrying": "請求受到限流,正在重試…",@@ -271,24 +271,7 @@"forkConfirmTitle": "從這裡開啟一個新任務?","forkConfirmDescription": "系統會根據這裡的對話上下文建立一個獨立的新任務。原任務不會改變,之後兩邊的訊息互不影響。","forkConfirm": "開啟新任務",- "forkCancel": "取消",- "estimatedValue": "約{{value}}",- "estimatedTokenRate": "約{{rate}} tok/s",- "responseWaiting": "等待 {{seconds}}秒",- "waitSeconds": "{{seconds}}秒",- "firstResponse": "首回應",- "streamWait": "流內等待",- "turnWaitDescription": "從本機收到引擎開始到首個文字、思考或工具內容,不等同於網路延遲。",- "streamWaitDescription": "從 SDK 串流開始到首個內容區塊,之前的請求等待無法測量。",- "lastGeneration": "上次生成",- "finalAverage": "最終平均",- "generationPaused": "生成暫停",- "responsePending": "等待回應",- "responseFailed": "請求失敗",- "responseCancelled": "已停止",- "responseRetrying": "正在重試",- "responseGenerating": "正在生成",- "toolRunning": "執行工具中"+ "forkCancel": "取消"},"shareImage": {"title": "分享對話",diff --git a/apps/mobile/src/session/RunningTokenRatePopover.tsx b/apps/mobile/src/session/RunningTokenRatePopover.tsxindex 632967c0db..9b948c1cf2 100644--- a/apps/mobile/src/session/RunningTokenRatePopover.tsx+++ b/apps/mobile/src/session/RunningTokenRatePopover.tsx@@ -1,5 +1,3 @@-import type { ResponseSpeedSnapshot } from "@cindy/maker-shared/usage-format";-import { responseSpeedActivity, responseSpeedHistory } from "@cindy/maker-shared/usage-format";import { useEffect, useRef, useState, type ReactNode } from "react";import {AccessibilityInfo,@@ -48,7 +46,6 @@ export function formatTokenRate(rate: number | null): string {/** Key this component by account/device/session so gestures and counters never cross tasks. */export function RunningTokenRatePopover({- responseSpeed,sessionKey,startedAt,outputTokens,@@ -60,7 +57,6 @@ export function RunningTokenRatePopover({enabled = true,history: managedHistory,}: {- responseSpeed?: ResponseSpeedSnapshot;sessionKey: string;startedAt: number | null;outputTokens: number;@@ -201,7 +197,7 @@ export function RunningTokenRatePopover({: emptyRateHistory(null);});useEffect(() => {- if (managedHistory || responseSpeed) return;+ if (managedHistory) return;setInternalHistory((previous) =>recordRunningTokenRate(previous, {startedAt,@@ -212,7 +208,6 @@ export function RunningTokenRatePopover({);}, [managedHistory,- responseSpeed,startedAt,outputTokens,generationDurationMs,@@ -225,30 +220,29 @@ export function RunningTokenRatePopover({}, [managedHistory, sessionKey, internalHistory]);const [now, setNow] = useState(Date.now);useEffect(() => {- const sampledAt = responseSpeed?.sampledAt ?? history.latestSampleAt;- if (sampledAt === undefined || responseSpeed?.phase === 'complete') return;+ if (history.latestSampleAt === undefined) return;setNow(Date.now());const timer = setTimeout(() => setNow(Date.now()),- Math.max(0, sampledAt + RATE_SAMPLE_FRESH_MS - Date.now()),+ Math.max(0, history.latestSampleAt + RATE_SAMPLE_FRESH_MS - Date.now()),);return () => clearTimeout(timer);- }, [history.latestSampleAt, responseSpeed]);+ }, [history.latestSampleAt]);// Keep observing counters before the first rate is available. Only the// interaction surface is conditional; it must not own sampling lifetime.if (!enabled) return <View pointerEvents="none">{children}</View>;- const recent = responseSpeed ? responseSpeedHistory(responseSpeed, Math.max(now, Date.now())).latestRate :+ const recent =generationReliable &&(startedAt === null || startedAt === history.startedAt) &&history.latestSampleAt !== undefined &&Math.max(now, Date.now()) - history.latestSampleAt < RATE_SAMPLE_FRESH_MS? history.latestRate: null;- const average = responseSpeed ? responseSpeed.averageRate :+ const average =generationReliable && generationDurationMs > 0 && outputTokens > 0? (outputTokens * 1000) / generationDurationMs: null;- const samples = responseSpeed?.samples ?? history.samples;+ const samples = history.samples;const firstTime = samples[0]?.durationMs ?? 0;const span = (samples.at(-1)?.durationMs ?? 0) - firstTime;const ceiling = Math.max(1, ...samples.map((sample) => sample.rate));@@ -264,10 +258,6 @@ export function RunningTokenRatePopover({rate === null? "—": t("session.screen.tokenRate", { rate: formatTokenRate(rate) });- const approximate = (value: string | number, estimated = true) => estimated && value !== '—'- ? t('session.screen.estimatedValue', { value }) : value;- const displayedOutput = responseSpeed?.outputTokens ?? outputTokens;- const activity = responseSpeed ? responseSpeedActivity(responseSpeed, Math.max(now, Date.now())) : null;const card = (<ViewpointerEvents={mode === "held" ? "none" : "auto"}@@ -307,17 +297,10 @@ export function RunningTokenRatePopover({<View style={styles.top}><View style={styles.metric}><Text ref={cardFocusTarget} style={styles.label}>- {t(activity === 'failed' ? 'session.screen.responseFailed'- : activity === 'cancelled' ? 'session.screen.responseCancelled'- : activity === 'retrying' ? 'session.screen.responseRetrying'- : activity === 'complete' ? 'session.screen.finalAverage'- : activity === 'waiting' ? 'session.screen.responsePending'- : activity === 'tool' ? 'session.screen.toolRunning'- : activity === 'paused' ? 'session.screen.generationPaused'- : activity === 'quiet' ? 'session.screen.responsePending' : 'session.screen.currentRate')}+ {t("session.screen.currentRate")}</Text><Text style={styles.value}>- {recent === null ? '—' : approximate(formatTokenRate(recent), Boolean(responseSpeed) && (responseSpeed?.phase !== 'complete' || responseSpeed.estimated))}{" "}+ {formatTokenRate(recent)}{" "}<Text style={styles.label}>{t("session.screen.tokenRateUnit")}</Text>@@ -358,15 +341,17 @@ export function RunningTokenRatePopover({</View><View style={styles.top}>{[- ["averageRate", approximate(rateText(average), responseSpeed?.estimated ?? false)],+ ["averageRate", rateText(average)],["outputTotal",t("session.screen.tokenCount", {tokens:- approximate(displayedOutput >= 1000 ? `${(displayedOutput / 1000).toFixed(1)}k` : displayedOutput, responseSpeed?.estimated ?? false),+ outputTokens >= 1000+ ? `${(outputTokens / 1000).toFixed(1)}k`+ : outputTokens,}),],- ["observedPeak", approximate(rateText(samples.length ? Math.max(...samples.map(sample => sample.rate)) : null), Boolean(responseSpeed))],+ ["observedPeak", rateText(samples.length ? history.peak : null)],].map(([key, value]) => (<View style={styles.metric} key={key}><Text style={styles.label}>{t(`session.screen.${key}`)}</Text>@@ -374,12 +359,6 @@ export function RunningTokenRatePopover({</View>))}</View>- {responseSpeed && (- <View style={styles.top}>- <Text style={styles.label}>{t(`session.screen.${responseSpeed.waitOrigin === 'stream' ? 'streamWait' : 'firstResponse'}`)}</Text>- <Text style={styles.detail}>{responseSpeed.firstResponseMs === null ? '—' : t('session.screen.waitSeconds', { seconds: (responseSpeed.firstResponseMs / 1000).toFixed(1) })}</Text>- </View>- )}</ScrollView></View>);diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 9ecbc0609d..8b23ac79d6 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1,4 +1,3 @@-import { readResponseSpeedSnapshot, stopResponseSpeed, retryResponseSpeed, resumeResponseSpeed, mergeResponseSpeedStatus, type ResponseSpeedSnapshot } from '@cindy/maker-shared/usage-format';import { normalizeTaskTags, reconcileTaskTags } from '@cindy/maker-shared';import {createContext,@@ -149,7 +148,6 @@ export interface RemoteSessionRunStatus {status: string;tokenUsage: number;outputTokens: number;- responseSpeed?: ResponseSpeedSnapshot;generationDurationMs: number;generationActive: boolean;generationReliable: boolean;@@ -4746,15 +4744,6 @@ export const remoteSessionStore = {? clearSessionReconnectAttempt(sessionId): false;const fullMessageWriteAllowed = fromList || messageWriteAllowed(sessionId);- const outputData = isRecord(event.data) ? event.data : null;- if (((type === 'text' || type === 'thinking') && readString(outputData, 'text')) || type === 'tool_use') {- const current = readSessionRunStatus(sessionId);- const responseSpeed = resumeResponseSpeed(current.responseSpeed);- if (responseSpeed !== current.responseSpeed) {- writeSessionRunStatus(sessionId, { ...current, responseSpeed });- emit();- }- }if (type === 'text') {if (!fullMessageWriteAllowed) {if (reconnectCleared) emit();@@ -4837,20 +4826,11 @@ export const remoteSessionStore = {}}}- const terminalData = isRecord(event.data) ? event.data : null;- const rawTurn = isRecord(terminalData?.raw) ? terminalData.raw : null;- const current = readSessionRunStatus(sessionId);- const cancelled = (!current.isRunning && current.responseSpeed?.outcome === 'cancelled') ||- terminalData?.cancelled === true || terminalData?.status === 'cancelled' ||- terminalData?.reason === 'send_cancelled_before_acceptance' ||- terminalData?.reason === 'turn_continuation_cancelled' ||- terminalData?.reason === 'user_stop_unconfirmed_wake_tasks';- const failed = !cancelled && (isTerminalMakerErrorEvent(event) || rawTurn?.status === 'failed' || terminalData?.status === 'failed');- const terminalErrorChanged = writeSessionRunStatus(sessionId, {- ...current,- ...(cancelled ? { hasTerminalError: false } : failed ? { hasTerminalError: true } : {}),- responseSpeed: stopResponseSpeed(current.responseSpeed, cancelled ? 'cancelled' : failed ? 'failed' : undefined),- });+ const terminalErrorChanged = isTerminalMakerErrorEvent(event)+ && writeSessionRunStatus(sessionId, {+ ...readSessionRunStatus(sessionId),+ hasTerminalError: true,+ });this.setSessionRunning(sessionId,false,@@ -4877,7 +4857,6 @@ export const remoteSessionStore = {...current,isRunning: true,reconnectAttempt,- responseSpeed: data?.willRetry === true ? retryResponseSpeed(current.responseSpeed) : current.responseSpeed,startedAt: current.startedAt ?? Date.now(),});if (changed || textFlushed) emit();@@ -5055,8 +5034,6 @@ export const remoteSessionStore = {status: rawStatus ?? current.status,tokenUsage,outputTokens,- responseSpeed: mergeResponseSpeedStatus(current.responseSpeed,- readResponseSpeedSnapshot(data?.responseSpeed, Date.now()), isRunning, isTurnStart),generationDurationMs,generationActive,generationReliable,@@ -5638,7 +5615,6 @@ function clearLiveGenerationOnWideRunStart(return {...next,outputTokens: 0,- responseSpeed: undefined,generationDurationMs: 0,generationActive: false,generationReliable: true,@@ -5659,9 +5635,6 @@ function writeMakerTurnRunning(sessionId: string, running: boolean): boolean {function writeSessionRunStatus(sessionId: string, next: RemoteSessionRunStatus): boolean {const current = readSessionRunStatus(sessionId);- if (!next.isRunning && next.responseSpeed?.phase !== 'complete') {- next = { ...next, responseSpeed: stopResponseSpeed(next.responseSpeed), generationActive: false };- }if (next.isRunning && !current.isRunning && current.hasTerminalError) {next = { ...next, hasTerminalError: false };}diff --git a/apps/mobile/src/session/useRunningTokenRateHistory.ts b/apps/mobile/src/session/useRunningTokenRateHistory.tsindex 447cb9a434..2fbcca018b 100644--- a/apps/mobile/src/session/useRunningTokenRateHistory.ts+++ b/apps/mobile/src/session/useRunningTokenRateHistory.ts@@ -15,7 +15,6 @@ export function useRunningTokenRateHistory(input: {outputTokens: number;generationDurationMs: number;generationReliable: boolean;- generationActive?: boolean;/** 本地发送或队列已让活动条出现,但远端本轮 startedAt 可能仍是 null。 */streaming?: boolean;}) {@@ -25,7 +24,6 @@ export function useRunningTokenRateHistory(input: {outputTokens,generationDurationMs,generationReliable,- generationActive,streaming = false,} = input;// 挂载时从按会话的进程内缓存播种:ComposerActivityStatus 以账号、设备和任务身份为 key,@@ -68,9 +66,9 @@ export function useRunningTokenRateHistory(input: {) {return { ...recorded, baseline: null, lastReport: null, latestRate: null };}- return generationActive === false ? { ...recorded, latestRate: null, latestSampleAt: undefined } : recorded;+ return recorded;});- }, [sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, generationActive, streaming]);+ }, [sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, streaming]);useEffect(() => {if (sessionKey) saveCachedRateHistory(sessionKey, history);}, [sessionKey, history]);diff --git a/docs/dev-rules/assets/response-speed-completed-dark.png b/docs/dev-rules/assets/response-speed-completed-dark.pngdeleted file mode 100644index d0c3296727..0000000000Binary files a/docs/dev-rules/assets/response-speed-completed-dark.png and /dev/null differdiff --git a/docs/dev-rules/assets/response-speed-completed-light.png b/docs/dev-rules/assets/response-speed-completed-light.pngdeleted file mode 100644index 311432a012..0000000000Binary files a/docs/dev-rules/assets/response-speed-completed-light.png and /dev/null differdiff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 3d3e9f636c..b8a61bb4c3 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -11,20 +11,6 @@> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。-## 回复速度快照--既有 maker status 可选携带 `responseSpeed`(等待边界、估算计数、最近/平均速度与最多-60 个采样点);仅用于显示,不参与费用或上下文计数。新客户端校验该字段,旧主机省略时-沿用原 usage 路径,旧客户端忽略新增字段。无需服务端更新、新通道、权限或数据库 migration。-原生重试事件可为快照附加可选 `retrying`;两端亦从既有 error / done / Stop 事件-附加可选 `outcome` 与 `retrying` 注记,-只反映明确失败、取消或自动重试;不要求主机发送新事件,不落盘,不更改错误原因或操作契约。-终态真实 output 与生成 duration 的匹配沿现有消息用量记录处理。详见-[`response-speed.md`](response-speed.md)。-Claude 的既有 done payload 可选携带 `turnUsage`,来自 SDK result 用量的本轮增量,-供历史速度与消息用量配对。原 `usage` 保持会话累计口径;旧端忽略新字段,新端缺字段且无模型增量时-省略该速度,不将累计用量当本轮输出。费用与上下文仍走原计量路径。-## 任务列表提前同步聊天正文同账号控制端声明 `session-list-messages-v1` 后,`sessions` 订阅同时接收普通用户/助手diff --git a/docs/dev-rules/response-speed.md b/docs/dev-rules/response-speed.mddeleted file mode 100644index 96b5ae1bfb..0000000000--- a/docs/dev-rules/response-speed.md+++ /dev/null@@ -1,67 +0,0 @@-# 回复速度测量与展示--速度是展示投影,计费、缓存命中与上下文容量仍由引擎真实 usage 管理。流式速度不能回写-`UsageTracker`、账单或 token 余额。实现位于 `agents/shared/response-speed.ts`,两端复用-`maker-shared/usage-format` 的快照校验与图表模型。--## 计时边界--| 引擎 | 等待起点 | 首响应终点 | 校准来源 |-| --- | --- | --- | --- |-| Pi | 本地 `agent_start` | text / thinking / toolcall 的内容开始或首个 delta | 每条 assistant `message_end.usage.output` |-| Claude Code | SDK `message_start` | 主线 `content_block_start` 或 delta;子 Agent 独立 | 主线 `message_delta.usage.output_tokens` |-| Codex | 本地接受 `turn/started` | reasoning/tool item 开始或已去重文字 delta | 本轮真实 usage segments 的累计 output |--这些是本地可观测边界,包含思考和工具参数,不代表首个可见文字或网络 TTFT。-Claude 显示「流内等待」,SDK 暴露事件前的请求时间不可测。Pi/Codex 显示「首响应」。-排队发生在引擎开始前,不进入等待或生成速度。--生成计时从内容开始,到响应结束或工具/审批暂停;最后一个工具/审批结束后重新显示等待,下一次内容才恢复;并行内容已恢复时不被工具结束打断。-Codex 在 `agentMessage` 完成时关闭观测响应,迟到 usage/turn 完成只校准计数,不延长生成时间。-Codex 工具参数、patch 和 plan 只有成品 item,没有可配对的参数生成流;含这些输出的轮次-不能用整轮 usage 放大后续回答的采样。保留已观测内容的估算曲线与完成平均,真实账单总量-照常保存,但省略该轮历史 TPS。下一轮重新判断;纯流式回复仍可校准。-Pi 重试关闭失败片段,下一请求重新等待;每轮重新清空测量。零 usage 是有效零;缺少 usage-则保留估算。仅结束事件有 output、没有可观测流,或检测到挂起/时钟异常时不提供 TPS。--## 实时与终态--- 字符加权估计避免把一个传输片段当一个精确 token。它跨分片可加,但仍不是 tokenizer。-- 最近 1 秒滑窗,Pi/Claude 最多每 250ms 推进;Codex沿用 500ms 状态节流。- 窗口按固定 4ms 时间桶聚合,边缘最多提前裁掉不足 4ms 的估算量;旧桶不会因新输出续期。- 窗口最多 256 个聚合点,图表最多 60 个采样点,不保留文本。-- 实时速率、峰值及未校准输出标「约」。真实 usage 到达后校准该响应的曲线及输出;- 完成时显示真实输出除以已观测生成时间的最终平均。校准后的曲线和峰值仍是估计分配。-- 工具期间不冒充正在生成,当前速度为空;Pi 的 tool_execution、Codex 的配对 item 执行边界显示「执行工具中」,不能从参数流推出执行已开始。Claude 缺少同等执行事件时只标「生成暂停」;并行模型 delta 优先显示实际生成。下一请求重新显示等待响应。静默超过观测窗口与首响应前统一显示「等待响应」,内部仍区分请求等待与无新采样;静默不重启首响应计时,也不把没有可见内容当真实零输出或 API 失败。远端快照的时间戳在接收端- 归一为本地观测时间,避免用两台机器的绝对时钟差延长等待或抹掉当前速度。-- 停止/终态错误可能没有最后一份 usage,冻结最后观测并保留估算标识。明确终态错误标「请求失败」,用户取消标「已停止」,不冒充成功完成。曲线与已观测平均保留,当前速度为空。-- 仅原生 `api_retry` / `auto_retry_start` 或明确 `willRetry: true` 的自动重试事件标「正在重试」;沿用原错误原因、重连进度与重试操作。普通警告与无输出不触发此态。实际文字/思考/工具调用输出或新输出快照恢复后撤掉重试标记;失败/取消标记保留至下一轮,普通收尾 status 不抹成成功。-- 原速度入口在完成后保留「上次生成」,点击/键盘可重开详情;不依赖 hover 或先 pin,- 不固定几秒后隐藏。下一轮用本轮等待替换,切换任务不把别的任务的数据搬过来。--## 回看与持久化--最新快照留在任务的进程内状态,切换任务或组件重新挂载可以回看;图表不写数据库。-应用/Renderer 重载后首响应和曲线不恢复。已有消息用量记录继续保存真实 output 与经过-计数匹配检查的生成 duration,支持历史最终平均 TPS;缺失或计数不匹配时省略 TPS。-不增加数据库 schema、migration 或首响应持久字段。-Claude result 的原始 `usage` 是会话累计值;历史速度与消息详情使用同一份真实本轮-`turnUsage` 增量(或模型增量),不能把累计输出与本轮生成时间配对。它不来自流式估算。--## 兼容与验证--`UsageSnapshot.responseSpeed` 是既有 status 的可选增量字段:旧主机缺省,新界面使用原-usage 算法;旧客户端忽略新字段。无新 IPC channel、服务端协议版本或移动端原生指纹。--事件序列验证见 `response-speed.test.ts`、`response-speed-adapters.test.ts`;-两端组件/任务状态验证覆盖工具暂停、完成保留、下一轮、停止、任务切换与旧主机兼容。-真实设备与离线受控事件截图必须分别记录,不把离线结果声称为真实模型吞吐。--## 组件验收画面--真实状态栏和速度卡,使用离线受控事件(2 秒首响应、300 输出、4 秒生成),并非真实模型-吞吐测量。两图分别加载完整 Cindy Light / Dark 主题;完成超过旧淡出时间后仍可点击查看。----diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.tsindex 960aa71abd..c2d7a224db 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts@@ -525,12 +525,6 @@ describe('Claude Code translator is_error result guard', () => {ctx,);- const progressIterator = queue[Symbol.asyncIterator]();- const progress = await progressIterator.next();- expect(progress.value).toMatchObject({ type: 'status', data: {- isRunning: true, responseSpeed: { retrying: true, recentRate: null },- } });- await progressIterator.return?.();expect(queue.pending, 'retryable envelope must not close the turn').toBe(0);translateSdkMessage(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 3a5fbf5135..95b02b92a6 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,42 +2011,3 @@ describe('claude generation pause boundaries', () => {vi.useRealTimers();});});--describe('Claude normalized completed-turn output', () => {- afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });-- it('preserves raw SDK aggregates while exposing real turn output across success, zero and reset', () => {- vi.useFakeTimers();- const ctx = createTranslatorCtx();- const events: AgentEvent[] = [];- const queue = { push: (event: AgentEvent) => events.push(event) } as unknown as Parameters<typeof translateSdkMessage>[1];- const counts = [100, 60, 0, 30];- const aggregates = [100, 160, 160, 30];- for (const [index, output] of counts.entries()) {- const start = 1_000 + index * 10_000;- vi.setSystemTime(start);- resetClaudeGenerationTiming(ctx.rt.generation);- ctx.tracker.beginTurn();- ctx.turn = createTurnState();- translateSdkMessage({ type: 'stream_event', event: { type: 'message_start',- message: { id: `m-${index}`, model: 'claude-sonnet-4.5', usage: { input_tokens: 0 } } } }, queue, ctx);- vi.setSystemTime(start + 1_000);- translateSdkMessage({ type: 'stream_event', event: { type: 'content_block_start',- content_block: { type: 'text', text: '' } } }, queue, ctx);- translateSdkMessage({ type: 'stream_event', event: { type: 'content_block_delta',- delta: { type: 'text_delta', text: 'answer' } } }, queue, ctx);- vi.setSystemTime(start + 3_000);- translateSdkMessage({ type: 'stream_event', event: { type: 'message_delta',- usage: { output_tokens: output } } }, queue, ctx);- vi.setSystemTime(start + 5_000);- translateSdkMessage({ type: 'result', subtype: 'success', result: 'answer', total_cost_usd: 0,- usage: { input_tokens: 0, output_tokens: aggregates[index] } }, queue, ctx);- const done = events.filter(event => event.type === 'done').at(-1);- expect(done?.data).toMatchObject({ usage: { output_tokens: aggregates[index] }, turnUsage: { output_tokens: output },- responseSpeed: { phase: 'complete', outputTokens: output, durationMs: 2_000,- averageRate: output / 2, estimated: false } });- expect(done?.data).not.toHaveProperty('modelUsage');- expect(ctx.rt.lastResultUsageAggregate?.outputTokens).toBe(aggregates[index]);- }- });-});diff --git a/packages/maker-core/src/agents/claude-code/generation-timing.ts b/packages/maker-core/src/agents/claude-code/generation-timing.tsindex 8003013381..ec16960afb 100644--- a/packages/maker-core/src/agents/claude-code/generation-timing.ts+++ b/packages/maker-core/src/agents/claude-code/generation-timing.ts@@ -1,9 +1,7 @@-import { ResponseSpeedTracker } from '../shared/response-speed.js';const CLAUDE_GENERATION_HEARTBEAT_MS = 5_000;const CLAUDE_GENERATION_SUSPEND_GAP_MS = 30_000;export interface ClaudeGenerationState {- responseSpeed: ResponseSpeedTracker;startedAt: number | null;durationMs: number;/** Model time sampled with the latest parent output usage. */@@ -33,7 +31,6 @@ export interface ClaudeGenerationState {export function newClaudeGenerationState(): ClaudeGenerationState {return {- responseSpeed: new ResponseSpeedTracker('stream'),startedAt: null,durationMs: 0,outputDurationMs: 0,@@ -60,7 +57,6 @@ function sampleHeartbeat(state: ClaudeGenerationState, now = Date.now()): void {now - previous > CLAUDE_GENERATION_HEARTBEAT_MS + CLAUDE_GENERATION_SUSPEND_GAP_MS) {state.reliable = false;- state.responseSpeed.invalidate();}state.heartbeatAt = now;}@@ -88,7 +84,6 @@ function closeInterval(state: ClaudeGenerationState, endedAt: number): void {export function resetClaudeGenerationTiming(state: ClaudeGenerationState): void {stopHeartbeat(state);- state.responseSpeed.reset('stream');state.startedAt = null;state.pendingToolIds.clear();state.settledPauseIds.clear();@@ -119,7 +114,6 @@ export function beginClaudeGenerationAtRequestStart(): void {for (const pauseId of state.pendingToolIds) state.settledPauseIds.add(pauseId);state.pendingToolIds.clear();- state.responseSpeed.beginRequest(startedAt);beginClaudeGeneration(state, startedAt);}@@ -135,7 +129,6 @@ export function pauseClaudeGeneration(if (state.pendingToolIds.has(pauseId)) return;if (state.settledPauseIds.has(pauseId)) return;if (state.pendingToolIds.size === 0) {- state.responseSpeed.pause(pausedAt);// No open generation interval means we never saw message_start (or it was// already closed). Pausing here would resume the clock at tool_result and// still count earlier output tokens, so tok/s would be inflated.diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.tsindex a333386e39..9f55212e04 100644--- a/packages/maker-core/src/agents/claude-code/translator.ts+++ b/packages/maker-core/src/agents/claude-code/translator.ts@@ -39,6 +39,7 @@ 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 {+ beginClaudeGeneration,beginClaudeGenerationAtRequestStart,finalizeClaudeGeneration,markClaudeGenerationUnreliable,@@ -342,7 +343,6 @@ function ccLiveStatus(return {status,...attachLiveGeneration(ctx.tracker.snapshot(), {- responseSpeed: ctx.rt.generation.responseSpeed.snapshot(),outputTokens: mainTurnOutputTokens(ctx.tracker),durationMs: ctx.rt.generation.outputDurationMs,openStartedAt: ctx.rt.generation.startedAt,@@ -1068,8 +1068,6 @@ function handleSystem(return;}if (msg.subtype === 'api_retry') {- if (ctx.turn.interruptRequested || !ctx.rt.generation.responseSpeed.beginRetry()) return;- queue.push({ type: 'status', data: ccLiveStatus(ctx, 'Working...', true), source: 'claude-code' });// SDKAPIRetryMessage 明确表示本次 API 失败仍在自动重试,不是 turn 终态。// 除日志外也暂存最后一次 retry 的错误详情,覆盖 SDK 没有额外发送// assistant.error envelope、最终 ResultMessage 又没有 result 文本的路径。@@ -1691,18 +1689,6 @@ function handleStreamEvent(: undefined;// 冗余 add: 防 SDK 顺序契约变化 (stream_event 先于 assistant message yield), Set 幂等。- if (!parentToolUseId && event.type === 'content_block_start') ctx.rt.generation.responseSpeed.content();- if (!parentToolUseId && event.type === 'content_block_delta') {- const delta = event.delta;- const text = delta?.text ?? delta?.thinking ?? delta?.partial_json;- if (typeof text === 'string' && ctx.rt.generation.responseSpeed.delta(text)) {- queue.push({ type: 'status', data: ccLiveStatus(ctx, 'Generating...', true), source: 'claude-code' });- }- }- if (!parentToolUseId && event.type === 'message_delta') {- ctx.rt.generation.responseSpeed.reportOutput(event.usage?.output_tokens);- ctx.rt.generation.responseSpeed.pause();- }if (event.type === 'content_block_start') {const cb = event.content_block;if (cb && cb.type === 'text') {@@ -2210,7 +2196,6 @@ function handleResult(resultUsage != null && segmentTotals.outputTokens === resultUsage.outputTokens,);const liveGeneration = ctx.rt.generation;- liveGeneration.responseSpeed.finish();const endSnapshot = ctx.tracker.endTurn(resultUsage? {@@ -2492,7 +2477,6 @@ function handleResult(data: {status: 'Done',...attachLiveGeneration(endSnapshot, {- responseSpeed: liveGeneration.responseSpeed.snapshot(),outputTokens: liveTurnOutput,durationMs: liveGeneration.outputDurationMs,openStartedAt: null,@@ -2516,15 +2500,6 @@ function handleResult(: msg;const resultWithUsageSegments = {...safeResult,- responseSpeed: liveGeneration.responseSpeed.snapshot(),- // Keep SDK usage intact; the normalized provider delta can pair- // with the current turn's response-speed denominator.- turnUsage: resultUsage ? {- input_tokens: resultUsage.inputTokens,- output_tokens: resultUsage.outputTokens,- cache_read_input_tokens: resultUsage.cacheReadTokens,- cache_creation_input_tokens: resultUsage.cacheCreateTokens,- } : undefined,usageSegments: turnUsageSegments,usageSegmentsComplete,modelUsageCumulativeStartsAtZero: ctx.modelUsageCumulativeStartsAtZero?.() === true,diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 35abb5a8e9..69d4b61dde 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -18385,8 +18385,6 @@ describe('CodexAgent MCP thread context hooks', () => {}now = 5_000;- handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'turn-ordering',- item: { id: 'ordering-reasoning', type: 'reasoning', summary: [], content: [] } });handlers.turnCompleted({threadId: 'start-thread-id',turn: { id: 'turn-ordering', status: 'completed' },@@ -18396,8 +18394,7 @@ describe('CodexAgent MCP thread context hooks', () => {});const done = events.find((event) => event.type === 'done');expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs)- .toBeUndefined();- expect(events.findLast((event) => event.type === 'status')?.data.responseSpeed).toMatchObject({ outputTokens: 0, averageRate: null, firstResponseMs: expectedDurationMs });+ .toBe(expectedDurationMs);await handle.close();} finally {@@ -18406,146 +18403,6 @@ describe('CodexAgent MCP thread context hooks', () => {},);- it.each(['serial', 'parallel-tools', 'parallel-output'])('publishes paired tool phases and closes response time before delayed usage/turn completion (%s)', async (mode) => {- let now = 1_000;- const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);- const agent = new CodexAgent(createDeps());- const host = installFakeHost(agent);- const handle = await agent.startSession({ sessionId: 'session-speed-lifecycle', model: 'gpt-5.4', workingDir: '/repo' });- const handlers = host.getThreadHandlers()!;- const events: AgentEvent[] = [];- void (async () => { for await (const event of handle.events()) events.push(event); })();- const latestSpeed = () => events.findLast((event) => event.type === 'status')?.data.responseSpeed;- try {- handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'speed-turn' } });- now = 2_000;- handlers.agentMessageDelta!({ threadId: 'start-thread-id', turnId: 'speed-turn', itemId: 'answer-1', delta: 'abcd' });- now = 3_000;- handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'speed-turn',- item: { id: 'tool-1', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'inProgress' } } as never);- await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', toolActive: true, durationMs: 1_000 }));- // A duplicate start must not reopen generation during tool execution.- now = 3_100;- handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'speed-turn',- item: { id: 'tool-1', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'inProgress' } } as never);- await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', durationMs: 1_000 }));- if (mode === 'parallel-tools') {- now = 4_000;- handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'speed-turn',- item: { id: 'tool-2', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'inProgress' } } as never);- now = 8_000;- handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'speed-turn',- item: { id: 'tool-2', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'completed' } } as never);- await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', toolActive: true }));- }- if (mode === 'parallel-output') {- now = 8_000;- handlers.agentMessageDelta!({ threadId: 'start-thread-id', turnId: 'speed-turn', itemId: 'parallel-answer', delta: 'ijkl' });- }- now = 9_000;- handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'speed-turn',- item: { id: 'tool-1', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'completed', aggregatedOutput: '/repo' } } as never);- await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: mode === 'parallel-output' ? 'generating' : 'waiting', toolActive: false, waitingMs: 0 }));- now = 11_000;- handlers.agentMessageDelta!({ threadId: 'start-thread-id', turnId: 'speed-turn', itemId: 'answer-2', delta: 'efgh' });- now = 13_000;- handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'speed-turn',- item: { id: 'answer-2', type: 'agentMessage', text: 'efgh' } } as never);- const observedMs = mode === 'parallel-output' ? 6_000 : 3_000;- await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', durationMs: observedMs }));- now = 19_000;- handlers.tokenUsageUpdated!({ threadId: 'start-thread-id', turnId: 'speed-turn', tokenUsage: {- total: { inputTokens: 10, cachedInputTokens: 0, outputTokens: 60, reasoningOutputTokens: 0, totalTokens: 70 },- last: { inputTokens: 10, cachedInputTokens: 0, outputTokens: 60, reasoningOutputTokens: 0, totalTokens: 70 },- } } as never);- now = 25_000;- handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: 'speed-turn', status: 'completed', durationMs: 24_000 } });- await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));- // Tool arguments are not a measured stream: the whole-turn 60 output- // tokens must not inflate these two/three observed character estimates.- const observedTokens = mode === 'parallel-output' ? 3 : 2;- expect(latestSpeed()).toMatchObject({ phase: 'complete', outputTokens: observedTokens,- durationMs: observedMs, averageRate: observedTokens * 1_000 / observedMs, estimated: true });- const usage = events.find((event) => event.type === 'done')?.data.usage;- expect(usage).toMatchObject({ completionTokens: 60 });- expect(usage?.durationMs).toBeUndefined();- now = 26_000;- handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'next-speed-turn' } });- now = 26_100;- handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'next-speed-turn', item: { id: 'reason-2', type: 'reasoning', summary: [], content: [] } } as never);- await waitForExpectation(() => expect(latestSpeed()?.outputTokens).toBe(0));- } finally {- await handle.close();- nowSpy.mockRestore();- }- });-- it.each(['commandExecution', 'mcpToolCall', 'fileChange', 'plan'])(- 'keeps tool-first %s turns approximate and restores calibration on the next text-only turn',- async (type) => {- let now = 1_000;- const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);- const agent = new CodexAgent(createDeps());- const host = installFakeHost(agent);- const handle = await agent.startSession({ sessionId: `session-tool-first-${type}`, model: 'gpt-5.4', workingDir: '/repo' });- const handlers = host.getThreadHandlers()!;- const events: AgentEvent[] = [];- void (async () => { for await (const event of handle.events()) events.push(event); })();- const latestSpeed = () => events.findLast(event => event.type === 'status')?.data.responseSpeed;- try {- handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'tool-first' } });- const item = type === 'commandExecution'- ? { id: 'first-tool', type, command: 'pwd', cwd: '/repo', status: 'inProgress' }- : type === 'mcpToolCall'- ? { id: 'first-tool', type, server: 'test', tool: 'lookup', arguments: { query: 'where' }, status: 'inProgress' }- : type === 'fileChange'- ? { id: 'first-tool', type, changes: [{ path: '/repo/example', kind: { type: 'update' }, diff: '+answer' }], status: 'completed' }- : { id: 'first-tool', type, text: 'Look up the answer' };- const execution = type === 'commandExecution' || type === 'mcpToolCall';- now = 2_000;- if (execution) {- handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'tool-first', item } as never);- await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', toolActive: true, firstResponseMs: 1_000, durationMs: 0 }));- now = 8_000;- }- handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'tool-first', item: { ...item, status: 'completed' } } as never);- if (execution) await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'waiting', toolActive: false }));-- const finishAnswer = async (turnId: string, start: number, cumulativeOutput: number, lastOutput: number) => {- now = start;- handlers.agentMessageDelta!({ threadId: 'start-thread-id', turnId, itemId: `${turnId}-answer`, delta: 'a'.repeat(40) });- now = start + 1_000;- handlers.agentMessageDelta!({ threadId: 'start-thread-id', turnId, itemId: `${turnId}-answer`, delta: 'b'.repeat(40) });- await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'generating', recentRate: 10 }));- now = start + 2_000;- handlers.itemCompleted!({ threadId: 'start-thread-id', turnId, item: { id: `${turnId}-answer`, type: 'agentMessage', text: 'a'.repeat(40) + 'b'.repeat(40) } } as never);- now = start + 3_000;- handlers.tokenUsageUpdated!({ threadId: 'start-thread-id', turnId, tokenUsage: {- total: { inputTokens: 20, cachedInputTokens: 0, outputTokens: cumulativeOutput, reasoningOutputTokens: 0, totalTokens: cumulativeOutput + 20 },- last: { inputTokens: 10, cachedInputTokens: 0, outputTokens: lastOutput, reasoningOutputTokens: 0, totalTokens: lastOutput + 10 },- } } as never);- handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: turnId, status: 'completed' } });- await waitForExpectation(() => expect(latestSpeed()?.phase).toBe('complete'));- return events.findLast(event => event.type === 'done')?.data.usage;- };- const mixedUsage = await finishAnswer('tool-first', 10_000, 150, 150);- expect(latestSpeed()).toMatchObject({ estimated: true, outputTokens: 20, durationMs: 2_000, averageRate: 10 });- expect(latestSpeed()?.samples.every((sample: { rate: number }) => sample.rate <= 10)).toBe(true);- expect(mixedUsage).toMatchObject({ completionTokens: 150 });- expect(mixedUsage?.durationMs).toBeUndefined();-- now = 14_000;- handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'text-only' } });- const textUsage = await finishAnswer('text-only', 15_000, 190, 40);- expect(latestSpeed()).toMatchObject({ estimated: false, outputTokens: 40, durationMs: 2_000, averageRate: 20 });- expect(textUsage).toMatchObject({ completionTokens: 40, durationMs: 2_000 });- } finally {- await handle.close();- nowSpy.mockRestore();- }- },- );-it('starts response-first generation timing at turn/started and excludes an approval wait', async () => {let now = 1_000;const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);@@ -18619,10 +18476,7 @@ describe('CodexAgent MCP thread context hooks', () => {});await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));const done = events.find((event) => event.type === 'done');- // No root output/usage was observed: tool/interaction facts remain- // available, but cannot become a persisted token-rate denominator.- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();- expect(events.findLast((event) => event.type === 'status')?.data.responseSpeed).toMatchObject({ outputTokens: 0, averageRate: null, firstResponseMs: null });+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);await handle.close();} finally {@@ -18711,9 +18565,7 @@ describe('CodexAgent MCP thread context hooks', () => {expect(events.some((event) => event.type === 'done')).toBe(true),);const done = events.find((event) => event.type === 'done');- // A last-only usage notification without a cumulative ledger cursor and- // no content stream cannot provide a calibrated generation rate.- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(1_500);await handle.close();} finally {@@ -18789,10 +18641,7 @@ describe('CodexAgent MCP thread context hooks', () => {expect(handle.getUsageSnapshot().tokenUsage).toBe(540 - cachedInputTokens);handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: 'turn-1', status: 'completed' } });await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));- // Real output exists, but no streamed text was observed: keep accounting- // and the legacy paired sample, while omitting an unobservable final TPS.- expect(events.find((event) => event.type === 'done')?.data.usage.durationMs).toBeUndefined();- expect(events.filter((event) => event.type === 'status').at(-1)?.data.responseSpeed).toMatchObject({ outputTokens: 500, averageRate: null });+ expect(events.find((event) => event.type === 'done')?.data.usage.durationMs).toBe(5_000);expect(events.filter((event) => event.type === 'status').at(-1)?.data).toMatchObject({status: 'Done', outputTokens: 500, generationDurationMs: 5_000,});@@ -19161,10 +19010,7 @@ describe('CodexAgent MCP thread context hooks', () => {});await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));const done = events.find((event) => event.type === 'done');- // No root output/usage was observed: tool/interaction facts remain- // available, but cannot become a persisted token-rate denominator.- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();- expect(events.findLast((event) => event.type === 'status')?.data.responseSpeed).toMatchObject({ outputTokens: 0, averageRate: null, firstResponseMs: 1_000 });+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);await handle.close();} finally {@@ -19242,10 +19088,7 @@ describe('CodexAgent MCP thread context hooks', () => {});await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));const done = events.find((event) => event.type === 'done');- // No root output/usage was observed: tool/interaction facts remain- // available, but cannot become a persisted token-rate denominator.- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();- expect(events.findLast((event) => event.type === 'status')?.data.responseSpeed).toMatchObject({ outputTokens: 0, averageRate: null, firstResponseMs: null });+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);if (outcome === 'server-resolved') {decision.resolve({ kind: 'ask_user_question', answers: {} });diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 93b2a63e11..b3281c9911 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -131,7 +131,6 @@ import {} from '../shared/auto-review-decision.js';import type { ReviewableAction } from '../shared/auto-review.js';import { UsageTracker } from '../shared/usage-tracker.js';-import { calibratedResponseDuration } from '@cindy/maker-shared/usage-format';import { attachLiveGeneration, sampleGenerationDuration } from '../shared/live-generation-snapshot.js';import { getDefaultImageResizer } from '../shared/image-resizer.js';import { formatManagedImageReferences } from '../shared/managed-image-reference.js';@@ -172,8 +171,8 @@ import {classifyCodexError,translateErrorNotification,translateItemNotification,- observeCodexItemTiming,beginCodexGenerationTurn,+ codexGenerationDurationMs,finalizeCodexGenerationTurn,pauseCodexGeneration,resetCodexGenerationTiming,@@ -3709,7 +3708,6 @@ assertRouteCurrent();const usageTracker = new UsageTracker();const translatorRt: CodexRuntimeState = newCodexRuntimeState();const liveUsageSnapshot = () => attachLiveGeneration(usageTracker.snapshot(), {- responseSpeed: translatorRt.responseSpeed.snapshot(),outputTokens: usageTracker.getTurnUsage().output,durationMs: translatorRt.generationOutputDurationMs,openStartedAt: translatorRt.generationStartedAt,@@ -10825,7 +10823,6 @@ assertRouteCurrent();text?: unknown;} | null | undefined;if (!candidate || candidate.type !== 'plan') return false;- translatorRt.responseSpeedHasUnobservedOutput = true;if (typeof candidate.text === 'string') proposedPlanText = candidate.text;return true;}@@ -10997,16 +10994,7 @@ assertRouteCurrent();const realTurnUsage = usageTracker.getTurnUsage();const realTurnUsageSegments = usageTracker.getTurnUsageSegments();finalizeCodexGenerationTurn(translatorRt, turn.id);- const unmeasuredOutputOnly = translatorRt.responseSpeedHasUnobservedOutput- && translatorRt.responseSpeed.snapshot().outputTokens === 0;- // With no sampled units, retain the real total but expose no rate. Mixed- // turns retain only their observed estimates, never a whole-turn scale.- translatorRt.responseSpeed.finish(realTurnUsageSegments.length > 0- && (!translatorRt.responseSpeedHasUnobservedOutput || unmeasuredOutputOnly)- ? realTurnUsage.output : undefined);- if (!translatorRt.generationTimingReliable || unmeasuredOutputOnly) translatorRt.responseSpeed.invalidate();- const speedSnapshot = translatorRt.responseSpeed.snapshot();- const generationDurationMs = calibratedResponseDuration(speedSnapshot, realTurnUsage.output);+ const generationDurationMs = codexGenerationDurationMs(translatorRt);const codexDoneUsage = {promptTokens: realTurnUsage.input,completionTokens: realTurnUsage.output,@@ -11017,9 +11005,12 @@ assertRouteCurrent();cachedTokens: realTurnUsage.cacheRead,cacheCreationTokens: realTurnUsage.cacheCreate,segments: realTurnUsageSegments,- // Persist TPS timing only when observed stream time pairs with real turn output.+ // With usage, exclude post-output finalization. Without usage, retain+ // the measured duration metadata (zero output cannot produce a rate)....(generationDurationMs !== undefined ? {- durationMs: generationDurationMs,+ durationMs: realTurnUsage.output > 0+ ? translatorRt.generationOutputDurationMs || undefined+ : generationDurationMs,} : {}),...(typeof turn.durationMs === 'number' && Number.isFinite(turn.durationMs)? { turnDurationMs: turn.durationMs }@@ -11223,7 +11214,6 @@ assertRouteCurrent();data: {status: 'Done',...attachLiveGeneration(endSnap, {- responseSpeed: translatorRt.responseSpeed.snapshot(),outputTokens: realTurnUsage.output,durationMs: translatorRt.generationOutputDurationMs,openStartedAt: null,@@ -12418,12 +12408,10 @@ assertRouteCurrent();params.turnId,'started',);- observeCodexItemTiming(translatorRt, 'started', translatedParams);pushItemStatus(translatedItem);translateItemNotification('started', translatedParams, eventQueue, {rt: translatorRt,log,- timingObserved: true,onCompactBoundary: handleCompactBoundary,});// 重放帧后发:translator 刚推的 running 帧不得把已重放出的终态盖回去。@@ -12558,12 +12546,6 @@ assertRouteCurrent();log,onCompactBoundary: handleCompactBoundary,});- // Close the observed response after translating any final text that- // was absent from deltas. A later usage/turn terminal calibrates the- // counts without charging its delivery lag as model generation.- if (!isLateCollabTerminal && translatedItem.type === 'agentMessage') {- translatorRt.responseSpeed.pause();- }// A late V1 spawn completion is the spawn tool closing, not necessarily// the child closing. Reassert a running compact state, or an explicit// failed/stopped tracker state; a completed replay would only duplicate@@ -12599,7 +12581,6 @@ 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;@@ -12615,7 +12596,6 @@ assertRouteCurrent();producedOutputTurnIds.add(params.turnId);noteRecoveryModelWork(params.turnId);translateReasoningSummaryTextDelta(params, eventQueue, { rt: translatorRt, log });- maybePushUsageRefresh();},reasoningSummaryPartAdded: (params) => {// thinking 流同样算产出(与非缓冲路径一致)。@@ -12632,7 +12612,6 @@ 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.ts b/packages/maker-core/src/agents/codex/translator.tsindex 7a22a7cd0e..9f6739c6d8 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -1,4 +1,3 @@-import { ResponseSpeedTracker } from '../shared/response-speed.js';/*** Codex app-server v2 Notification → maker-core 语义 AgentEvent 翻译器。*@@ -81,9 +80,6 @@ export interface CodexRuntimeState {/** item.id → agentMessage 已 emit 文本字符长度(citation 归一化后的空间,见 handleAgentMessage)。 */itemTextLen: Map<string, number>;/** Current model-active interval start; null while tools/approvals own the turn. */- responseSpeed: ResponseSpeedTracker;- /** Tool inputs arrive after generation, so whole-turn usage cannot calibrate only observed text. */- responseSpeedHasUnobservedOutput: boolean;generationStartedAt: number | null;/** Tool/approval boundaries currently owning the turn. Generation resumes after all finish. */generationPendingToolIds: Set<string>;@@ -134,8 +130,6 @@ export function newCodexRuntimeState(): CodexRuntimeState {reasoningStartedAt: new Map(),reasoningTextLen: new Map(),itemTextLen: new Map(),- responseSpeed: new ResponseSpeedTracker(),- responseSpeedHasUnobservedOutput: false,generationStartedAt: null,generationPendingToolIds: new Set(),generationDurationMs: 0,@@ -172,7 +166,6 @@ function sampleCodexGenerationHeartbeat(rt: CodexRuntimeState, now = Date.now())now - previous > CODEX_GENERATION_HEARTBEAT_MS + CODEX_GENERATION_SUSPEND_GAP_MS) {rt.generationTimingReliable = false;- rt.responseSpeed.invalidate();}rt.generationHeartbeatAt = now;}@@ -196,7 +189,6 @@ export function resetCodexGenerationTiming(rt: CodexRuntimeState): void {rt.generationOutputDurationMs = 0;rt.generationTurnId = null;rt.generationTimingReliable = true;- rt.responseSpeedHasUnobservedOutput = false;}function closeCodexGenerationInterval(rt: CodexRuntimeState, endedAt: number): void {@@ -220,7 +212,6 @@ export function beginCodexGenerationTurn(if (rt.generationTurnId !== turnId) {resetCodexGenerationTiming(rt);rt.generationTurnId = turnId;- rt.responseSpeed.reset('turn', startedAt);}if (rt.generationStartedAt === null && rt.generationPendingToolIds.size === 0) {rt.generationStartedAt = startedAt;@@ -266,7 +257,6 @@ export function pauseCodexGeneration(return;}if (rt.generationPendingToolIds.has(pauseId)) return;- rt.responseSpeed.pause(pausedAt);if (rt.generationPendingToolIds.size === 0) closeCodexGenerationInterval(rt, pausedAt);rt.generationPendingToolIds.add(pauseId);}@@ -282,12 +272,6 @@ export function resumeCodexGeneration(return;}if (rt.generationPendingToolIds.size === 0) rt.generationStartedAt = resumedAt;- // Completion of the last tool/approval is a locally observed waiting- // boundary, not evidence that the next model response has started. Preserve- // a parallel response that already resumed on an actual output delta.- if (rt.generationPendingToolIds.size === 0 && rt.responseSpeed.snapshot(resumedAt).phase === 'paused') {- rt.responseSpeed.beginRequest(resumedAt);- }if (rt.generationPendingToolIds.size === 0) startCodexGenerationHeartbeat(rt);}@@ -340,12 +324,10 @@ function noteCodexGenerationBoundary(}const pauseId = `item:${item.id}`;if (phase === 'started') {- if (item.type !== 'contextCompaction') rt.responseSpeed.toolStarted(pauseId);pauseCodexGeneration(rt, turnId, pauseId, receivedAt);return;}if (phase !== 'completed') return;- rt.responseSpeed.toolEnded(pauseId);resumeCodexGeneration(rt, turnId, pauseId, receivedAt);}@@ -360,8 +342,6 @@ interface TranslatorLog {export interface CodexTranslateContext {rt: CodexRuntimeState;log: TranslatorLog;- /** Host observed the boundary before publishing its status frame. */- timingObserved?: boolean;/*** Maker Memory flush 观察器 — codex contextCompaction completed 时调,* controller 重置 fired 阈值 (compact 后 context 又有空间, 可重新触发)。@@ -393,30 +373,6 @@ export interface CodexTranslateContext {type ItemPhase = 'started' | 'updated' | 'completed';-/** Observe before status publication without changing the established event order. */-export function observeCodexItemTiming(- rt: CodexRuntimeState,- phase: ItemPhase,- notification: ItemStartedNotification['params'] | ItemUpdatedNotification['params'] | ItemCompletedNotification['params'],-): void {- const item = notification.item;- const itemType = item?.type;- if (!item || typeof item !== 'object') return;- if (phase === 'started' && CODEX_GENERATION_PAUSE_ITEM_TYPES.has(itemType)- && rt.generationPendingToolIds.has(`item:${item.id}`)) return;- if (phase === 'started' && (itemType === 'reasoning' || CODEX_GENERATION_PAUSE_ITEM_TYPES.has(itemType))) {- rt.responseSpeed.content();- }- noteCodexGenerationBoundary(rt, phase, item, notification);- // These inputs have no argument delta/start pair. Their output tokens may be- // included in turn usage, but their generation time is not in our samples.- // Retain measured streaming estimates without scaling them by that total.- if ((CODEX_GENERATION_PAUSE_ITEM_TYPES.has(itemType) && itemType !== 'contextCompaction')- || itemType === 'fileChange' || itemType === 'plan') {- rt.responseSpeedHasUnobservedOutput = true;- }-}-export function translateItemNotification(phase: ItemPhase,notification:@@ -436,7 +392,12 @@ export function translateItemNotification(ctx.log.warn('item missing type field', { phase, itemKeys: Object.keys(item) });return;}- if (!ctx.timingObserved) observeCodexItemTiming(ctx.rt, phase, notification);+ noteCodexGenerationBoundary(+ ctx.rt,+ phase,+ item as { id?: unknown; type?: unknown },+ notification as { turnId?: unknown },+ );switch (itemType) {case 'agentMessage':@@ -1145,7 +1106,6 @@ function emitAgentMessageProgress(ctx.rt.itemRawText.set(itemId, rawText);ctx.rt.itemTextLen.set(itemId, emitted.length);if (delta.length === 0) return;- ctx.rt.responseSpeed.delta(delta);queue.push({type: 'text',data: { text: delta, isFinal: false, agentMessageId: itemId,@@ -1361,7 +1321,6 @@ export function translateReasoningSummaryTextDelta(ctx: CodexTranslateContext,): void {if (!params.delta) return;- ctx.rt.responseSpeed.delta(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);@@ -1396,7 +1355,6 @@ export function translateReasoningTextDelta(ctx: CodexTranslateContext,): void {if (!params.delta) return;- ctx.rt.responseSpeed.delta(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 2babc441a6..b56625510c 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@@ -1427,8 +1427,7 @@ describe('pi translator', () => {cacheCreateTokens: 3,}),]);- // Completed-only frames cannot prove when streaming began.- expect(usage.durationMs).toBeUndefined();+ expect(usage.durationMs).toBeGreaterThanOrEqual(1_200);expect(usage.turnDurationMs).toBeGreaterThanOrEqual(0);// 快照累计 input+output。expect(usageSnapshotOf(ctx).tokenUsage).toBe(120);@@ -1578,7 +1577,7 @@ describe('pi translator', () => {disposePiTranslateContext(ctx);});- it('keeps native timestamp timing but omits TPS without a first-content observation', () => {+ it('reads Pi v0.83 generation duration from timestamp with a live heartbeat', () => {const ctx = createPiTranslateContext(noopLogger);const { queue, events } = makeQueue();const timestamp = Date.now() - 1_200;@@ -1599,8 +1598,8 @@ describe('pi translator', () => {);translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);const usage = (events.find((e) => e.type === 'done')!.data as { usage: Record<string, unknown> }).usage;- expect(usage.durationMs).toBeUndefined();- expect(usageSnapshotOf(ctx).generationDurationMs).toBeGreaterThanOrEqual(1_200);+ expect(usage.durationMs).toEqual(expect.any(Number));+ expect(usage.durationMs).toBeGreaterThanOrEqual(1_200);expect(usage.turnDurationMs).toEqual(expect.any(Number));});@@ -2240,90 +2239,3 @@ describe('pi translator', () => {});});});--describe('Pi tool-end response speed publication', () => {- function withTurn(run: (harness: {- send: (now: number, event: Record<string, unknown>) => void;- latestStatus: () => unknown;- events: AgentEvent[];- ctx: ReturnType<typeof createPiTranslateContext>;- }) => void) {- const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000);- const ctx = createPiTranslateContext(noopLogger);- const { queue, events } = makeQueue();- const send = (now: number, event: Record<string, unknown>) => {- clock.mockReturnValue(now);- translatePiEvent(ev(event), queue, ctx);- };- try {- send(1_000, { type: 'agent_start' });- send(2_000, { type: 'message_start', message: { role: 'assistant' } });- send(3_000, { type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: 'a'.repeat(40) } });- run({ send, events, ctx, latestStatus: () => events.filter(event => event.type === 'status').at(-1)?.data });- } finally {- disposePiTranslateContext(ctx);- clock.mockRestore();- }- }-- it('publishes remaining parallel tools and starts waiting immediately after the last result', () => {- withTurn(({ send, latestStatus, ctx }) => {- send(5_000, { type: 'message_end', message: { role: 'assistant', content: [], usage: { output: 80 } } });- send(6_000, { type: 'tool_execution_start', toolCallId: 'a', toolName: 'read', args: {} });- send(7_000, { type: 'tool_execution_start', toolCallId: 'b', toolName: 'bash', args: {} });- send(8_000, { type: 'tool_execution_end', toolCallId: 'a', result: 'done' });- expect(latestStatus()).toMatchObject({ isRunning: true,- responseSpeed: { phase: 'paused', toolActive: true, recentRate: null } });- send(9_000, { type: 'tool_execution_end', toolCallId: 'b', result: 'done' });- expect(latestStatus()).toMatchObject({ isRunning: true,- responseSpeed: { phase: 'waiting', toolActive: false, waitingMs: 0, recentRate: null,- durationMs: 2_000, firstResponseMs: 2_000, outputTokens: 80 } });- send(10_000, { type: 'message_start', message: { role: 'toolResult' } });- expect(usageSnapshotOf(ctx).responseSpeed).toMatchObject({ phase: 'waiting', waitingMs: 1_000, durationMs: 2_000 });- });- });-- it('preserves a request already waiting while a parallel tool finishes', () => {- withTurn(({ send, latestStatus }) => {- send(4_000, { type: 'message_end', message: { role: 'assistant', content: [] } });- send(5_000, { type: 'tool_execution_start', toolCallId: 'a', toolName: 'read', args: {} });- send(6_000, { type: 'message_start', message: { role: 'assistant' } });- send(9_000, { type: 'tool_execution_end', toolCallId: 'a', result: 'done' });- expect(latestStatus()).toMatchObject({ responseSpeed: {- phase: 'waiting', toolActive: false, waitingMs: 3_000, durationMs: 1_000 } });- });- });-- it('preserves parallel model output instead of reopening its generation clock', () => {- withTurn(({ send, latestStatus }) => {- send(3_100, { type: 'tool_execution_start', toolCallId: 'a', toolName: 'read', args: {} });- send(4_000, { type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: 'b'.repeat(40) } });- send(4_500, { type: 'tool_execution_end', toolCallId: 'a', result: 'done' });- expect(latestStatus()).toMatchObject({ responseSpeed: {- phase: 'generating', toolActive: false, durationMs: 1_500, recentRate: 10, outputTokens: 20 } });- });- });-- it('does not publish running status for orphan, duplicate or settled-turn results', () => {- withTurn(({ send, events, latestStatus }) => {- const countStatus = () => events.filter(event => event.type === 'status').length;- let count = countStatus();- send(4_000, { type: 'tool_execution_end', toolCallId: 'unknown', result: 'done' });- expect(countStatus()).toBe(count);- send(5_000, { type: 'message_end', message: { role: 'assistant', content: [] } });- send(6_000, { type: 'tool_execution_start', toolCallId: 'a', toolName: 'read', args: {} });- send(7_000, { type: 'tool_execution_end', toolCallId: 'a', result: 'done' });- count = countStatus();- send(8_000, { type: 'tool_execution_end', toolCallId: 'a', result: 'done' });- expect(countStatus()).toBe(count);- send(9_000, { type: 'tool_execution_start', toolCallId: 'b', toolName: 'read', args: {} });- send(10_000, { type: 'agent_settled' });- count = countStatus();- const terminal = latestStatus();- send(11_000, { type: 'tool_execution_end', toolCallId: 'b', result: 'done' });- expect(countStatus()).toBe(count);- expect(latestStatus()).toEqual(terminal);- expect(latestStatus()).toMatchObject({ isRunning: false, responseSpeed: { phase: 'complete' } });- });- });-});diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex 99a9af11f3..17064889fa 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -1,5 +1,3 @@-import { calibratedResponseDuration } from '@cindy/maker-shared/usage-format';-import { ResponseSpeedTracker } from '../shared/response-speed.js';/*** pi RPC 事件 → AgentEvent 翻译层。*@@ -162,7 +160,6 @@ export interface PiTranslateContext {terminalAssistantErrorEmitted: boolean;/** 整轮 wall-clock 起点;只用于诊断,不参与 TPS。 */turnWallClockStartedAt: number;- responseSpeed: ResponseSpeedTracker;generationDurationMs: number;/** Open generation interval start; 0 while tools/user waits own the turn. */generationOpenAt: number;@@ -227,7 +224,6 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {finalAssistantText: '',finalAssistantStopReason: null,turnWallClockStartedAt: 0,- responseSpeed: new ResponseSpeedTracker(),generationDurationMs: 0,generationOpenAt: 0,generationTimingReliable: true,@@ -344,7 +340,6 @@ function samplePiGenerationHeartbeat(ctx: PiTranslateContext, now = Date.now()):PI_GENERATION_HEARTBEAT_MS + PI_GENERATION_SUSPEND_GAP_MS) {ctx.generationHeartbeatReliable = false;- ctx.responseSpeed.invalidate();}ctx.generationHeartbeatAt = now;}@@ -369,7 +364,6 @@ export function usageSnapshotOf(ctx: PiTranslateContext): UsageSnapshot {costUsd: ctx.costUsd,},{- responseSpeed: ctx.responseSpeed.snapshot(),outputTokens: ctx.turnOutput,// Pi reports output only at message_end, alongside the closed duration.durationMs: ctx.generationDurationMs,@@ -690,7 +684,6 @@ export function translatePiEvent(ctx.pendingAssistantError = null;ctx.terminalAssistantErrorEmitted = false;ctx.turnWallClockStartedAt = Date.now();- ctx.responseSpeed.reset('turn');ctx.generationDurationMs = 0;ctx.generationTimingReliable = true;stopPiGenerationHeartbeat(ctx);@@ -710,9 +703,6 @@ export function translatePiEvent(return;case 'message_start': {- const role = (event.message as { role?: string } | undefined)?.role;- if (role && role !== 'assistant') return;- ctx.responseSpeed.beginRequest();ctx.thinkingBlocks.clear();ctx.streamStopTokenByIndex.clear();const message = event.message as { usage?: PiUsage } | undefined;@@ -727,10 +717,6 @@ export function translatePiEvent(case 'message_update': {const delta = event.assistantMessageEvent as Record<string, unknown> | undefined;if (!delta || typeof delta.type !== 'string') return;- if (['text_start', 'thinking_start', 'toolcall_start'].includes(delta.type)) ctx.responseSpeed.content();- if (['text_delta', 'thinking_delta', 'toolcall_delta'].includes(delta.type) && typeof delta.delta === 'string') {- if (ctx.responseSpeed.delta(delta.delta)) pushStatus(queue, ctx, 'Generating...', true);- }handleAssistantDelta(delta, queue, ctx);return;}@@ -738,7 +724,6 @@ export function translatePiEvent(case 'message_end': {const message = event.message as PiAssistantMessage | undefined;if (!message || message.role !== 'assistant') return;- ctx.responseSpeed.endResponse(message.usage?.output);const pendingPriceVariant = ctx.pendingPriceVariants.shift();const reportedPriceVariant = priceVariantFromServiceTier(message.usage?.service_tier);const executionPriceVariant = message.usage && ctx.resolveUsagePriceVariant?.({@@ -811,7 +796,6 @@ export function translatePiEvent(case 'tool_execution_start': {const toolUseId = String(event.toolCallId ?? '');- ctx.responseSpeed.toolStarted(toolUseId);const toolName = String(event.toolName ?? 'tool');const toolArgs = (event.args as Record<string, unknown>) ?? {};if (toolUseId) ctx.toolNamesByCallId.set(toolUseId, toolName);@@ -905,7 +889,6 @@ export function translatePiEvent(case 'tool_execution_end': {const toolUseId = String(event.toolCallId ?? '');- const endedTrackedTool = ctx.responseSpeed.toolEnded(toolUseId);const isError = event.isError === true;const rawText = toolResultFullText(event.result);const toolName = String(@@ -955,13 +938,6 @@ export function translatePiEvent(source: 'pi',});}- if (endedTrackedTool && ctx.isStreaming) {- const speed = ctx.responseSpeed.snapshot();- // The last tool result is an observable wait boundary, even before- // Pi emits the next message_start. Keep parallel output/request clocks.- if (!speed.toolActive && speed.phase === 'paused') ctx.responseSpeed.beginRequest();- pushStatus(queue, ctx, 'Working…', true);- }return;}@@ -980,7 +956,6 @@ export function translatePiEvent(ctx.turnSettled = true;ctx.isStreaming = false;ctx.pendingPriceVariants = [];- ctx.responseSpeed.finish();stopPiGenerationHeartbeat(ctx);const hostAbortRequested = isCurrentTurnHostAbortRequested(ctx);const pendingAssistantError = hostAbortRequested ? null : ctx.pendingAssistantError;@@ -989,7 +964,6 @@ export function translatePiEvent(const outputLimited = !hostAbortRequested&& !ctx.terminalAssistantErrorEmitted&& ctx.finalAssistantStopReason === 'length';- const speedDuration = calibratedResponseDuration(ctx.responseSpeed.snapshot(), ctx.turnOutput);const usage = {inputTokens: ctx.turnInput,outputTokens: ctx.turnOutput,@@ -997,10 +971,11 @@ export function translatePiEvent(cacheCreationTokens: ctx.turnCacheWrite,segments: ctx.turnUsageSegments.map((segment) => ({ ...segment })),segmentsComplete: ctx.turnUsageSegmentsComplete,- // Persist observed streaming time only after provider usage calibration.- // Tools, request waiting and completed-only output have no TPS denominator.- ...(speedDuration !== undefined- ? { durationMs: speedDuration }+ // durationMs is deliberately generation-only. If Pi does not report a+ // per-assistant generation duration, omit it instead of charging tool+ // execution / user waits to TPS.+ ...(ctx.generationTimingReliable && ctx.generationDurationMs > 0+ ? { durationMs: ctx.generationDurationMs }: {}),...(ctx.turnWallClockStartedAt > 0? { turnDurationMs: Math.max(0, Date.now() - ctx.turnWallClockStartedAt) }@@ -1069,14 +1044,11 @@ export function translatePiEvent(}case 'auto_retry_start': {- ctx.responseSpeed.endResponse();// A provider retry may begin without a matching message_end for the// failed request. Drop any stale latch so the next request samples its// own tariff at message_start.ctx.pendingPriceVariants = [];if (isCurrentTurnHostAbortRequested(ctx)) return;- if (!ctx.responseSpeed.beginRetry()) return;- pushStatus(queue, ctx, 'Working…', true);// `(auto-retry N/M)` 只给过载用:mobile / Telegram 把这个后缀当成「模型服务繁忙」。// 网络类改走 `Reconnecting... N/M`,未分类 5xx / LiteLLM in-stream 仍静默。const progress = parsePiAutoRetryProgress(event);diff --git a/packages/maker-core/src/agents/shared/live-generation-snapshot.ts b/packages/maker-core/src/agents/shared/live-generation-snapshot.tsindex 542f0e1435..be8802c8a0 100644--- a/packages/maker-core/src/agents/shared/live-generation-snapshot.ts+++ b/packages/maker-core/src/agents/shared/live-generation-snapshot.ts@@ -2,7 +2,6 @@ import type { UsageSnapshot } from '../../types/events.js';export interface LiveGenerationTiming {/** Turn-cumulative output tokens, including reasoning. */- responseSpeed?: import("@cindy/maker-shared/usage-format").ResponseSpeedSnapshot;outputTokens: number;/** Duration captured with outputTokens; sparse usage must not include later in-flight time. */durationMs: number;@@ -27,7 +26,7 @@ export function attachLiveGeneration(typeof timing.outputTokens === 'number' && Number.isFinite(timing.outputTokens)? Math.max(0, timing.outputTokens): 0;- const next: UsageSnapshot = { ...snapshot, outputTokens, ...(timing.responseSpeed ? { responseSpeed: timing.responseSpeed } : {}) };+ const next: UsageSnapshot = { ...snapshot, outputTokens };if (!timing.reliable) {return {...next,diff --git a/packages/maker-core/src/agents/shared/response-speed-adapters.test.ts b/packages/maker-core/src/agents/shared/response-speed-adapters.test.tsdeleted file mode 100644index 9ffeeba8f5..0000000000--- a/packages/maker-core/src/agents/shared/response-speed-adapters.test.ts+++ /dev/null@@ -1,158 +0,0 @@-import { afterEach, expect, it, vi } from 'vitest';-import type { AgentEvent } from '../../types/events.js';-import type { AsyncQueue } from './async-queue.js';-import type { Logger } from '../../interfaces/logger.js';-import { UsageTracker } from './usage-tracker.js';-import { newRuntimeState, translateSdkMessage, type TurnState } from '../claude-code/translator.js';-import { createPiTranslateContext, disposePiTranslateContext, translatePiEvent, usageSnapshotOf } from '../pi/translator.js';-import type { PiRpcEvent } from '../pi/rpc-client.js';-import { beginCodexGenerationTurn, newCodexRuntimeState, translateAgentMessageDelta,- translateItemNotification, pauseCodexGeneration } from '../codex/translator.js';--afterEach(() => vi.restoreAllMocks());-function harness() {- const events: AgentEvent[] = [];- const queue = { push: (event: AgentEvent) => events.push(event) } as unknown as AsyncQueue<AgentEvent>;- return { events, queue };-}-const log = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };--it('Pi publishes streaming estimates with untouched billing/cache counters, then calibrates two tool rounds', () => {- const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000);- const { queue, events } = harness();- const ctx = createPiTranslateContext(log as unknown as Logger);- const send = (now: number, event: Record<string, unknown>) => {- clock.mockReturnValue(now); translatePiEvent(event as unknown as PiRpcEvent, queue, ctx);- };- try {- send(1_000, { type: 'agent_start' });- send(2_000, { type: 'message_start', message: { role: 'assistant' } });- send(3_000, { type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: 'a'.repeat(40) } });- send(4_000, { type: 'message_update', assistantMessageEvent: { type: 'toolcall_delta', delta: 'b'.repeat(40) } });- expect(usageSnapshotOf(ctx)).toMatchObject({ tokenUsage: 0, outputTokens: 0,- responseSpeed: { firstResponseMs: 2_000, estimated: true, outputTokens: 20 } });- expect(events.some((event) => event.type === 'status' &&- ((event.data as { responseSpeed?: { recentRate: number } }).responseSpeed?.recentRate ?? 0) > 0)).toBe(true);- send(5_000, { type: 'message_end', message: { role: 'assistant', content: [],- usage: { input: 10, output: 100, cacheRead: 20, cacheWrite: 5 }, duration: 3_000 } });- send(6_000, { type: 'tool_execution_start', toolCallId: 't', toolName: 'bash', args: {} });- expect(usageSnapshotOf(ctx).responseSpeed).toMatchObject({ phase: 'paused', toolActive: true, recentRate: null });- send(16_000, { type: 'tool_execution_end', toolCallId: 't', toolName: 'bash', result: { content: [] } });- expect(events.filter(event => event.type === 'status').at(-1)?.data).toMatchObject({- responseSpeed: { phase: 'waiting', toolActive: false, waitingMs: 0, durationMs: 2_000 },- });- send(17_000, { type: 'message_start', message: { role: 'toolResult' } });- expect(usageSnapshotOf(ctx).responseSpeed).toMatchObject({ phase: 'waiting', waitingMs: 1_000 });- send(17_000, { type: 'message_start', message: { role: 'assistant' } });- send(18_000, { type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: 'answer' } });- send(19_000, { type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: 'answer' }],- usage: { input: 10, output: 50 }, duration: 2_000 } });- send(20_000, { type: 'agent_settled' });- expect(usageSnapshotOf(ctx).responseSpeed).toMatchObject({ phase: 'complete', estimated: false,- outputTokens: 150, durationMs: 3_000, averageRate: 50 });- expect((events.find((event) => event.type === 'done')!.data as { usage: unknown }).usage)- .toMatchObject({ inputTokens: 20, outputTokens: 150, cacheReadTokens: 20,- cacheCreationTokens: 5, durationMs: 3_000 });- send(21_000, { type: 'agent_start' });- expect(usageSnapshotOf(ctx).responseSpeed).toMatchObject({ firstResponseMs: null, outputTokens: 0, samples: [] });- } finally { disposePiTranslateContext(ctx); }-});--it('Claude measures only SDK stream wait, keeps child output separate, and deduplicates message usage', () => {- const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000);- const { queue, events } = harness();- const turn: TurnState = { text: '', toolUses: 0, apiCalls: 0, sawCompactBoundary: false,- hasEmittedText: false, uiEmittedText: '', pendingApiError: null, interruptRequested: false,- generation: 0, interruptGeneration: 0, lastAssistantMsgHadSubstance: true };- const ctx = { rt: newRuntimeState(), turn, log, getModel: () => 'test-model',- getEffort: () => 'high', getPermissionMode: () => 'auto', onSessionId: vi.fn(),- getSdkSessionId: () => undefined, getLogTitle: () => undefined, tracker: new UsageTracker() };- const stream = (now: number, event: Record<string, unknown>, parent_tool_use_id?: string) => {- clock.mockReturnValue(now); translateSdkMessage({ type: 'stream_event', event, parent_tool_use_id }, queue, ctx);- };- stream(1_000, { type: 'message_start', message: { id: 'm1', model: 'test-model' } });- stream(2_000, { type: 'content_block_start', content_block: { type: 'thinking' } });- stream(2_000, { type: 'content_block_delta', delta: { type: 'thinking_delta', thinking: 'a'.repeat(40) } });- stream(3_000, { type: 'content_block_delta', delta: { type: 'input_json_delta', partial_json: 'b'.repeat(40) } });- const beforeChild = ctx.rt.generation.responseSpeed.snapshot();- stream(3_000, { type: 'content_block_delta', delta: { type: 'text_delta', text: 'child'.repeat(100) } }, 'child');- expect(ctx.rt.generation.responseSpeed.snapshot()).toEqual(beforeChild);- stream(4_000, { type: 'message_delta', usage: { output_tokens: 100 } });- stream(5_000, { type: 'message_delta', usage: { output_tokens: 100 } });- clock.mockReturnValue(20_000);- translateSdkMessage({ type: 'result', subtype: 'success', result: 'done', usage: { output_tokens: 100 } }, queue, ctx);- const done = events.find((event) => event.type === 'done')!.data as { responseSpeed: unknown };- expect(done.responseSpeed).toMatchObject({ waitOrigin: 'stream', firstResponseMs: 1_000,- outputTokens: 100, durationMs: 2_000, estimated: false, averageRate: 50 });-});--it('Codex counts the shared snapshot/delta cursor once and pauses while tools own the turn', () => {- const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000);- const rt = newCodexRuntimeState();- const { queue } = harness();- const ctx = { rt, log };- beginCodexGenerationTurn(rt, 'turn', 1_000);- clock.mockReturnValue(2_000);- translateAgentMessageDelta({ threadId: 'thread', turnId: 'turn', itemId: 'msg', delta: 'a'.repeat(40) }, queue, ctx);- clock.mockReturnValue(3_000);- translateItemNotification('updated', { threadId: 'thread', turnId: 'turn', item:- { id: 'msg', type: 'agentMessage', text: 'a'.repeat(40) } }, queue, ctx);- expect(rt.responseSpeed.snapshot().outputTokens).toBe(10);- pauseCodexGeneration(rt, 'turn', 'tool', 4_000);- clock.mockReturnValue(15_000);- rt.responseSpeed.finish(100);- expect(rt.responseSpeed.snapshot()).toMatchObject({ waitOrigin: 'turn', firstResponseMs: 1_000,- durationMs: 2_000, outputTokens: 100, averageRate: 50 });- // Reset disposes the old generation heartbeat without altering the completed speed snapshot.- beginCodexGenerationTurn(rt, 'next', 16_000);- pauseCodexGeneration(rt, 'next', 'cleanup', 16_000);-});--it('Pi publishes even an unclassified native retry without adding an error banner, then recovers on content', () => {- const clock = vi.spyOn(Date, 'now').mockReturnValue(1000);- const { queue, events } = harness();- const ctx = createPiTranslateContext(log as unknown as Logger);- try {- translatePiEvent({ type: 'agent_start' } as PiRpcEvent, queue, ctx);- clock.mockReturnValue(2000);- translatePiEvent({ type: 'auto_retry_start', attempt: 1, maxAttempts: 3,- errorMessage: 'unclassified upstream error' } as PiRpcEvent, queue, ctx);- expect(events.filter(event => event.type === 'error')).toHaveLength(0);- expect(events.filter(event => event.type === 'status').at(-1)?.data).toMatchObject({- responseSpeed: { retrying: true, recentRate: null } });- clock.mockReturnValue(12000);- translatePiEvent({ type: 'message_start', message: { role: 'assistant' } } as PiRpcEvent, queue, ctx);- translatePiEvent({ type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: 'recovered' } } as PiRpcEvent, queue, ctx);- expect(usageSnapshotOf(ctx).responseSpeed).toMatchObject({ retrying: false, durationMs: 0 });- ctx.responseSpeed.finish();- const settledEvents = events.length;- translatePiEvent({ type: 'auto_retry_start', attempt: 2, maxAttempts: 3 } as PiRpcEvent, queue, ctx);- expect(events).toHaveLength(settledEvents);- } finally { disposePiTranslateContext(ctx); }-});--it('Claude publishes its first native retry without an error banner and excludes backoff from generation', () => {- const clock = vi.spyOn(Date, 'now').mockReturnValue(1000);- const { queue, events } = harness();- const turn: TurnState = { text: '', toolUses: 0, apiCalls: 0, sawCompactBoundary: false,- hasEmittedText: false, uiEmittedText: '', pendingApiError: null, interruptRequested: false,- generation: 0, interruptGeneration: 0, lastAssistantMsgHadSubstance: true };- const ctx = { rt: newRuntimeState(), turn, log, getModel: () => 'test-model',- getEffort: () => 'high', getPermissionMode: () => 'auto', onSessionId: vi.fn(),- getSdkSessionId: () => undefined, getLogTitle: () => undefined, tracker: new UsageTracker() };- translateSdkMessage({ type: 'system', subtype: 'api_retry', attempt: 1, max_retries: 3,- retry_delay_ms: 10000, error_status: 500, error: 'api_error' }, queue, ctx);- expect(events.filter(event => event.type === 'error')).toHaveLength(0);- expect(events.filter(event => event.type === 'status').at(-1)?.data).toMatchObject({- responseSpeed: { retrying: true, recentRate: null } });- clock.mockReturnValue(12000);- translateSdkMessage({ type: 'stream_event', event: { type: 'message_start', message: { id: 'recovered' } } }, queue, ctx);- translateSdkMessage({ type: 'stream_event', event: { type: 'content_block_start', content_block: { type: 'text' } } }, queue, ctx);- expect(ctx.rt.generation.responseSpeed.snapshot().retrying).not.toBe(true);- expect(ctx.rt.generation.responseSpeed.snapshot().durationMs).toBe(0);- ctx.turn.interruptRequested = true;- const stoppedEvents = events.length;- translateSdkMessage({ type: 'system', subtype: 'api_retry', attempt: 2, max_retries: 3,- retry_delay_ms: 1000, error_status: 529, error: 'overloaded_error' }, queue, ctx);- expect(events).toHaveLength(stoppedEvents);-});diff --git a/packages/maker-core/src/agents/shared/response-speed.test.ts b/packages/maker-core/src/agents/shared/response-speed.test.tsdeleted file mode 100644index c1bea31587..0000000000--- a/packages/maker-core/src/agents/shared/response-speed.test.ts+++ /dev/null@@ -1,237 +0,0 @@-import { describe, expect, it } from 'vitest';-import { retryResponseSpeed, resumeResponseSpeed, mergeResponseSpeedStatus, calibratedResponseDuration, readResponseSpeedSnapshot, stopResponseSpeed, responseSpeedHistory, responseSpeedActivity } from '@cindy/maker-shared/usage-format';-import { ResponseSpeedTracker } from './response-speed.js';--describe('response speed', () => {- it('distinguishes observed output, silence, execution and subsequent request waiting', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 1000);- expect(responseSpeedActivity(speed.snapshot(2000), 2000)).toBe('waiting');- speed.delta('tool arguments', 2000);- expect(speed.snapshot(2000).toolActive).toBe(false);- expect(responseSpeedActivity(speed.snapshot(2000), 2000)).toBe('generating');- expect(responseSpeedActivity(speed.snapshot(3500), 3500)).toBe('quiet');- speed.endResponse(20, 4000);- expect(responseSpeedActivity(speed.snapshot(4000), 4000)).toBe('paused');- speed.toolStarted('command');- expect(responseSpeedActivity(speed.snapshot(5000), 5000)).toBe('tool');- // A concurrent model delta remains model generation, even with a tool active.- speed.delta('parallel output', 6000);- expect(responseSpeedActivity(speed.snapshot(6000), 6000)).toBe('generating');- speed.toolEnded('command');- speed.beginRequest(7000);- expect(speed.snapshot(8500)).toMatchObject({ phase: 'waiting', waitingMs: 1500, firstResponseMs: 1000 });- speed.finish(undefined, 9000);- expect(responseSpeedActivity(speed.snapshot(10000), 10000)).toBe('complete');- });- it('separates first content wait from streaming time and calibrates the curve', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- expect(speed.snapshot(2_000)).toMatchObject({ phase: 'waiting', waitingMs: 2_000, recentRate: null });- speed.content(2_000);- speed.delta('a'.repeat(40), 2_000);- speed.delta('b'.repeat(40), 3_000);- expect(speed.snapshot(3_000)).toMatchObject({ firstResponseMs: 2_000, estimated: true, outputTokens: 20 });- expect(speed.snapshot(3_000).samples.length).toBeGreaterThan(0);- speed.endResponse(100, 4_000);- speed.finish(undefined, 20_000);- const done = speed.snapshot(20_000);- expect(done).toMatchObject({ durationMs: 2_000, outputTokens: 100, estimated: false, averageRate: 50, recentRate: 50 });- expect(done.samples.at(-1)?.rate).toBe(50);- expect(calibratedResponseDuration(done, 100)).toBe(2_000);- expect(calibratedResponseDuration(done, 101)).toBeUndefined();- });-- it('updates a long response before any usage arrives and decays a silent window', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- speed.content(1_000);- for (let now = 1_000; now <= 8_000; now += 250) speed.delta('abcdefgh', now);- expect(speed.snapshot(8_000).samples.length).toBeGreaterThan(20);- expect(speed.snapshot(8_000)).toMatchObject({ estimated: true, phase: 'generating' });- expect(speed.snapshot(9_500).recentRate).toBeNull();- });-- it('excludes tools and the next request wait, and calibrates each response separately', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- speed.content(1_000);- speed.delta('a'.repeat(40), 1_000);- speed.endResponse(40, 2_000);- speed.beginRequest(10_000);- speed.content(12_000);- speed.delta('a'.repeat(40), 12_000);- speed.endResponse(60, 13_000);- speed.finish(undefined, 30_000);- expect(speed.snapshot(30_000)).toMatchObject({ firstResponseMs: 1_000, durationMs: 2_000,- outputTokens: 100, estimated: false, averageRate: 50 });- });-- it('does not double-add repeated per-response usage and handles a real zero', () => {- const speed = new ResponseSpeedTracker('stream');- speed.beginRequest(1_000);- speed.delta('a'.repeat(40), 2_000);- speed.reportOutput(50);- speed.reportOutput(50);- speed.pause(3_000);- speed.beginRequest(4_000);- speed.delta('a'.repeat(40), 5_000);- speed.endResponse(0, 6_000);- speed.finish(undefined, 7_000);- expect(speed.snapshot(7_000)).toMatchObject({ waitOrigin: 'stream', firstResponseMs: 1_000,- outputTokens: 50, durationMs: 2_000, estimated: false, averageRate: 25 });- });-- it('keeps missing usage approximate and suppresses completed-only or untimed output', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- speed.delta('a'.repeat(40), 1_000);- speed.finish(undefined, 2_000);- expect(speed.snapshot(2_000)).toMatchObject({ estimated: true, outputTokens: 10, averageRate: 10 });- expect(calibratedResponseDuration(speed.snapshot(2_000), 10)).toBeUndefined();- speed.reset('turn', 3_000);- speed.endResponse(100, 4_000);- speed.finish(undefined, 5_000);- expect(speed.snapshot(5_000)).toMatchObject({ firstResponseMs: null, averageRate: null, samples: [] });- });-- it('cumulative turn usage calibrates Codex without counting hidden reasoning twice', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- speed.delta('a'.repeat(40), 1_000);- speed.pause(2_000);- speed.delta('b'.repeat(40), 10_000);- speed.finish(200, 11_000);- expect(speed.snapshot(20_000)).toMatchObject({ outputTokens: 200, durationMs: 2_000, averageRate: 100 });- speed.finish(300, 30_000);- expect(speed.snapshot(30_000).outputTokens).toBe(200);- });-- it('does not manufacture a current rate from a short burst, silence or a tool gap', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- speed.delta('a'.repeat(4000), 1000);- expect(speed.snapshot(1250).recentRate).toBeNull();- speed.delta('a'.repeat(40), 2000);- const observed = speed.snapshot(2000);- expect(observed.recentRate).toBe(10);- const local = readResponseSpeedSnapshot(observed, 100000)!;- expect(responseSpeedHistory(local, 100999).latestRate).toBe(10);- expect(responseSpeedHistory(local, 101000).latestRate).toBeNull();- expect(local.firstResponseMs).toBe(observed.firstResponseMs);- expect(speed.snapshot(5000).recentRate).toBeNull();- speed.pause(5000);- speed.delta('resume', 20000);- expect(speed.snapshot(20000).recentRate).toBeNull();- speed.finish(1100, 21000);- expect(speed.snapshot(21000)).toMatchObject({ durationMs: 5000, averageRate: 220 });- });-- it('reset clears cancelled/retried turns and ignores late deltas after completion', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- speed.delta('a'.repeat(40), 1_000);- speed.finish(undefined, 2_000);- speed.delta('late', 3_000);- speed.reset('turn', 4_000);- expect(speed.snapshot(4_500)).toMatchObject({ phase: 'waiting', firstResponseMs: null,- waitingMs: 500, outputTokens: 0, samples: [] });- speed.content(5_000);- speed.finish(0, 6_000);- expect(speed.snapshot(6_000)).toMatchObject({ outputTokens: 0, estimated: false, averageRate: 0 });- });-- it('expires high-frequency output instead of renewing accumulated units', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- speed.content(0);- for (let now = 1; now <= 10_000; now++) {- speed.delta('abcd', now); // 1 estimated token, 1000 deltas per second.- if (now === 1_000 || now === 5_000 || now === 10_000) {- expect(speed.snapshot(now).recentRate).toBeGreaterThanOrEqual(996);- expect(speed.snapshot(now).recentRate).toBeLessThanOrEqual(1000);- }- }- expect(speed.snapshot(10_000).samples.every(sample => sample.rate <= 1000)).toBe(true);- expect(responseSpeedHistory(speed.snapshot(10_000), 10_000).peak).toBeLessThanOrEqual(1000);- expect(speed.snapshot(11_000).recentRate).toBeNull();- speed.pause(11_000);- for (let now = 20_000; now <= 21_000; now++) speed.delta('abcd', now);- expect(speed.snapshot(21_000).recentRate).toBeLessThanOrEqual(1000);- expect(speed.snapshot(22_000).recentRate).toBeNull();- speed.finish(11_001, 22_000);- const done = speed.snapshot(22_000);- expect(done).toMatchObject({ estimated: false, outputTokens: 11_001,- durationMs: 13_000, averageRate: 11_001_000 / 13_000 });- expect(responseSpeedHistory(done, 22_000).peak).toBeLessThanOrEqual(1000);- });-- it('character estimates are independent of chunk boundaries and samples stay bounded', () => {- const measure = (chunks: string[]) => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- for (const chunk of chunks) speed.delta(chunk, 1_000);- return speed.snapshot(2_000).outputTokens;- };- expect(measure(['hello 世界 👋'])).toBe(measure(['h', 'ello ', '世', '界 ', '👋']));- expect(measure(['👋'.repeat(10)])).toBe(measure('👋'.repeat(10).split('')));- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- for (let i = 1; i < 500; i++) speed.delta('a', i * 250);- expect(speed.snapshot(125_000).samples.length).toBeLessThanOrEqual(60);- speed.invalidate();- expect(speed.snapshot(125_000)).toMatchObject({ averageRate: null, recentRate: null, samples: [] });- });-- it('freezes an interrupted observation without claiming provider calibration', () => {- const speed = new ResponseSpeedTracker();- speed.reset('turn', 0);- speed.delta('a'.repeat(40), 1_000);- const stopped = stopResponseSpeed(speed.snapshot(2_000));- expect(stopped).toMatchObject({ phase: 'complete', estimated: true, durationMs: 1_000 });- expect(calibratedResponseDuration(stopped, 10)).toBeUndefined();- expect(stopResponseSpeed(stopped)).toBe(stopped);- });-- it('rejects malformed remote snapshots and supports older hosts omitting the field', () => {- expect(readResponseSpeedSnapshot(undefined)).toBeUndefined();- expect(readResponseSpeedSnapshot({ phase: 'generating', outputTokens: Infinity })).toBeUndefined();- const speed = new ResponseSpeedTracker();- speed.reset('turn', 1_000);- expect(readResponseSpeedSnapshot(speed.snapshot(2_000))).toEqual(speed.snapshot(2_000));- });-});--it('retains incomplete history without showing success or a live rate on failure, cancellation or retry', () => {- const tracker = new ResponseSpeedTracker();- tracker.reset('turn', 0);- tracker.delta('observed output', 1000);- tracker.delta('more observed output', 2000);- const original = tracker.snapshot(2000);- for (const outcome of ['failed', 'cancelled'] as const) {- const stopped = stopResponseSpeed(original, outcome)!;- expect(responseSpeedActivity(stopped, 3000)).toBe(outcome);- expect(responseSpeedHistory(stopped).latestRate).toBeNull();- expect(stopped.samples).toEqual(original.samples);- expect(stopped.averageRate).toBe(original.averageRate);- expect(calibratedResponseDuration(stopped, stopped.outputTokens)).toBeUndefined();- expect(mergeResponseSpeedStatus(stopped, { ...original, phase: 'complete' }, false, false)?.outcome).toBe(outcome);- expect(mergeResponseSpeedStatus(stopped, undefined, true, true)).toBeUndefined();- }- const retry = retryResponseSpeed(original)!;- expect(responseSpeedActivity(retry)).toBe('retrying');- expect(responseSpeedHistory(retry).latestRate).toBeNull();- expect(mergeResponseSpeedStatus(retry, original, true, false)?.retrying).toBe(true);- expect(mergeResponseSpeedStatus(retry, { ...original, outputTokens: 1000 }, true, false)?.retrying).toBe(true);- expect(responseSpeedActivity(mergeResponseSpeedStatus(retry, { ...original, phase: 'complete' }, true, false)!)).toBe('retrying');- expect(mergeResponseSpeedStatus(retry, { ...original, hasRecentOutput: true,- samples: [...original.samples, { durationMs: original.durationMs + 1000, outputTokens: 100, rate: 40 }] }, true, false)?.retrying).not.toBe(true);- expect(mergeResponseSpeedStatus(retry, { ...original, retrying: false }, true, false)?.retrying).toBe(false);- expect(resumeResponseSpeed(retry)?.retrying).toBe(false);- const parallelToolRetry = retryResponseSpeed({ ...original, phase: 'paused', toolActive: true })!;- expect(parallelToolRetry.toolActive).toBe(true);- expect(mergeResponseSpeedStatus(parallelToolRetry, { ...original, phase: 'paused', toolActive: true }, true, false)?.retrying).toBe(true);- expect(responseSpeedActivity(resumeResponseSpeed(parallelToolRetry)!)).toBe('tool');- expect(readResponseSpeedSnapshot({ ...original, outcome: 'unknown' })).toBeUndefined();- expect(readResponseSpeedSnapshot({ ...original, retrying: 'yes' })).toBeUndefined();-});diff --git a/packages/maker-core/src/agents/shared/response-speed.ts b/packages/maker-core/src/agents/shared/response-speed.tsdeleted file mode 100644index f052775a6e..0000000000--- a/packages/maker-core/src/agents/shared/response-speed.ts+++ /dev/null@@ -1,206 +0,0 @@-import type { ResponseSpeedSnapshot, RateSample } from '@cindy/maker-shared/usage-format';--const WINDOW_MS = 1_000;-const WINDOW_BUCKET_MS = 4;-const REFRESH_MS = 250;-const MAX_SAMPLES = 60;--/**- * Inspired by pi-token-speed's separate wait/stream clocks and usage reconciliation.- * Original implementation: estimates characters, never treats a transport chunk as a token.- * Only display facts leave this object; UsageTracker remains the accounting authority.- */-export class ResponseSpeedTracker {- private origin: 'turn' | 'stream' = 'turn';- private startedAt: number | null = null;- private firstAt: number | null = null;- private waitingAt: number | null = null;- private tools = new Set<string>();- private openAt: number | null = null;- private closedMs = 0;- private phase: ResponseSpeedSnapshot['phase'] = 'waiting';- private retrying = false;- private retryObserved = false;- private settledTokens = 0;- private units = 0;- private reported: number | null = null;- private allCalibrated = true;- private measurable = true;- private segment = 0;- private lastSampleAt = 0;- private lastDeltaAt: number | null = null;- private window: { time: number; units: number }[] = [];- private points: (RateSample & { segment: number; units: number })[] = [];-- constructor(origin: 'turn' | 'stream' = 'turn') { this.origin = origin; }-- reset(origin: 'turn' | 'stream', now = Date.now()): void {- this.origin = origin;- this.startedAt = now;- this.waitingAt = now;- this.tools.clear();- this.firstAt = this.openAt = null;- this.closedMs = this.settledTokens = this.units = 0;- this.reported = null;- this.allCalibrated = this.measurable = true;- this.phase = 'waiting';- this.retrying = this.retryObserved = false;- this.segment = 0;- this.lastSampleAt = 0;- this.lastDeltaAt = null;- this.window = [];- this.points = [];- }-- /** A new request starts waiting again; tools and prompt processing are not generation. */- beginRequest(now = Date.now()): void {- if (this.startedAt === null || this.phase === 'complete') this.reset(this.origin, now);- this.endResponse(undefined, now);- if (this.origin === 'stream' && this.firstAt === null) this.startedAt = now;- this.phase = 'waiting';- this.waitingAt = now;- }-- content(now = Date.now()): void {- if (this.startedAt === null || this.phase === 'complete') return;- if (this.firstAt === null) this.firstAt = now;- if (this.openAt === null) {- this.openAt = now;- this.window = [];- }- this.phase = 'generating';- this.retrying = false;- this.waitingAt = null;- }-- delta(text: string, now = Date.now()): boolean {- if (!text || this.startedAt === null || this.phase === 'complete') return false;- this.content(now);- // Additive across arbitrary chunks; no regex word-boundary or per-delta rounding.- let units = 0;- for (const character of text) units += character.charCodeAt(0) > 0xff ? 0.67 * character.length : 0.25;- this.units += units;- this.reported = null;- this.lastDeltaAt = now;- // Fixed bucket boundaries never move forward as new units arrive. At most- // four milliseconds of the oldest edge expire early; old output cannot- // keep renewing itself in a high-frequency stream.- const bucketAt = Math.floor(now / WINDOW_BUCKET_MS) * WINDOW_BUCKET_MS;- const bucket = this.window.at(-1);- if (bucket?.time === bucketAt) bucket.units += units;- else this.window.push({ time: bucketAt, units });- this.prune(now);- if (now - this.lastSampleAt < REFRESH_MS) return false;- this.lastSampleAt = now;- const rate = this.recent(now);- if (rate !== null) {- this.points.push({ durationMs: this.duration(now), outputTokens: this.settledTokens + this.units,- rate, segment: this.segment, units: this.units });- this.points = this.points.slice(-MAX_SAMPLES);- }- return true;- }-- pause(now = Date.now()): void {- if (this.openAt !== null) this.closedMs += Math.max(0, now - this.openAt);- this.openAt = null;- if (this.phase !== 'complete') this.phase = 'paused';- this.window = [];- this.waitingAt = null;- }-- /** A native retry event proves automatic recovery, even when no error banner is emitted. */- beginRetry(now = Date.now()): boolean {- if (this.startedAt === null) this.reset(this.origin, now);- if (this.phase === 'complete') return false;- this.pause(now);- this.retrying = this.retryObserved = true;- return true;- }-- toolStarted(id: string): void { if (id) this.tools.add(id); }- toolEnded(id: string): boolean { return this.tools.delete(id); }-- reportOutput(output: number | undefined): void {- if (output !== undefined && Number.isFinite(output) && output >= 0) this.reported = output;- }-- /** Provider counts for this assistant response, including a legitimate zero. */- endResponse(output?: number, now = Date.now()): void {- this.pause(now);- this.reportOutput(output);- const count = this.reported ?? this.units;- if (count > 0 && this.units === 0) this.measurable = false;- if (this.units > 0) {- const factor = count / this.units;- this.points = this.points.map((point) => point.segment === this.segment- ? { ...point, rate: point.rate * factor,- outputTokens: this.settledTokens + point.units * factor } : point);- }- if (this.reported === null && this.units > 0) this.allCalibrated = false;- this.settledTokens += count;- this.units = 0;- this.reported = null;- this.segment += 1;- }-- /** Codex exposes cumulative turn usage, rather than a stable request-end pair. */- finish(total?: number, now = Date.now()): void {- if (this.phase === 'complete') return;- this.endResponse(undefined, now);- if (total !== undefined && Number.isFinite(total) && total >= 0) {- if (this.settledTokens > 0) {- const factor = total / this.settledTokens;- this.points = this.points.map((point) => ({ ...point,- rate: point.rate * factor, outputTokens: point.outputTokens * factor }));- } else if (total > 0) this.measurable = false;- this.settledTokens = total;- this.allCalibrated = true;- }- this.phase = 'complete';- this.retrying = false;- }-- invalidate(): void { this.measurable = false; }-- snapshot(now = Date.now()): ResponseSpeedSnapshot {- this.prune(now);- const outputTokens = Math.round(this.settledTokens + (this.reported ?? this.units));- const durationMs = this.duration(now);- const averageRate = this.measurable && durationMs > 0- ? outputTokens * 1_000 / durationMs : null;- return {- phase: this.phase, waitOrigin: this.origin,- firstResponseMs: this.startedAt !== null && this.firstAt !== null- ? Math.max(0, this.firstAt - this.startedAt) : null,- waitingMs: this.phase === 'waiting' && this.waitingAt !== null- ? Math.max(0, now - this.waitingAt) : 0,- outputTokens, durationMs,- estimated: !this.allCalibrated || (this.units > 0 && this.reported === null),- recentRate: this.phase === 'complete' ? averageRate : this.recent(now),- averageRate,- samples: this.measurable ? this.points.map(({ durationMs, outputTokens, rate }) =>- ({ durationMs, outputTokens, rate })) : [],- sampledAt: now,- hasRecentOutput: this.phase === 'generating' && this.window.length > 0,- toolActive: this.tools.size > 0,- ...(this.retryObserved ? { retrying: this.retrying } : {}),- };- }-- private duration(now: number): number {- return this.closedMs + (this.openAt === null ? 0 : Math.max(0, now - this.openAt));- }- private prune(now: number): void {- this.window = this.window.filter((point) => now - point.time < WINDOW_MS);- // A monotonic one-second window has at most 251 fixed buckets. Bound even- // malformed/backwards clocks without renewing discarded output's lifetime.- if (this.window.length > 256) this.window = this.window.slice(-256);- }- private recent(now: number): number | null {- if (!this.measurable || this.openAt === null || this.lastDeltaAt === null) return null;- const elapsed = Math.min(WINDOW_MS, Math.max(0, now - this.openAt));- if (elapsed < WINDOW_MS || this.window.length === 0) return null;- return this.window.reduce((sum, point) => sum + point.units, 0) * 1_000 / elapsed;- }-}diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex eeda14b5c1..d2df179d45 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -406,7 +406,6 @@ export interface InteractionDismissedEvent {* 注: isRunning / status text 不属于 usage, 由 translator 在 emit status event 时单独拼。*/export interface UsageSnapshot {- responseSpeed?: import("@cindy/maker-shared/usage-format").ResponseSpeedSnapshot;tokenUsage: number;contextTokens: number;contextWindow: number;diff --git a/packages/maker-shared/src/runningTokenRateHistory.ts b/packages/maker-shared/src/runningTokenRateHistory.tsindex f42e0c54f9..c40497e66e 100644--- a/packages/maker-shared/src/runningTokenRateHistory.ts+++ b/packages/maker-shared/src/runningTokenRateHistory.ts@@ -3,115 +3,6 @@ interface RateCounters {outputTokens: number;}-/** Display-only stream measurement. Never use these counters for billing or context. */-export interface ResponseSpeedSnapshot {- phase: 'waiting' | 'generating' | 'paused' | 'complete';- /** Local provider-turn start, or SDK stream start (not network TTFT). */- waitOrigin: 'turn' | 'stream';- firstResponseMs: number | null;- waitingMs: number;- outputTokens: number;- durationMs: number;- estimated: boolean;- recentRate: number | null;- averageRate: number | null;- samples: RateSample[];- sampledAt: number;- /** Fresh observed output, including warm-up before the first full rate window. */- hasRecentOutput?: boolean;- /** Explicit native tool execution, distinct from streamed tool arguments. */- toolActive?: boolean;- /** Display annotation from an explicit terminal event, never inferred from silence. */- outcome?: 'failed' | 'cancelled';- /** True requires an explicit retry event; false can acknowledge native recovery. */- retrying?: boolean;-}--export function responseSpeedActivity(speed: ResponseSpeedSnapshot, now = Date.now()):- 'waiting' | 'generating' | 'quiet' | 'tool' | 'paused' | 'complete' | 'failed' | 'cancelled' | 'retrying' {- if (speed.phase === 'complete') return speed.outcome ?? 'complete';- if (speed.retrying) return 'retrying';- if (speed.phase === 'waiting') return 'waiting';- if (speed.phase === 'paused') return speed.toolActive ? 'tool' : 'paused';- return now - speed.sampledAt < RATE_SAMPLE_FRESH_MS &&- (speed.hasRecentOutput ?? speed.recentRate !== null) ? 'generating' : 'quiet';-}--export function responseSpeedHistory(speed: ResponseSpeedSnapshot, now = Date.now()): RateHistory {- return {- ...emptyRateHistory(null),- samples: speed.samples,- peak: Math.max(0, ...speed.samples.map((sample) => sample.rate)),- latestRate: speed.outcome || speed.retrying || (speed.phase === 'generating' && now - speed.sampledAt >= RATE_SAMPLE_FRESH_MS) ? null : speed.recentRate,- latestSampleAt: speed.sampledAt,- };-}--/** Optional additive wire field: old hosts simply omit it. Reject malformed peer data. */-export function readResponseSpeedSnapshot(value: unknown, observedAt?: number): ResponseSpeedSnapshot | undefined {- if (!value || typeof value !== 'object') return undefined;- const speed = value as ResponseSpeedSnapshot;- const finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0;- if (!['waiting', 'generating', 'paused', 'complete'].includes(speed.phase) ||- !['turn', 'stream'].includes(speed.waitOrigin) || typeof speed.estimated !== 'boolean' ||- !finite(speed.waitingMs) || !finite(speed.outputTokens) || !finite(speed.durationMs) ||- !finite(speed.sampledAt) || (speed.hasRecentOutput !== undefined && typeof speed.hasRecentOutput !== 'boolean') ||- (speed.toolActive !== undefined && typeof speed.toolActive !== 'boolean') ||- (speed.outcome !== undefined && !['failed', 'cancelled'].includes(speed.outcome)) ||- (speed.retrying !== undefined && typeof speed.retrying !== 'boolean') ||- (speed.firstResponseMs !== null && !finite(speed.firstResponseMs)) ||- (speed.recentRate !== null && !finite(speed.recentRate)) ||- (speed.averageRate !== null && !finite(speed.averageRate)) || !Array.isArray(speed.samples)) return undefined;- return { ...speed, sampledAt: observedAt ?? speed.sampledAt, samples: speed.samples.slice(-60).filter((point) =>- point && finite(point.durationMs) && finite(point.outputTokens) && finite(point.rate)) };-}--/** Terminal errors/abort can lack a final provider snapshot. Freeze the last observation. */-export function stopResponseSpeed(speed: ResponseSpeedSnapshot | undefined, outcome?: ResponseSpeedSnapshot['outcome']): ResponseSpeedSnapshot | undefined {- if (!speed || (speed.phase === 'complete' && (!outcome || speed.outcome === outcome))) return speed;- const terminalOutcome = outcome ?? speed.outcome;- return { ...speed, phase: 'complete', ...(terminalOutcome ? { outcome: terminalOutcome } : {}), retrying: false,- recentRate: terminalOutcome ? null : speed.averageRate,- estimated: Boolean(terminalOutcome) || speed.estimated || speed.phase === 'generating' || speed.phase === 'waiting' };-}--/** Pause displayed generation only after an explicit automatic retry event. */-export function retryResponseSpeed(speed: ResponseSpeedSnapshot | undefined): ResponseSpeedSnapshot | undefined {- if (!speed || speed.phase === 'complete') return speed;- return { ...speed, phase: 'paused', retrying: true, recentRate: null,- hasRecentOutput: false };-}--/** Actual output ends the retry annotation without inventing a throughput sample. */-export function resumeResponseSpeed(speed: ResponseSpeedSnapshot | undefined): ResponseSpeedSnapshot | undefined {- return speed?.retrying && speed.phase !== 'complete'- ? { ...speed, phase: speed.toolActive ? 'paused' : 'generating', retrying: false, hasRecentOutput: false, recentRate: null }- : speed;-}--/** Preserve terminal/retry annotations across ordinary status tails; a new turn clears them. */-export function mergeResponseSpeedStatus(previous: ResponseSpeedSnapshot | undefined,- incoming: ResponseSpeedSnapshot | undefined, isRunning: boolean, isTurnStart: boolean): ResponseSpeedSnapshot | undefined {- const baseline = isTurnStart ? undefined : previous;- const next = incoming ?? baseline;- if (!isRunning) return stopResponseSpeed(next, baseline?.outcome);- if (baseline?.retrying && next && incoming?.retrying !== false) {- // Usage calibration can raise tokens without any new output. Only a new- // stream sample or explicit tool execution can recover a status-only view.- const newSample = next.hasRecentOutput === true &&- (next.samples.at(-1)?.durationMs ?? 0) > (baseline.samples.at(-1)?.durationMs ?? 0);- if (!(next.toolActive && !baseline.toolActive) && !newSample) return retryResponseSpeed({ ...next, phase: 'paused' });- }- return next;-}--/** A finalized speed denominator may only pair with the same real output count. */-export function calibratedResponseDuration(value: unknown, outputTokens: number): number | undefined {- const speed = readResponseSpeedSnapshot(value);- return speed?.phase === 'complete' && !speed.outcome && !speed.estimated && speed.averageRate !== null &&- speed.outputTokens === outputTokens && speed.durationMs > 0 ? speed.durationMs : undefined;-}-export interface RateSample extends RateCounters {/** Cumulative measured generation time across turns, excluding unmeasured gaps. */durationMs: number;@@ -120,7 +11,7 @@ export interface RateSample extends RateCounters {// Millisecond-scale usage batches are not meaningful throughput measurements.const MIN_SAMPLE_DURATION_MS = 1000;-export const RATE_SAMPLE_FRESH_MS = 1_000;+export const RATE_SAMPLE_FRESH_MS = 60_000;export interface RateHistory {startedAt: number | null;