Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(agent): add streaming response speed and retain completed results

zqchriscc7d5c09f592
diff --git a/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts b/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
index a9621fd9ce..bc9ca96b55 100644
--- a/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
@@ -1,3 +1,4 @@
+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';
@@ -99,6 +100,7 @@ export function recordSessionClaudeTurnUsage(
total_cost_usd?: unknown;
duration_ms?: unknown;
duration_api_ms?: unknown;
+ responseSpeed?: unknown;
usage?: {
input_tokens?: number;
output_tokens?: number;
@@ -169,9 +171,13 @@ export function recordSessionClaudeTurnUsage(
);
const claudeGenerationDurationMs = outputLagTiming.suppressTiming
? undefined
- : typeof doneData?.duration_api_ms === 'number'
- ? doneData.duration_api_ms
- : undefined;
+ : doneData?.responseSpeed !== undefined
+ ? calibratedResponseDuration(doneData.responseSpeed, modelUsageDeltas?.length
+ ? modelUsageDeltas.reduce((sum, delta) => sum + delta.outputTokensDelta, 0)
+ : doneData?.usage?.output_tokens ?? 0)
+ : typeof doneData?.duration_api_ms === 'number'
+ ? doneData.duration_api_ms
+ : undefined;
// total_cost_usd 累计基线: 主路径不靠它算钱, 但仍跟住, 以便万一某轮缺 modelUsage
// 走兜底时累计差才准。先取"更新前"基线给兜底用, 再写入本轮累计。
const prevReportedCost = deps.lastReportedCostUsdBySession.get(session.id);
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts
index 27ec716536..9bb49cdfbc 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreLiveGeneration.test.ts
@@ -1,6 +1,11 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/lib/makerTransport', () => ({
+ makerApiFor: () => ({ input: { stop: vi.fn(async () => ({ queue: [], paused: false })) } }),
+}));
import { makerChatStore } from '@/lib/makerChatStore';
+import type { ResponseSpeedSnapshot } from '@cindy/maker-shared/usage-format';
function applyStatus(
sessionId: string,
@@ -12,6 +17,7 @@ function applyStatus(
generationDurationMs?: number;
generationActive?: boolean;
generationReliable?: boolean;
+ responseSpeed?: ResponseSpeedSnapshot;
},
): void {
makerChatStore.__applyStatusUpdateForTest(sessionId, {
@@ -21,6 +27,7 @@ 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 }
@@ -35,6 +42,26 @@ 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: 25, 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 {
diff --git a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
index 0857964e55..047997ccce 100644
--- a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
@@ -2,8 +2,9 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import React, { useCallback, useEffect, useRef, useState } from 'react';
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { act, 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 {
@@ -40,6 +41,7 @@ const compiled = ts.transpileModule(component.getText(ast), {
const Icon = () => null;
const deps = {
React,
+ responseSpeedActivity,
useCallback,
useEffect,
useRef,
@@ -69,11 +71,12 @@ 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;
+ startedAt: number | null;
tokenUsage: number;
outputTokens: number;
generationDurationMs: number;
@@ -191,3 +194,58 @@ it.each([true, false])(
expect(container.childElementCount).toBe(0);
},
);
+
+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.noRecentSample');
+ 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(); }
+});
diff --git a/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx b/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx
index 258f619711..8d8176257f 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(59_999));
+ act(() => vi.advanceTimersByTime(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.tsx
index 622f069324..52daeba17e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1,3 +1,4 @@
+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';
@@ -5117,6 +5118,7 @@ export function CCAgentSessionView({
reconnectStatus={reconnectStatus}
tokenUsage={agentStatus.tokenUsage}
outputTokens={agentStatus.outputTokens ?? 0}
+ responseSpeed={agentStatus.responseSpeed}
generationDurationMs={agentStatus.generationDurationMs ?? 0}
generationReliable={agentStatus.generationReliable ?? true}
startedAt={agentStatus.startedAt}
@@ -5992,6 +5994,7 @@ function RunningStatusBar({
reconnectStatus = null,
tokenUsage,
outputTokens = 0,
+ responseSpeed,
generationDurationMs = 0,
generationReliable = true,
startedAt,
@@ -6013,6 +6016,7 @@ function RunningStatusBar({
reconnectStatus?: string | null;
tokenUsage: number;
outputTokens?: number;
+ responseSpeed?: ResponseSpeedSnapshot;
generationDurationMs?: number;
generationReliable?: boolean;
startedAt: number | null;
@@ -6100,6 +6104,8 @@ 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", 此时任务还在跑, 显示 ✓ 完成图标会让用户以为已经做完)。
@@ -6107,6 +6113,12 @@ function RunningStatusBar({
// 后台子任务模式的左段文案:上一轮残留的 status(多半是 "Done")在此语义下是
// 误导信息,整体替换为后台运行提示。仅后台 Bash 时用带数量的专属文案 ——
// 「模型用量仍在消耗」对不调模型的 bash 任务是错误陈述。
+ const speedActivity = responseSpeed ? responseSpeedActivity(responseSpeed) : null;
+ const speedStatusKey = speedActivity === 'waiting' ? 'responsePending'
+ : speedActivity === 'quiet' ? 'noRecentSample'
+ : speedActivity === 'tool' ? 'toolRunning'
+ : speedActivity === 'paused' ? 'generationPaused'
+ : speedActivity === 'generating' ? 'responseGenerating' : null;
const displayStatus =
reconnectStatus ??
workflowStatus ??
@@ -6114,7 +6126,8 @@ function RunningStatusBar({
? backgroundBashOnlyCount > 0
? t('chat.backgroundActivity.bashStatus', { count: backgroundBashOnlyCount })
: t('chat.backgroundActivity.status')
- : localizeAgentStatus(status, t));
+ : speedStatusKey && !status.toLowerCase().startsWith('compact')
+ ? t(`chat.runningStatus.${speedStatusKey}`) : 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
@@ -6178,30 +6191,36 @@ function RunningStatusBar({
tokens: formatRunningTokenCount(animatedTokens),
});
const rateHistory = useRunningTokenRateHistory({
+ responseSpeed,
sessionKey,
startedAt,
outputTokens,
generationDurationMs,
generationReliable:
- generationReliable &&
+ !responseSpeed && generationReliable &&
!reconnecting &&
!sideTaskRunning &&
!backgroundTasksRunning &&
!workflowWaiting,
});
const latestRate = rateHistory.latestRate;
- const usageMeta = resolveRunningUsageMeta({
+ const legacyUsageMeta = 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 && !reconnecting && usageMeta.kind === 'rate'
+ (!isHidden || completedSpeed) && !reconnecting && usageMeta.kind === 'rate'
? latestRateText !== null
- ? t('chat.runningStatus.tokenRate', { rate: latestRateText })
+ ? t(responseSpeed && (responseSpeed.phase !== 'complete' || responseSpeed.estimated) ? 'chat.runningStatus.estimatedTokenRate' : 'chat.runningStatus.tokenRate', { rate: latestRateText })
: null
: null;
@@ -6214,17 +6233,19 @@ 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 &&
- usageMeta.kind === 'rate'));
+ (Boolean(responseSpeed) || 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))) return null;
+ if (!rightLeadingSlot && (suppressContent || (isHidden && !ratePanelPinned && !completedSpeed))) return null;
// 两段式布局:左(运行状态) / 右(elapsed·tokens)。
// - 左段 min-w-0(可收缩):status 并非短枚举 —— turn-start 文案带用户名(可含中文长句)、
@@ -6286,16 +6307,17 @@ function RunningStatusBar({
走 LLM, 显示残留 token 计数会误导用户以为也耗了 token。 */}
<div className="flex min-w-0 items-center justify-self-end gap-2">
{rightLeadingSlot}
- {(!suppressContent && (!isHidden || ratePanelPinned)) && (
+ {(!suppressContent && (!isHidden || ratePanelPinned || completedSpeed)) && (
<div
data-running-status-meta="true"
className="flex min-w-0 items-center gap-[6px]"
- style={ratePanelPinned ? undefined : fadeStyle}
- aria-hidden={isHidden && !ratePanelPinned}
+ style={ratePanelPinned || completedSpeed ? undefined : fadeStyle}
+ aria-hidden={isHidden && !ratePanelPinned && !completedSpeed}
>
{showRatePanel && (
<RunningTokenRatePopover
- elapsedText={elapsedText}
+ responseSpeed={responseSpeed}
+ elapsedText={completedSpeed ? t('chat.runningStatus.lastGeneration') : waitingText ?? (speedActivity === 'quiet' ? t('chat.runningStatus.noRecentSample') : elapsedText)}
rate={latestRateText}
rateText={
workflowWaiting || sideTaskRunning || backgroundTasksRunning
@@ -6306,7 +6328,7 @@ function RunningStatusBar({
}
isTokenCount={usageMeta.kind === 'tokens'}
averageRate={usageMeta.kind === 'rate' ? usageMeta.rate : null}
- outputTokens={outputTokens}
+ outputTokens={responseSpeed?.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.tsx
index 665e3ddf13..23c7ecd5f7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx
@@ -1,3 +1,5 @@
+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';
@@ -15,6 +17,7 @@ import {
export function useRunningTokenRateHistory(input: {
/** 会话身份:用于进程内缓存速度历史,切任务再切回不清零(重启应用清零)。 */
+ responseSpeed?: ResponseSpeedSnapshot;
sessionKey: string | null;
startedAt: number | null;
outputTokens: number;
@@ -46,22 +49,24 @@ export function useRunningTokenRateHistory(input: {
}, [sessionKey, history]);
const [now, setNow] = useState(Date.now);
useEffect(() => {
- const timestamp = history.latestSampleAt;
- if (timestamp === undefined || history.latestRate === null) return;
+ const timestamp = input.responseSpeed?.sampledAt ?? history.latestSampleAt;
+ if (timestamp === undefined || (input.responseSpeed ? input.responseSpeed.phase !== 'generating' : 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]);
+ }, [history.latestSampleAt, history.latestRate, input.responseSpeed]);
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,
@@ -71,6 +76,7 @@ export function RunningTokenRatePopover({
history,
onPinnedChange,
}: {
+ responseSpeed?: ResponseSpeedSnapshot;
elapsedText: string;
rate: string | null;
rateText: string | null;
@@ -84,6 +90,8 @@ 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;
@@ -94,6 +102,7 @@ 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 = (
<div
aria-description={t('chat.runningStatus.tokenRateDescription')}
@@ -103,10 +112,14 @@ 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('chat.runningStatus.currentRate')}
+ {t(activity === 'complete' ? 'chat.runningStatus.finalAverage'
+ : activity === 'waiting' ? 'chat.runningStatus.responsePending'
+ : activity === 'tool' ? 'chat.runningStatus.toolRunning'
+ : activity === 'paused' ? 'chat.runningStatus.generationPaused'
+ : activity === 'quiet' ? 'chat.runningStatus.noRecentSample' : 'chat.runningStatus.currentRate')}
</div>
<div className="flex items-baseline gap-1.5 tabular-nums">
- <span className="text-28 font-medium leading-none">{rate ?? '—'}</span>
+ <span className="text-28 font-medium leading-none">{approximate(rate, Boolean(responseSpeed) && (responseSpeed?.phase !== 'complete' || responseSpeed.estimated)) ?? '—'}</span>
<span className="text-12 text-[var(--text-secondary)]">
{t('chat.runningStatus.tokenRateUnit')}
</span>
@@ -137,14 +150,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: averageRate }) : '—'}
+ {averageRate ? t('chat.runningStatus.tokenRate', { rate: approximate(averageRate, responseSpeed?.estimated ?? false) }) : '—'}
</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: formatRunningTokenCount(outputTokens),
+ tokens: approximate(formatRunningTokenCount(outputTokens), responseSpeed?.estimated ?? false),
})}
</dd>
</div>
@@ -153,12 +166,18 @@ export function RunningTokenRatePopover({
<dd className="font-medium">
{samples.length > 0
? t('chat.runningStatus.tokenRate', {
- rate: formatRecentOutputTokenRate(history.peak),
+ rate: approximate(formatRecentOutputTokenRate(history.peak), Boolean(responseSpeed)),
})
: '—'}
</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.json
index 51dda2b07e..b495339abc 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -10060,8 +10060,23 @@
"observedPeak": "Peak",
"tokenRate": "{{rate}} tok/s",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "Latest generation interval. Excludes tools and waits.",
- "tokenCount": "{{tokens}} tok"
+ "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",
+ "noRecentSample": "No new output received",
+ "generationPaused": "Generation paused",
+ "responsePending": "Waiting for response",
+ "responseGenerating": "Generating",
+ "toolRunning": "Running tool"
},
"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.json
index 852d612831..fc102e23b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -10038,8 +10038,23 @@
"observedPeak": "ピーク",
"tokenRate": "{{rate}} tok/s",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "直近の生成区間の速度。ツール実行と待機は除きます。",
- "tokenCount": "{{tokens}} tok"
+ "tokenRateDescription": "リアルタイム速度とピークは推定値です。応答後に実使用量で補正し、ツール実行とリクエスト待機は除外します。",
+ "tokenCount": "{{tokens}} tok",
+ "estimatedValue": "約{{value}}",
+ "estimatedTokenRate": "約{{rate}} tok/s",
+ "responseWaiting": "待機 {{seconds}}秒",
+ "waitSeconds": "{{seconds}}秒",
+ "firstResponse": "初回応答",
+ "streamWait": "ストリーム内待機",
+ "turnWaitDescription": "ローカルでの実行開始から最初のテキスト、思考、ツール内容まで。ネットワーク遅延とは異なります。",
+ "streamWaitDescription": "SDK ストリーム開始から最初のコンテンツまで。それ以前のリクエスト待機は測定できません。",
+ "lastGeneration": "前回の生成",
+ "finalAverage": "最終平均",
+ "noRecentSample": "新しい出力を受信していません",
+ "generationPaused": "生成を一時停止",
+ "responsePending": "応答待ち",
+ "responseGenerating": "生成中",
+ "toolRunning": "ツール実行中"
},
"shareImage": {
"entry": "画像として共有",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1e29a12a95..f656816b64 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -10038,8 +10038,23 @@
"observedPeak": "최고",
"tokenRate": "{{rate}} tok/s",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "최근 생성 구간의 속도. 도구 실행과 대기는 제외합니다.",
- "tokenCount": "{{tokens}} tok"
+ "tokenRateDescription": "실시간 속도와 최고 속도는 추정값입니다. 응답 후 실제 사용량으로 보정하며 도구 실행과 요청 대기는 제외합니다.",
+ "tokenCount": "{{tokens}} tok",
+ "estimatedValue": "약 {{value}}",
+ "estimatedTokenRate": "약 {{rate}} tok/s",
+ "responseWaiting": "대기 {{seconds}}초",
+ "waitSeconds": "{{seconds}}초",
+ "firstResponse": "첫 응답",
+ "streamWait": "스트림 내 대기",
+ "turnWaitDescription": "로컬 실행 시작부터 첫 텍스트, 사고 또는 도구 내용까지의 시간입니다. 네트워크 지연과는 다릅니다.",
+ "streamWaitDescription": "SDK 스트림 시작부터 첫 콘텐츠까지의 시간입니다. 그 이전의 요청 대기는 측정할 수 없습니다.",
+ "lastGeneration": "지난 생성",
+ "finalAverage": "최종 평균",
+ "noRecentSample": "새 출력을 받지 못함",
+ "generationPaused": "생성 일시 중지",
+ "responsePending": "응답 대기 중",
+ "responseGenerating": "생성 중",
+ "toolRunning": "도구 실행 중"
},
"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.json
index 147c087cb6..0bf8a00444 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -10038,8 +10038,23 @@
"observedPeak": "峰值",
"tokenRate": "{{rate}} tok/s",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "最近一段生成速度,不含工具执行与等待。",
- "tokenCount": "{{tokens}} tok"
+ "tokenRateDescription": "实时速度和峰值为估算。响应结束后用真实用量校准;不计工具执行和请求等待。",
+ "tokenCount": "{{tokens}} tok",
+ "estimatedValue": "约{{value}}",
+ "estimatedTokenRate": "约{{rate}} tok/s",
+ "responseWaiting": "等待 {{seconds}}秒",
+ "waitSeconds": "{{seconds}}秒",
+ "firstResponse": "首响应",
+ "streamWait": "流内等待",
+ "turnWaitDescription": "从本地收到引擎开始到首个文字、思考或工具内容,不等同于网络延迟。",
+ "streamWaitDescription": "从 SDK 流开始到首个内容块,之前的请求等待不可测。",
+ "lastGeneration": "上次生成",
+ "finalAverage": "最终平均",
+ "noRecentSample": "暂未收到新输出",
+ "generationPaused": "生成暂停",
+ "responsePending": "等待响应",
+ "responseGenerating": "正在生成",
+ "toolRunning": "执行工具中"
},
"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.json
index 006e8aca54..58b539c08b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -10037,8 +10037,23 @@
"observedPeak": "峰值",
"tokenRate": "{{rate}} tok/s",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "最近一段生成速度,不含工具執行與等待。",
- "tokenCount": "{{tokens}} tok"
+ "tokenRateDescription": "即時速度和峰值為估算。回應結束後以實際用量校準;不計工具執行和請求等待。",
+ "tokenCount": "{{tokens}} tok",
+ "estimatedValue": "約{{value}}",
+ "estimatedTokenRate": "約{{rate}} tok/s",
+ "responseWaiting": "等待 {{seconds}}秒",
+ "waitSeconds": "{{seconds}}秒",
+ "firstResponse": "首回應",
+ "streamWait": "流內等待",
+ "turnWaitDescription": "從本機收到引擎開始到首個文字、思考或工具內容,不等同於網路延遲。",
+ "streamWaitDescription": "從 SDK 串流開始到首個內容區塊,之前的請求等待無法測量。",
+ "lastGeneration": "上次生成",
+ "finalAverage": "最終平均",
+ "noRecentSample": "暫未收到新輸出",
+ "generationPaused": "生成暫停",
+ "responsePending": "等待回應",
+ "responseGenerating": "正在生成",
+ "toolRunning": "執行工具中"
},
"shareImage": {
"entry": "分享為圖片",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 2b04bd9042..a6da1d41c9 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -1,3 +1,4 @@
+import { readResponseSpeedSnapshot, stopResponseSpeed, 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';
@@ -730,6 +731,7 @@ 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;
@@ -6285,6 +6287,8 @@ export function handleStreamEvent(
turnStoppedByUser: state.turnStoppedByUser || terminalCancelled,
agentStatus: {
...state.agentStatus,
+ responseSpeed: stopResponseSpeed(state.agentStatus.responseSpeed),
+ generationActive: false,
isRunning: false,
startedAt: null,
},
@@ -6512,6 +6516,8 @@ export function handleStreamEvent(
// 初始 "Let's go" 文案上 shimmer 闪个不停(done 路径有同样的复位)。
agentStatus: {
...state.agentStatus,
+ responseSpeed: stopResponseSpeed(state.agentStatus.responseSpeed),
+ generationActive: false,
isRunning: false,
startedAt: null,
},
@@ -7024,6 +7030,8 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatState
turnStoppedByUser: false,
agentStatus: {
...finalized.agentStatus,
+ responseSpeed: stopResponseSpeed(finalized.agentStatus.responseSpeed),
+ generationActive: false,
isRunning: false,
startedAt: null,
},
@@ -7036,7 +7044,7 @@ function mergeLiveGenerationStatus(
previous: AgentStatus,
): Pick<
AgentStatus,
- 'outputTokens' | 'generationDurationMs' | 'generationActive' | 'generationReliable'
+ 'outputTokens' | 'generationDurationMs' | 'generationActive' | 'generationReliable' | 'responseSpeed'
> {
// Turn start drops leftover metrics from the previous turn, then keeps any
// live fields carried by this same status. A reconnect-shaped first event
@@ -7044,6 +7052,7 @@ function mergeLiveGenerationStatus(
// zero the values that just arrived.
const baseline = isTurnStart
? {
+ responseSpeed: undefined,
outputTokens: 0,
generationDurationMs: 0,
generationActive: false,
@@ -7057,6 +7066,9 @@ function mergeLiveGenerationStatus(
typeof update.generationReliable === 'boolean';
if (!hasLiveFields) {
return {
+ responseSpeed: update.isRunning
+ ? readResponseSpeedSnapshot(update.responseSpeed, Date.now()) ?? baseline.responseSpeed
+ : stopResponseSpeed(readResponseSpeedSnapshot(update.responseSpeed, Date.now()) ?? baseline.responseSpeed),
outputTokens: baseline.outputTokens,
generationDurationMs: baseline.generationDurationMs,
generationActive: update.isRunning ? baseline.generationActive : false,
@@ -7064,6 +7076,9 @@ function mergeLiveGenerationStatus(
};
}
const merged = {
+ responseSpeed: update.isRunning
+ ? readResponseSpeedSnapshot(update.responseSpeed, Date.now()) ?? baseline.responseSpeed
+ : stopResponseSpeed(readResponseSpeedSnapshot(update.responseSpeed, Date.now()) ?? baseline.responseSpeed),
outputTokens:
typeof update.outputTokens === 'number' ? update.outputTokens : baseline.outputTokens,
generationDurationMs:
@@ -15598,6 +15613,8 @@ function stopSession(
costUsd: s.agentStatus.costUsd,
contextTokens: s.agentStatus.contextTokens,
contextWindow: s.agentStatus.contextWindow,
+ responseSpeed: stopResponseSpeed(s.agentStatus.responseSpeed),
+ 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.ts
index 498926b558..1121c8b98f 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -804,6 +804,7 @@ 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].tsx
index 1e8e8efae9..9cd9efc5f9 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,3 +1,5 @@
+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';
@@ -10133,7 +10135,7 @@ export default function SessionScreen() {
紧接着消息落屏时这条又要重排一次。等有内容了再显示活动条。
判据必须带 messageCount:syncingWhileEmpty 只要 loading 就为真,而收口后
还会再来几轮 load(实测日志),只看它会让已有消息的会话反复熄灭活动条。 */}
- {!companionChat && showComposerActivity && !(syncingWhileEmpty && !hasRenderedMessages) ? (
+ {!companionChat && (showComposerActivity || remoteSessionRunStatus.responseSpeed?.phase === 'complete') && !(syncingWhileEmpty && !hasRenderedMessages) ? (
<View
style={[
styles.composerActivityFrame,
@@ -10151,6 +10153,7 @@ export default function SessionScreen() {
streaming={isSessionStreaming}
tokenUsage={composerActivityTokenUsage}
outputTokens={remoteSessionRunStatus.outputTokens}
+ responseSpeed={remoteSessionRunStatus.responseSpeed}
generationDurationMs={remoteSessionRunStatus.generationDurationMs}
generationReliable={remoteSessionRunStatus.generationReliable}
generationActive={remoteSessionRunStatus.generationActive}
@@ -12029,6 +12032,7 @@ function ComposerActivityStatus({
rateStartedAt = startedAt,
streaming = false,
tokenUsage,
+ responseSpeed,
outputTokens,
generationDurationMs,
generationReliable,
@@ -12043,6 +12047,7 @@ function ComposerActivityStatus({
rateStartedAt?: number | null;
streaming?: boolean;
tokenUsage: number;
+ responseSpeed?: ResponseSpeedSnapshot;
outputTokens: number;
generationDurationMs: number;
generationReliable: boolean;
@@ -12070,7 +12075,7 @@ 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 rateHistory = useRunningTokenRateHistory({
+ const legacyRateHistory = useRunningTokenRateHistory({
sessionKey,
startedAt: samplerStartedAt,
outputTokens,
@@ -12079,22 +12084,30 @@ function ComposerActivityStatus({
streaming,
});
- if (!visible) return null;
+ const rateHistory = responseSpeed ? responseSpeedHistory(responseSpeed) : legacyRateHistory;
+ const completedSpeed = !visible && responseSpeed?.phase === 'complete';
+ const speedActivity = responseSpeed ? responseSpeedActivity(responseSpeed) : null;
+ if (!visible && !completedSpeed) return null;
- const elapsedText = formatComposerActivityElapsed(elapsed);
+ const elapsedText = completedSpeed
+ ? t('session.screen.lastGeneration')
+ : 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.noRecentSample') : 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
- && generationReliable
+ const canShowRateDetails = !showElapsedOnly && (Boolean(responseSpeed) || (generationReliable
&& outputTokens > 0
&& Number.isFinite(outputTokens)
&& Number.isFinite(generationDurationMs)
- && generationDurationMs > 0;
+ && generationDurationMs > 0));
const rateText = rateValue
- ? t('session.screen.tokenRate', { rate: rateValue })
+ ? responseSpeed && (responseSpeed.phase !== 'complete' || responseSpeed.estimated)
+ ? t('session.screen.estimatedTokenRate', { rate: rateValue })
+ : t('session.screen.tokenRate', { rate: rateValue })
: null;
const showUsageMeta = !showElapsedOnly && (Boolean(rateText) || tokenUsage > 0);
// iOS pills share the header/composer edge glass; Android's blur is too weak
@@ -12139,7 +12152,11 @@ function ComposerActivityStatus({
? 'session.screen.rateLimitRetrying'
: 'session.screen.networkReconnecting',
)
- : t('session.screen.thinking');
+ : t(speedActivity === 'waiting' ? 'session.screen.responsePending'
+ : speedActivity === 'quiet' ? 'session.screen.noRecentSample'
+ : speedActivity === 'tool' ? 'session.screen.toolRunning'
+ : speedActivity === 'paused' ? 'session.screen.generationPaused'
+ : speedActivity === 'generating' ? 'session.screen.responseGenerating' : 'session.screen.thinking');
return (
<View
@@ -12147,7 +12164,7 @@ function ComposerActivityStatus({
style={styles.composerActivityStatus}
testID="session.composerActivityStatus"
>
- <View pointerEvents="none" style={[styles.composerActivityPill, styles.composerActivityPrimary]}>
+ {visible && <View pointerEvents="none" style={[styles.composerActivityPill, styles.composerActivityPrimary]}>
<BlurBackdrop intensity={FLOATING_CHROME_BLUR_INTENSITY} overlayColor={pillOverlayColor} style={styles.composerActivityPillBackdrop} />
<Sparkles color={colors.statusAccent} size={iconSize.sm} strokeWidth={iconStroke.regular} />
<Text numberOfLines={1} style={styles.composerActivityStatusText}>{activityText}</Text>
@@ -12156,8 +12173,9 @@ function ComposerActivityStatus({
{reconnectAttempt.attempt}/{reconnectAttempt.maxAttempts}
</Text>
) : null}
- </View>
+ </View>}
<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.ts
index 1bcb634e66..a25184cb76 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -6691,3 +6691,27 @@ 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 });
+});
diff --git a/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx b/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx
index 2f90f5e316..b1d0aca26d 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('50');
- expect(report({ generationDurationMs: 14_000 })).toBe('50');
+ expect(host.textContent).toBe('waiting');
+ expect(report({ generationDurationMs: 14_000 })).toBe('waiting');
expect(report({ outputTokens: 1140 })).toBe('20');
});
-it('expires stale samples after 60 seconds and resumes on a new paired report', () => {
+it('expires stale samples after the one-second observation window and resumes on a new paired report', () => {
report();
report({ outputTokens: 1100, generationDurationMs: 12_000 });
- act(() => vi.advanceTimersByTime(59_999));
+ act(() => vi.advanceTimersByTime(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.tsx
index 27f846d0b1..e9bc469b41 100644
--- a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx
+++ b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx
@@ -15,6 +15,9 @@ 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";
@@ -193,6 +196,8 @@ const bindings = {
iconStroke: {},
RunningTokenRatePopover,
useRunningTokenRateHistory,
+ responseSpeedActivity,
+ responseSpeedHistory,
formatComposerActivityElapsed: () => "1s",
formatComposerActivityTokenCount: () => "100",
};
@@ -201,6 +206,40 @@ const ActivityStatus = new Function(
`${compiledStatus}; return ComposerActivityStatus;`,
)(...Object.values(bindings));
+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.noRecentSample');
+ 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) => {
@@ -527,7 +566,7 @@ it("uses paired generation samples, expires recent speed, and isolates a differe
expect(card()!.textContent).toContain("50");
expect(card()!.textContent).toContain("75 tok/s");
expect(card()!.textContent).toContain("100 tok/s");
- await act(async () => vi.advanceTimersByTime(60_000));
+ await act(async () => vi.advanceTimersByTime(1_000));
expect(card()!.textContent).toContain("—");
await render({ key: "other", sessionKey: "account/device/other" });
expect(card()).toBeNull();
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index e2925550d9..a2ac960067 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("t('session.screen.thinking')");
+ expect(source).toContain("'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.json
index 4c17e76904..eb8c4a2ddd 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -185,7 +185,7 @@
"outputTotal": "Output",
"observedPeak": "Peak",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "Latest generation interval. Excludes tools and waits.",
+ "tokenRateDescription": "Streaming rates and peaks are estimates. Response totals are calibrated with reported usage. Tool execution and request waits are excluded.",
"networkReconnecting": "Reconnecting…",
"modelBusyRetrying": "Model service busy — retrying…",
"rateLimitRetrying": "Request rate limited — retrying…",
@@ -266,7 +266,22 @@
"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"
+ "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",
+ "noRecentSample": "No new output received",
+ "generationPaused": "Generation paused",
+ "responsePending": "Waiting for response",
+ "responseGenerating": "Generating",
+ "toolRunning": "Running tool"
},
"shareImage": {
"title": "Share Conversation",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 5944c39959..2af7c9db4c 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -185,7 +185,7 @@
"outputTotal": "累計出力",
"observedPeak": "ピーク",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "直近の生成区間の速度。ツール実行と待機は除きます。",
+ "tokenRateDescription": "リアルタイム速度とピークは推定値です。応答後に実使用量で補正し、ツール実行とリクエスト待機は除外します。",
"networkReconnecting": "再接続中…",
"modelBusyRetrying": "モデルサービスが混雑、再試行中…",
"rateLimitRetrying": "リクエストがレート制限されました。再試行中…",
@@ -266,7 +266,22 @@
"forkConfirmTitle": "ここから新しいセッションを始めますか?",
"forkConfirmDescription": "この時点の会話コンテキストを使って、独立した新しいセッションを作成します。元のセッションは変更されず、以後のメッセージは互いに影響しません。",
"forkConfirm": "新しいセッションを始める",
- "forkCancel": "キャンセル"
+ "forkCancel": "キャンセル",
+ "estimatedValue": "約{{value}}",
+ "estimatedTokenRate": "約{{rate}} tok/s",
+ "responseWaiting": "待機 {{seconds}}秒",
+ "waitSeconds": "{{seconds}}秒",
+ "firstResponse": "初回応答",
+ "streamWait": "ストリーム内待機",
+ "turnWaitDescription": "ローカルでの実行開始から最初のテキスト、思考、ツール内容まで。ネットワーク遅延とは異なります。",
+ "streamWaitDescription": "SDK ストリーム開始から最初のコンテンツまで。それ以前のリクエスト待機は測定できません。",
+ "lastGeneration": "前回の生成",
+ "finalAverage": "最終平均",
+ "noRecentSample": "新しい出力を受信していません",
+ "generationPaused": "生成を一時停止",
+ "responsePending": "応答待ち",
+ "responseGenerating": "生成中",
+ "toolRunning": "ツール実行中"
},
"shareImage": {
"title": "会話を共有",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 30c14e6b47..36e9968924 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -181,7 +181,7 @@
"outputTotal": "누적 출력",
"observedPeak": "최고",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "최근 생성 구간의 속도. 도구 실행과 대기는 제외합니다.",
+ "tokenRateDescription": "실시간 속도와 최고 속도는 추정값입니다. 응답 후 실제 사용량으로 보정하며 도구 실행과 요청 대기는 제외합니다.",
"networkReconnecting": "다시 연결하는 중…",
"modelBusyRetrying": "모델 서비스 혼잡, 다시 시도 중…",
"rateLimitRetrying": "요청이 속도 제한에 걸렸습니다. 다시 시도 중…",
@@ -262,7 +262,22 @@
"forkConfirmTitle": "여기서 새 세션을 시작할까요?",
"forkConfirmDescription": "이 지점의 대화 맥락을 사용해 독립된 새 세션을 만듭니다. 원래 세션은 변경되지 않으며, 이후 두 세션의 메시지는 서로에게 영향을 주지 않습니다.",
"forkConfirm": "새 세션 시작",
- "forkCancel": "취소"
+ "forkCancel": "취소",
+ "estimatedValue": "약 {{value}}",
+ "estimatedTokenRate": "약 {{rate}} tok/s",
+ "responseWaiting": "대기 {{seconds}}초",
+ "waitSeconds": "{{seconds}}초",
+ "firstResponse": "첫 응답",
+ "streamWait": "스트림 내 대기",
+ "turnWaitDescription": "로컬 실행 시작부터 첫 텍스트, 사고 또는 도구 내용까지의 시간입니다. 네트워크 지연과는 다릅니다.",
+ "streamWaitDescription": "SDK 스트림 시작부터 첫 콘텐츠까지의 시간입니다. 그 이전의 요청 대기는 측정할 수 없습니다.",
+ "lastGeneration": "지난 생성",
+ "finalAverage": "최종 평균",
+ "noRecentSample": "새 출력을 받지 못함",
+ "generationPaused": "생성 일시 중지",
+ "responsePending": "응답 대기 중",
+ "responseGenerating": "생성 중",
+ "toolRunning": "도구 실행 중"
},
"shareImage": {
"title": "대화 공유",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 02dfd6de28..8e7a48becc 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -181,7 +181,7 @@
"outputTotal": "累计输出",
"observedPeak": "峰值",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "最近一段生成速度,不含工具执行与等待。",
+ "tokenRateDescription": "实时速度和峰值为估算。响应结束后用真实用量校准;不计工具执行和请求等待。",
"networkReconnecting": "正在重新连接…",
"modelBusyRetrying": "模型服务繁忙,正在重试…",
"rateLimitRetrying": "请求受到限流,正在重试…",
@@ -262,7 +262,22 @@
"forkConfirmTitle": "从这里开启一个新任务?",
"forkConfirmDescription": "系统会根据这里的对话上下文创建一个独立的新任务。原任务不会改变,之后两边的消息互不影响。",
"forkConfirm": "开启新任务",
- "forkCancel": "取消"
+ "forkCancel": "取消",
+ "estimatedValue": "约{{value}}",
+ "estimatedTokenRate": "约{{rate}} tok/s",
+ "responseWaiting": "等待 {{seconds}}秒",
+ "waitSeconds": "{{seconds}}秒",
+ "firstResponse": "首响应",
+ "streamWait": "流内等待",
+ "turnWaitDescription": "从本地收到引擎开始到首个文字、思考或工具内容,不等同于网络延迟。",
+ "streamWaitDescription": "从 SDK 流开始到首个内容块,之前的请求等待不可测。",
+ "lastGeneration": "上次生成",
+ "finalAverage": "最终平均",
+ "noRecentSample": "暂未收到新输出",
+ "generationPaused": "生成暂停",
+ "responsePending": "等待响应",
+ "responseGenerating": "正在生成",
+ "toolRunning": "执行工具中"
},
"shareImage": {
"title": "分享对话",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index a85e293e87..f3e144d196 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -185,7 +185,7 @@
"outputTotal": "累計輸出",
"observedPeak": "峰值",
"tokenRateUnit": "tok/s",
- "tokenRateDescription": "最近一段生成速度,不含工具執行與等待。",
+ "tokenRateDescription": "即時速度和峰值為估算。回應結束後以實際用量校準;不計工具執行和請求等待。",
"networkReconnecting": "正在重新連線…",
"modelBusyRetrying": "模型服務繁忙,正在重試…",
"rateLimitRetrying": "請求受到限流,正在重試…",
@@ -266,7 +266,22 @@
"forkConfirmTitle": "從這裡開啟一個新任務?",
"forkConfirmDescription": "系統會根據這裡的對話上下文建立一個獨立的新任務。原任務不會改變,之後兩邊的訊息互不影響。",
"forkConfirm": "開啟新任務",
- "forkCancel": "取消"
+ "forkCancel": "取消",
+ "estimatedValue": "約{{value}}",
+ "estimatedTokenRate": "約{{rate}} tok/s",
+ "responseWaiting": "等待 {{seconds}}秒",
+ "waitSeconds": "{{seconds}}秒",
+ "firstResponse": "首回應",
+ "streamWait": "流內等待",
+ "turnWaitDescription": "從本機收到引擎開始到首個文字、思考或工具內容,不等同於網路延遲。",
+ "streamWaitDescription": "從 SDK 串流開始到首個內容區塊,之前的請求等待無法測量。",
+ "lastGeneration": "上次生成",
+ "finalAverage": "最終平均",
+ "noRecentSample": "暫未收到新輸出",
+ "generationPaused": "生成暫停",
+ "responsePending": "等待回應",
+ "responseGenerating": "正在生成",
+ "toolRunning": "執行工具中"
},
"shareImage": {
"title": "分享對話",
diff --git a/apps/mobile/src/session/RunningTokenRatePopover.tsx b/apps/mobile/src/session/RunningTokenRatePopover.tsx
index 9b948c1cf2..cd68cbbf14 100644
--- a/apps/mobile/src/session/RunningTokenRatePopover.tsx
+++ b/apps/mobile/src/session/RunningTokenRatePopover.tsx
@@ -1,3 +1,5 @@
+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,
@@ -46,6 +48,7 @@ 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,
@@ -57,6 +60,7 @@ export function RunningTokenRatePopover({
enabled = true,
history: managedHistory,
}: {
+ responseSpeed?: ResponseSpeedSnapshot;
sessionKey: string;
startedAt: number | null;
outputTokens: number;
@@ -197,7 +201,7 @@ export function RunningTokenRatePopover({
: emptyRateHistory(null);
});
useEffect(() => {
- if (managedHistory) return;
+ if (managedHistory || responseSpeed) return;
setInternalHistory((previous) =>
recordRunningTokenRate(previous, {
startedAt,
@@ -208,6 +212,7 @@ export function RunningTokenRatePopover({
);
}, [
managedHistory,
+ responseSpeed,
startedAt,
outputTokens,
generationDurationMs,
@@ -220,29 +225,30 @@ export function RunningTokenRatePopover({
}, [managedHistory, sessionKey, internalHistory]);
const [now, setNow] = useState(Date.now);
useEffect(() => {
- if (history.latestSampleAt === undefined) return;
+ const sampledAt = responseSpeed?.sampledAt ?? history.latestSampleAt;
+ if (sampledAt === undefined || responseSpeed?.phase === 'complete') return;
setNow(Date.now());
const timer = setTimeout(
() => setNow(Date.now()),
- Math.max(0, history.latestSampleAt + RATE_SAMPLE_FRESH_MS - Date.now()),
+ Math.max(0, sampledAt + RATE_SAMPLE_FRESH_MS - Date.now()),
);
return () => clearTimeout(timer);
- }, [history.latestSampleAt]);
+ }, [history.latestSampleAt, responseSpeed]);
// 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 =
+ const recent = responseSpeed ? responseSpeedHistory(responseSpeed, Math.max(now, Date.now())).latestRate :
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 =
+ const average = responseSpeed ? responseSpeed.averageRate :
generationReliable && generationDurationMs > 0 && outputTokens > 0
? (outputTokens * 1000) / generationDurationMs
: null;
- const samples = history.samples;
+ const samples = responseSpeed?.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));
@@ -258,6 +264,10 @@ 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 = (
<View
pointerEvents={mode === "held" ? "none" : "auto"}
@@ -297,10 +307,14 @@ export function RunningTokenRatePopover({
<View style={styles.top}>
<View style={styles.metric}>
<Text ref={cardFocusTarget} style={styles.label}>
- {t("session.screen.currentRate")}
+ {t(activity === 'complete' ? 'session.screen.finalAverage'
+ : activity === 'waiting' ? 'session.screen.responsePending'
+ : activity === 'tool' ? 'session.screen.toolRunning'
+ : activity === 'paused' ? 'session.screen.generationPaused'
+ : activity === 'quiet' ? 'session.screen.noRecentSample' : 'session.screen.currentRate')}
</Text>
<Text style={styles.value}>
- {formatTokenRate(recent)}{" "}
+ {recent === null ? '—' : approximate(formatTokenRate(recent), Boolean(responseSpeed) && (responseSpeed?.phase !== 'complete' || responseSpeed.estimated))}{" "}
<Text style={styles.label}>
{t("session.screen.tokenRateUnit")}
</Text>
@@ -341,17 +355,15 @@ export function RunningTokenRatePopover({
</View>
<View style={styles.top}>
{[
- ["averageRate", rateText(average)],
+ ["averageRate", approximate(rateText(average), responseSpeed?.estimated ?? false)],
[
"outputTotal",
t("session.screen.tokenCount", {
tokens:
- outputTokens >= 1000
- ? `${(outputTokens / 1000).toFixed(1)}k`
- : outputTokens,
+ approximate(displayedOutput >= 1000 ? `${(displayedOutput / 1000).toFixed(1)}k` : displayedOutput, responseSpeed?.estimated ?? false),
}),
],
- ["observedPeak", rateText(samples.length ? history.peak : null)],
+ ["observedPeak", approximate(rateText(samples.length ? Math.max(...samples.map(sample => sample.rate)) : null), Boolean(responseSpeed))],
].map(([key, value]) => (
<View style={styles.metric} key={key}>
<Text style={styles.label}>{t(`session.screen.${key}`)}</Text>
@@ -359,6 +371,12 @@ 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.ts
index 74eeff6159..d91f573a11 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -1,3 +1,4 @@
+import { readResponseSpeedSnapshot, stopResponseSpeed, type ResponseSpeedSnapshot } from '@cindy/maker-shared/usage-format';
import { normalizeTaskTags, reconcileTaskTags } from '@cindy/maker-shared';
import {
createContext,
@@ -148,6 +149,7 @@ export interface RemoteSessionRunStatus {
status: string;
tokenUsage: number;
outputTokens: number;
+ responseSpeed?: ResponseSpeedSnapshot;
generationDurationMs: number;
generationActive: boolean;
generationReliable: boolean;
@@ -5016,6 +5018,7 @@ export const remoteSessionStore = {
status: rawStatus ?? current.status,
tokenUsage,
outputTokens,
+ responseSpeed: readResponseSpeedSnapshot(data?.responseSpeed, Date.now()) ?? (isTurnStart ? undefined : current.responseSpeed),
generationDurationMs,
generationActive,
generationReliable,
@@ -5596,6 +5599,7 @@ function clearLiveGenerationOnWideRunStart(
return {
...next,
outputTokens: 0,
+ responseSpeed: undefined,
generationDurationMs: 0,
generationActive: false,
generationReliable: true,
@@ -5616,6 +5620,9 @@ 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/docs/dev-rules/assets/response-speed-completed-dark.png b/docs/dev-rules/assets/response-speed-completed-dark.png
new file mode 100644
index 0000000000..d0c3296727
Binary files /dev/null and b/docs/dev-rules/assets/response-speed-completed-dark.png differ
diff --git a/docs/dev-rules/assets/response-speed-completed-light.png b/docs/dev-rules/assets/response-speed-completed-light.png
new file mode 100644
index 0000000000..311432a012
Binary files /dev/null and b/docs/dev-rules/assets/response-speed-completed-light.png differ
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 3af39e087f..679ca0eeb3 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,14 @@
> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+## 回复速度快照
+
+既有 maker status 可选携带 `responseSpeed`(等待边界、估算计数、最近/平均速度与最多
+60 个采样点);仅用于显示,不参与费用或上下文计数。新客户端校验该字段,旧主机省略时
+沿用原 usage 路径,旧客户端忽略新增字段。无需服务端更新、新通道、权限或数据库 migration。
+终态真实 output 与生成 duration 的匹配沿现有消息用量记录处理。详见
+[`response-speed.md`](response-speed.md)。
+
## 任务列表提前同步聊天正文
同账号控制端声明 `session-list-messages-v1` 后,`sessions` 订阅同时接收普通用户/助手
diff --git a/docs/dev-rules/response-speed.md b/docs/dev-rules/response-speed.md
new file mode 100644
index 0000000000..db507acb0b
--- /dev/null
+++ b/docs/dev-rules/response-speed.md
@@ -0,0 +1,59 @@
+# 回复速度测量与展示
+
+速度是展示投影,计费、缓存命中与上下文容量仍由引擎真实 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 显示「首响应」。
+排队发生在引擎开始前,不进入等待或生成速度。
+
+生成计时从内容开始,到响应结束或工具/审批暂停;工具结束后要等到下一次内容才恢复。
+Pi 重试关闭失败片段,下一请求重新等待;每轮重新清空测量。零 usage 是有效零;缺少 usage
+则保留估算。仅结束事件有 output、没有可观测流,或检测到挂起/时钟异常时不提供 TPS。
+
+## 实时与终态
+
+- 字符加权估计避免把一个传输片段当一个精确 token。它跨分片可加,但仍不是 tokenizer。
+- 最近 1 秒滑窗,Pi/Claude 最多每 250ms 推进;Codex沿用 500ms 状态节流。
+ 窗口最多 256 个聚合点,图表最多 60 个采样点,不保留文本。
+- 实时速率、峰值及未校准输出标「约」。真实 usage 到达后校准该响应的曲线及输出;
+ 完成时显示真实输出除以已观测生成时间的最终平均。校准后的曲线和峰值仍是估计分配。
+- 工具期间不冒充正在生成,当前速度为空;Pi 的 tool_execution、Codex 的配对 item 执行边界显示「执行工具中」,不能从参数流推出执行已开始。Claude 缺少同等执行事件时只标「生成暂停」;并行模型 delta 优先显示实际生成。下一请求重新显示等待响应。静默超过观测窗口显示「暂未收到新输出」;不把没有可见内容当真实零输出。远端快照的时间戳在接收端
+ 归一为本地观测时间,避免用两台机器的绝对时钟差延长等待或抹掉当前速度。
+- 停止/终态错误可能没有最后一份 usage,冻结最后观测并保留估算标识。
+- 原速度入口在完成后保留「上次生成」,点击/键盘可重开详情;不依赖 hover 或先 pin,
+ 不固定几秒后隐藏。下一轮用本轮等待替换,切换任务不把别的任务的数据搬过来。
+
+## 回看与持久化
+
+最新快照留在任务的进程内状态,切换任务或组件重新挂载可以回看;图表不写数据库。
+应用/Renderer 重载后首响应和曲线不恢复。已有消息用量记录继续保存真实 output 与经过
+计数匹配检查的生成 duration,支持历史最终平均 TPS;缺失或计数不匹配时省略 TPS。
+不增加数据库 schema、migration 或首响应持久字段。
+
+## 兼容与验证
+
+`UsageSnapshot.responseSpeed` 是既有 status 的可选增量字段:旧主机缺省,新界面使用原
+usage 算法;旧客户端忽略新字段。无新 IPC channel、服务端协议版本或移动端原生指纹。
+
+事件序列验证见 `response-speed.test.ts`、`response-speed-adapters.test.ts`;
+两端组件/任务状态验证覆盖工具暂停、完成保留、下一轮、停止、任务切换与旧主机兼容。
+真实设备与离线受控事件截图必须分别记录,不把离线结果声称为真实模型吞吐。
+
+## 组件验收画面
+
+真实状态栏和速度卡,使用离线受控事件(2 秒首响应、300 输出、4 秒生成),并非真实模型
+吞吐测量。两图分别加载完整 Cindy Light / Dark 主题;完成超过旧淡出时间后仍可点击查看。
+
+![完成后的速度入口和详情(浅色)](assets/response-speed-completed-light.png)
+
+![完成后的速度入口和详情(深色)](assets/response-speed-completed-dark.png)
diff --git a/packages/maker-core/src/agents/claude-code/generation-timing.ts b/packages/maker-core/src/agents/claude-code/generation-timing.ts
index ec16960afb..8003013381 100644
--- a/packages/maker-core/src/agents/claude-code/generation-timing.ts
+++ b/packages/maker-core/src/agents/claude-code/generation-timing.ts
@@ -1,7 +1,9 @@
+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. */
@@ -31,6 +33,7 @@ export interface ClaudeGenerationState {
export function newClaudeGenerationState(): ClaudeGenerationState {
return {
+ responseSpeed: new ResponseSpeedTracker('stream'),
startedAt: null,
durationMs: 0,
outputDurationMs: 0,
@@ -57,6 +60,7 @@ 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;
}
@@ -84,6 +88,7 @@ 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();
@@ -114,6 +119,7 @@ export function beginClaudeGenerationAtRequestStart(
): void {
for (const pauseId of state.pendingToolIds) state.settledPauseIds.add(pauseId);
state.pendingToolIds.clear();
+ state.responseSpeed.beginRequest(startedAt);
beginClaudeGeneration(state, startedAt);
}
@@ -129,6 +135,7 @@ 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.ts
index 9f55212e04..17e73a72d9 100644
--- a/packages/maker-core/src/agents/claude-code/translator.ts
+++ b/packages/maker-core/src/agents/claude-code/translator.ts
@@ -39,7 +39,6 @@ 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,
@@ -343,6 +342,7 @@ 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,
@@ -1689,6 +1689,18 @@ 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') {
@@ -2196,6 +2208,7 @@ function handleResult(
resultUsage != null && segmentTotals.outputTokens === resultUsage.outputTokens,
);
const liveGeneration = ctx.rt.generation;
+ liveGeneration.responseSpeed.finish();
const endSnapshot = ctx.tracker.endTurn(
resultUsage
? {
@@ -2477,6 +2490,7 @@ function handleResult(
data: {
status: 'Done',
...attachLiveGeneration(endSnapshot, {
+ responseSpeed: liveGeneration.responseSpeed.snapshot(),
outputTokens: liveTurnOutput,
durationMs: liveGeneration.outputDurationMs,
openStartedAt: null,
@@ -2500,6 +2514,7 @@ function handleResult(
: msg;
const resultWithUsageSegments = {
...safeResult,
+ responseSpeed: liveGeneration.responseSpeed.snapshot(),
usageSegments: turnUsageSegments,
usageSegmentsComplete,
modelUsageCumulativeStartsAtZero: ctx.modelUsageCumulativeStartsAtZero?.() === true,
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 4038e338cb..0970e5c839 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -127,6 +127,7 @@ 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';
@@ -168,7 +169,6 @@ import {
translateErrorNotification,
translateItemNotification,
beginCodexGenerationTurn,
- codexGenerationDurationMs,
finalizeCodexGenerationTurn,
pauseCodexGeneration,
resetCodexGenerationTiming,
@@ -3692,6 +3692,7 @@ 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,
@@ -10895,7 +10896,10 @@ assertRouteCurrent();
const realTurnUsage = usageTracker.getTurnUsage();
const realTurnUsageSegments = usageTracker.getTurnUsageSegments();
finalizeCodexGenerationTurn(translatorRt, turn.id);
- const generationDurationMs = codexGenerationDurationMs(translatorRt);
+ translatorRt.responseSpeed.finish(realTurnUsageSegments.length > 0 ? realTurnUsage.output : undefined);
+ if (!translatorRt.generationTimingReliable) translatorRt.responseSpeed.invalidate();
+ const speedSnapshot = translatorRt.responseSpeed.snapshot();
+ const generationDurationMs = calibratedResponseDuration(speedSnapshot, realTurnUsage.output);
const codexDoneUsage = {
promptTokens: realTurnUsage.input,
completionTokens: realTurnUsage.output,
@@ -10906,12 +10910,9 @@ assertRouteCurrent();
cachedTokens: realTurnUsage.cacheRead,
cacheCreationTokens: realTurnUsage.cacheCreate,
segments: realTurnUsageSegments,
- // With usage, exclude post-output finalization. Without usage, retain
- // the measured duration metadata (zero output cannot produce a rate).
+ // Persist TPS timing only when observed stream time pairs with real turn output.
...(generationDurationMs !== undefined ? {
- durationMs: realTurnUsage.output > 0
- ? translatorRt.generationOutputDurationMs || undefined
- : generationDurationMs,
+ durationMs: generationDurationMs,
} : {}),
...(typeof turn.durationMs === 'number' && Number.isFinite(turn.durationMs)
? { turnDurationMs: turn.durationMs }
@@ -11115,6 +11116,7 @@ assertRouteCurrent();
data: {
status: 'Done',
...attachLiveGeneration(endSnap, {
+ responseSpeed: translatorRt.responseSpeed.snapshot(),
outputTokens: realTurnUsage.output,
durationMs: translatorRt.generationOutputDurationMs,
openStartedAt: null,
@@ -12482,6 +12484,7 @@ assertRouteCurrent();
producedOutputTurnIds.add(params.turnId);
noteRecoveryModelWork(params.turnId);
translateAgentMessageDelta(params, eventQueue, { rt: translatorRt, log });
+ maybePushUsageRefresh();
},
turnPlanUpdated: (params) => {
if (enqueueIfBufferedTurn(params.turnId, () => handlers.turnPlanUpdated?.(params))) return;
@@ -12497,6 +12500,7 @@ assertRouteCurrent();
producedOutputTurnIds.add(params.turnId);
noteRecoveryModelWork(params.turnId);
translateReasoningSummaryTextDelta(params, eventQueue, { rt: translatorRt, log });
+ maybePushUsageRefresh();
},
reasoningSummaryPartAdded: (params) => {
// thinking 流同样算产出(与非缓冲路径一致)。
@@ -12513,6 +12517,7 @@ assertRouteCurrent();
producedOutputTurnIds.add(params.turnId);
noteRecoveryModelWork(params.turnId);
translateReasoningTextDelta(params, eventQueue, { rt: translatorRt, log });
+ maybePushUsageRefresh();
},
accountRateLimitsUpdated: (params) =>
translateAccountRateLimitsUpdated(params, eventQueue, { rt: translatorRt, log }),
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index 9f6739c6d8..0808959a29 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -1,3 +1,4 @@
+import { ResponseSpeedTracker } from '../shared/response-speed.js';
/**
* Codex app-server v2 Notification → maker-core 语义 AgentEvent 翻译器。
*
@@ -80,6 +81,7 @@ 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;
generationStartedAt: number | null;
/** Tool/approval boundaries currently owning the turn. Generation resumes after all finish. */
generationPendingToolIds: Set<string>;
@@ -130,6 +132,7 @@ export function newCodexRuntimeState(): CodexRuntimeState {
reasoningStartedAt: new Map(),
reasoningTextLen: new Map(),
itemTextLen: new Map(),
+ responseSpeed: new ResponseSpeedTracker(),
generationStartedAt: null,
generationPendingToolIds: new Set(),
generationDurationMs: 0,
@@ -166,6 +169,7 @@ 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;
}
@@ -212,6 +216,7 @@ 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;
@@ -257,6 +262,7 @@ 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);
}
@@ -324,10 +330,12 @@ 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);
}
@@ -392,6 +400,9 @@ export function translateItemNotification(
ctx.log.warn('item missing type field', { phase, itemKeys: Object.keys(item) });
return;
}
+ if (phase === 'started' && (itemType === 'reasoning' || CODEX_GENERATION_PAUSE_ITEM_TYPES.has(itemType))) {
+ ctx.rt.responseSpeed.content();
+ }
noteCodexGenerationBoundary(
ctx.rt,
phase,
@@ -1106,6 +1117,7 @@ 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,
@@ -1321,6 +1333,7 @@ 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);
@@ -1355,6 +1368,7 @@ 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.ts
index 03614642d5..39facb16dd 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
@@ -1421,7 +1421,8 @@ describe('pi translator', () => {
cacheCreateTokens: 3,
}),
]);
- expect(usage.durationMs).toBeGreaterThanOrEqual(1_200);
+ // Completed-only frames cannot prove when streaming began.
+ expect(usage.durationMs).toBeUndefined();
expect(usage.turnDurationMs).toBeGreaterThanOrEqual(0);
// 快照累计 input+output。
expect(usageSnapshotOf(ctx).tokenUsage).toBe(120);
@@ -1571,7 +1572,7 @@ describe('pi translator', () => {
disposePiTranslateContext(ctx);
});
- it('reads Pi v0.83 generation duration from timestamp with a live heartbeat', () => {
+ it('keeps native timestamp timing but omits TPS without a first-content observation', () => {
const ctx = createPiTranslateContext(noopLogger);
const { queue, events } = makeQueue();
const timestamp = Date.now() - 1_200;
@@ -1592,8 +1593,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).toEqual(expect.any(Number));
- expect(usage.durationMs).toBeGreaterThanOrEqual(1_200);
+ expect(usage.durationMs).toBeUndefined();
+ expect(usageSnapshotOf(ctx).generationDurationMs).toBeGreaterThanOrEqual(1_200);
expect(usage.turnDurationMs).toEqual(expect.any(Number));
});
diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.ts
index 35b4d2b246..0a4c6fb8ad 100644
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@ -1,3 +1,5 @@
+import { calibratedResponseDuration } from '@cindy/maker-shared/usage-format';
+import { ResponseSpeedTracker } from '../shared/response-speed.js';
/**
* pi RPC 事件 → AgentEvent 翻译层。
*
@@ -160,6 +162,7 @@ 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;
@@ -224,6 +227,7 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {
finalAssistantText: '',
finalAssistantStopReason: null,
turnWallClockStartedAt: 0,
+ responseSpeed: new ResponseSpeedTracker(),
generationDurationMs: 0,
generationOpenAt: 0,
generationTimingReliable: true,
@@ -332,6 +336,7 @@ 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;
}
@@ -356,6 +361,7 @@ 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,
@@ -676,6 +682,7 @@ 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);
@@ -695,6 +702,9 @@ 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;
@@ -709,6 +719,10 @@ 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;
}
@@ -716,6 +730,7 @@ 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?.({
@@ -788,6 +803,7 @@ 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);
@@ -881,6 +897,7 @@ export function translatePiEvent(
case 'tool_execution_end': {
const toolUseId = String(event.toolCallId ?? '');
+ ctx.responseSpeed.toolEnded(toolUseId);
const isError = event.isError === true;
const rawText = toolResultFullText(event.result);
const toolName = String(
@@ -948,6 +965,7 @@ 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;
@@ -956,6 +974,7 @@ 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,
@@ -963,11 +982,10 @@ export function translatePiEvent(
cacheCreationTokens: ctx.turnCacheWrite,
segments: ctx.turnUsageSegments.map((segment) => ({ ...segment })),
segmentsComplete: ctx.turnUsageSegmentsComplete,
- // 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 }
+ // Persist observed streaming time only after provider usage calibration.
+ // Tools, request waiting and completed-only output have no TPS denominator.
+ ...(speedDuration !== undefined
+ ? { durationMs: speedDuration }
: {}),
...(ctx.turnWallClockStartedAt > 0
? { turnDurationMs: Math.max(0, Date.now() - ctx.turnWallClockStartedAt) }
@@ -1036,6 +1054,7 @@ 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.
diff --git a/packages/maker-core/src/agents/shared/live-generation-snapshot.ts b/packages/maker-core/src/agents/shared/live-generation-snapshot.ts
index be8802c8a0..542f0e1435 100644
--- a/packages/maker-core/src/agents/shared/live-generation-snapshot.ts
+++ b/packages/maker-core/src/agents/shared/live-generation-snapshot.ts
@@ -2,6 +2,7 @@ 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;
@@ -26,7 +27,7 @@ export function attachLiveGeneration(
typeof timing.outputTokens === 'number' && Number.isFinite(timing.outputTokens)
? Math.max(0, timing.outputTokens)
: 0;
- const next: UsageSnapshot = { ...snapshot, outputTokens };
+ const next: UsageSnapshot = { ...snapshot, outputTokens, ...(timing.responseSpeed ? { responseSpeed: timing.responseSpeed } : {}) };
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.ts
new file mode 100644
index 0000000000..08a89e9d3a
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/response-speed-adapters.test.ts
@@ -0,0 +1,107 @@
+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(usageSnapshotOf(ctx).responseSpeed?.toolActive).toBe(false);
+ send(17_000, { type: 'message_start', message: { role: 'toolResult' } });
+ expect(usageSnapshotOf(ctx).responseSpeed?.phase).toBe('paused');
+ 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);
+});
diff --git a/packages/maker-core/src/agents/shared/response-speed.test.ts b/packages/maker-core/src/agents/shared/response-speed.test.ts
new file mode 100644
index 0000000000..74b0e890e7
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/response-speed.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it } from 'vitest';
+import { 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('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 ', '世', '界 ', '👋']));
+ 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));
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/response-speed.ts b/packages/maker-core/src/agents/shared/response-speed.ts
new file mode 100644
index 0000000000..116bcdadf2
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/response-speed.ts
@@ -0,0 +1,186 @@
+import type { ResponseSpeedSnapshot, RateSample } from '@cindy/maker-shared/usage-format';
+
+const WINDOW_MS = 1_000;
+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 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.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.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.codePointAt(0)! > 0xff ? 0.67 : 0.25;
+ this.units += units;
+ this.reported = null;
+ this.lastDeltaAt = now;
+ this.window.push({ time: now, 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;
+ }
+
+ toolStarted(id: string): void { if (id) this.tools.add(id); }
+ toolEnded(id: string): void { 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';
+ }
+
+ 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,
+ };
+ }
+
+ 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);
+ // Bound storage even when a provider emits thousands of deltas in one millisecond.
+ if (this.window.length > 256) {
+ const first = this.window.splice(0, this.window.length - 255);
+ this.window.unshift({ time: first.at(-1)!.time, units: first.reduce((sum, p) => sum + p.units, 0) });
+ }
+ }
+ 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.ts
index d2df179d45..eeda14b5c1 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -406,6 +406,7 @@ 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.ts
index c40497e66e..fc38faf2e1 100644
--- a/packages/maker-shared/src/runningTokenRateHistory.ts
+++ b/packages/maker-shared/src/runningTokenRateHistory.ts
@@ -3,6 +3,75 @@ 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;
+}
+
+export function responseSpeedActivity(speed: ResponseSpeedSnapshot, now = Date.now()):
+ 'waiting' | 'generating' | 'quiet' | 'tool' | 'paused' | 'complete' {
+ if (speed.phase === 'complete' || speed.phase === 'waiting') return speed.phase;
+ 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.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.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): ResponseSpeedSnapshot | undefined {
+ if (!speed || speed.phase === 'complete') return speed;
+ return { ...speed, phase: 'complete', recentRate: speed.averageRate,
+ estimated: speed.estimated || speed.phase === 'generating' || speed.phase === 'waiting' };
+}
+
+/** 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.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;
@@ -11,7 +80,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 = 60_000;
+export const RATE_SAMPLE_FRESH_MS = 1_000;
export interface RateHistory {
startedAt: number | null;