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(desktop): 展示跨轮速度历史与可常驻浮窗 (#4271)

Dash2451b101e569
diff --git a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
index 41149187ea..eb7086cb42 100644
--- a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
+++ b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
@@ -54,7 +54,9 @@ describe('controlled banner placement', () => {
expect(sessionViewSource).toContain(
'const controlledBannerMaxWidth = `min(${inputHalfWidth}, ${CONTROLLED_BANNER_MAX_WIDTH}px)`;',
);
- expect(sessionViewSource).toContain('if (isHidden && !rightLeadingSlot) return null;');
+ expect(sessionViewSource).toContain(
+ 'if (!rightLeadingSlot && (suppressContent || (isHidden && !ratePanelPinned))) return null;',
+ );
expect(controlledBannerSource).toContain("placement?: 'floating' | 'inline' | 'composer';");
expect(controlledBannerSource).toContain(
'className="pointer-events-auto flex min-w-0 max-w-full shrink justify-end"',
diff --git a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
new file mode 100644
index 0000000000..a89ea2c3a3
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
@@ -0,0 +1,141 @@
+// @vitest-environment jsdom
+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 ts from 'typescript';
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ RunningTokenRatePopover,
+ useRunningTokenRateHistory,
+} from '@/features/cc-agent/RunningTokenRatePopover';
+import {
+ formatRecentOutputTokenRate,
+ formatRunningTokenCount,
+ resolveRunningUsageMeta,
+} from '@/features/cc-agent/lib/runningTokenUsage';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+// Execute the actual status bar without loading the entire session view's IPC/store graph.
+const source = readFileSync(
+ resolve(__dirname, '../features/cc-agent/CCAgentSessionView.tsx'),
+ 'utf8',
+);
+const ast = ts.createSourceFile(
+ 'view.tsx',
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+);
+const component = ast.statements.find(
+ (node) => ts.isFunctionDeclaration(node) && node.name?.text === 'RunningStatusBar',
+);
+if (!component) throw new Error('RunningStatusBar not found');
+const compiled = ts.transpileModule(component.getText(ast), {
+ compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },
+}).outputText;
+const Icon = () => null;
+const deps = {
+ React,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ useTranslation: () => ({ t: (key: string) => key }),
+ useReducedMotion: () => true,
+ useAnimatedNumber: (value: number) => value,
+ localizeAgentStatus: (status: string) => status,
+ cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),
+ Check: Icon,
+ Activity: Icon,
+ Layers: Icon,
+ Sparkles: Icon,
+ Square: Icon,
+ ArrowDown: Icon,
+ STATUS_BAR_FADE_MS: 400,
+ RunningTokenRatePopover,
+ useRunningTokenRateHistory,
+ formatRecentOutputTokenRate,
+ formatRunningTokenCount,
+ resolveRunningUsageMeta,
+};
+const RunningStatusBar = new Function(
+ 'deps',
+ `const {${Object.keys(deps).join(',')}} = deps; ${compiled}; return RunningStatusBar;`,
+)(deps) as React.ComponentType<{
+ visible: boolean;
+ suppressContent?: boolean;
+ rightLeadingSlot?: React.ReactNode;
+ status: string;
+ startedAt: number;
+ tokenUsage: number;
+ outputTokens: number;
+ generationDurationMs: number;
+ generationReliable?: boolean;
+}>;
+
+afterEach(cleanup);
+
+it('opens measured zero history and restores fallback across reliability and turn changes', () => {
+ const props = {
+ visible: true,
+ status: 'Thinking',
+ startedAt: 1,
+ tokenUsage: 100,
+ outputTokens: 0,
+ generationDurationMs: 1000,
+ generationReliable: true,
+ };
+ const { container, rerender } = render(<RunningStatusBar {...props} />);
+ const trigger = () => container.querySelector('[data-running-status-meta] button');
+ expect(trigger()).toBeNull();
+ rerender(<RunningStatusBar {...props} generationDurationMs={2000} />);
+ expect(trigger()).not.toBeNull();
+ fireEvent.click(trigger()!);
+ expect(screen.getByRole('dialog').textContent).not.toContain('—');
+ fireEvent.click(screen.getByRole('button', { name: 'titleBar.close' }));
+ rerender(<RunningStatusBar {...props} generationDurationMs={2000} generationReliable={false} />);
+ expect(trigger()).toBeNull();
+ rerender(<RunningStatusBar {...props} startedAt={2} />);
+ expect(trigger()).toBeNull();
+ rerender(<RunningStatusBar {...props} startedAt={2} generationDurationMs={2000} />);
+ expect(trigger()).not.toBeNull();
+});
+
+it.each([true, false])(
+ 'plan review preserves the collapsed indicator and suppresses a pinned panel (running=%s)',
+ (visible) => {
+ const props = {
+ visible: true,
+ status: 'Thinking',
+ startedAt: Date.now(),
+ tokenUsage: 100,
+ outputTokens: 100,
+ generationDurationMs: 1000,
+ };
+ const indicator = <button aria-label="Controlled session">Device</button>;
+ const { container, rerender } = render(
+ <RunningStatusBar {...props} rightLeadingSlot={indicator} />,
+ );
+ fireEvent.click(container.querySelector('[data-running-status-meta] button')!);
+ expect(screen.getByRole('button', { name: 'titleBar.close' })).toBeTruthy();
+
+ rerender(
+ <RunningStatusBar
+ {...props}
+ visible={visible}
+ suppressContent
+ rightLeadingSlot={indicator}
+ />,
+ );
+ expect(screen.getByRole('button', { name: 'Controlled session' })).toBeTruthy();
+ expect(container.querySelector('[data-running-status-meta]')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'titleBar.close' })).toBeNull();
+
+ // Explicit suppression without an independent indicator leaves no row behind.
+ rerender(<RunningStatusBar {...props} visible={visible} suppressContent />);
+ expect(container.childElementCount).toBe(0);
+ },
+);
diff --git a/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts b/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts
new file mode 100644
index 0000000000..42da50a915
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from 'vitest';
+import {
+ clearRateHistoryCache,
+ emptyRateHistory,
+ loadCachedRateHistory,
+ recordRunningTokenRate,
+ saveCachedRateHistory,
+} from '@/features/cc-agent/lib/runningTokenRateHistory';
+
+const input = { startedAt: 1, outputTokens: 0, generationDurationMs: 0, generationReliable: true };
+const begin = () => recordRunningTokenRate(emptyRateHistory(null), input);
+
+describe('running speed history', () => {
+ it('uses paired deltas rather than the cumulative turn average', () => {
+ const first = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 100,
+ generationDurationMs: 1000,
+ });
+ const nextInput = { ...input, outputTokens: 150, generationDurationMs: 2000 };
+ const next = recordRunningTokenRate(first, nextInput);
+ expect(next.samples.map((sample) => sample.rate)).toEqual([100, 50]);
+ expect(next.peak).toBe(100);
+ expect(recordRunningTokenRate(next, nextInput)).toBe(next);
+ });
+
+ it('does not call a reconnect cumulative total the latest speed', () => {
+ const first = recordRunningTokenRate(emptyRateHistory(null), {
+ ...input,
+ outputTokens: 1000,
+ generationDurationMs: 10000,
+ });
+ expect(first.samples).toEqual([]);
+ const next = recordRunningTokenRate(first, {
+ ...input,
+ outputTokens: 1100,
+ generationDurationMs: 12000,
+ });
+ expect(next.samples[0].rate).toBe(50);
+ });
+
+ it('uses sparse real generation intervals without counting wall-clock waits', () => {
+ const first = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 1000,
+ generationDurationMs: 10000,
+ });
+ const next = recordRunningTokenRate(first, {
+ ...input,
+ outputTokens: 1600,
+ generationDurationMs: 30000,
+ });
+ expect(next.samples.at(-1)?.rate).toBe(30);
+ });
+
+ it('re-baselines on turn changes, counters resetting, or unreliable timing', () => {
+ const first = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 100,
+ generationDurationMs: 1000,
+ });
+ const newTurn = recordRunningTokenRate(first, { ...input, startedAt: 2 });
+ expect(newTurn.samples).toEqual(first.samples);
+ expect(newTurn.latestRate).toBeNull();
+ expect(
+ recordRunningTokenRate(first, { ...input, outputTokens: 50, generationDurationMs: 500 })
+ .samples,
+ ).toEqual(first.samples);
+ expect(
+ recordRunningTokenRate(first, { ...input, generationReliable: false }).baseline,
+ ).toBeNull();
+ expect(recordRunningTokenRate(first, { ...input, generationDurationMs: NaN }).samples).toEqual(
+ first.samples,
+ );
+ });
+
+ it('does not turn a count correction with frozen time into a spike', () => {
+ const first = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 100,
+ generationDurationMs: 1000,
+ });
+ const correction = recordRunningTokenRate(first, {
+ ...input,
+ outputTokens: 150,
+ generationDurationMs: 1000,
+ });
+ expect(correction.samples).toEqual(first.samples);
+ const next = recordRunningTokenRate(correction, {
+ ...input,
+ outputTokens: 200,
+ generationDurationMs: 2000,
+ });
+ expect(next.samples.at(-1)?.rate).toBe(50);
+ });
+
+ it('bounds samples and excludes evicted samples from the observed peak', () => {
+ let history = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 1000,
+ generationDurationMs: 1000,
+ });
+ for (let n = 2; n <= 200; n++) {
+ history = recordRunningTokenRate(history, {
+ ...input,
+ outputTokens: 1000 + n,
+ generationDurationMs: n * 1000,
+ });
+ }
+ expect(history.samples).toHaveLength(60);
+ expect(history.peak).toBe(1);
+ expect(history.samples[0].durationMs).toBe(141000);
+ });
+});
+
+it('records final usage and appends the next turn on a continuous generation timeline', () => {
+ const active = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 100,
+ generationDurationMs: 1000,
+ });
+ const terminal = recordRunningTokenRate(active, {
+ ...input,
+ startedAt: null,
+ outputTokens: 150,
+ generationDurationMs: 2000,
+ });
+ expect(terminal.startedAt).toBe(1);
+ expect(terminal.samples.map((sample) => sample.rate)).toEqual([100, 50]);
+ expect(terminal.peak).toBe(100);
+ const newTurn = recordRunningTokenRate(terminal, { ...input, startedAt: 2 });
+ expect(newTurn.samples).toEqual(terminal.samples);
+ expect(newTurn.latestRate).toBeNull();
+ const next = recordRunningTokenRate(newTurn, {
+ ...input,
+ startedAt: 2,
+ outputTokens: 20,
+ generationDurationMs: 500,
+ });
+ expect(next.samples.map((sample) => sample.rate)).toEqual([100, 50, 40]);
+ expect(next.samples.map((sample) => sample.durationMs)).toEqual([1000, 2000, 2500]);
+ expect(next.latestRate).toBe(40);
+});
+
+it('retains the chart while hidden or unreliable, then measures only new paired reports', () => {
+ const active = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 100,
+ generationDurationMs: 1000,
+ });
+ const hidden = recordRunningTokenRate(active, {
+ ...input,
+ startedAt: null,
+ generationReliable: false,
+ });
+ expect(hidden.samples).toEqual(active.samples);
+ expect(hidden.latestRate).toBeNull();
+ const resumed = recordRunningTokenRate(hidden, {
+ ...input,
+ outputTokens: 500,
+ generationDurationMs: 10000,
+ });
+ expect(resumed.samples).toEqual(active.samples);
+ const next = recordRunningTokenRate(resumed, {
+ ...input,
+ outputTokens: 550,
+ generationDurationMs: 11000,
+ });
+ expect(next.samples.map((sample) => sample.rate)).toEqual([100, 50]);
+ expect(next.samples.map((sample) => sample.durationMs)).toEqual([1000, 2000]);
+});
+
+describe('per-session speed history cache', () => {
+ it('round-trips a history with samples and keeps the latest entry warm', () => {
+ clearRateHistoryCache();
+ saveCachedRateHistory('s1', emptyRateHistory(null));
+ expect(loadCachedRateHistory('s1')).toBeNull();
+ const history = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 100,
+ generationDurationMs: 1000,
+ });
+ saveCachedRateHistory('s1', history);
+ const restored = loadCachedRateHistory('s1');
+ expect(restored?.samples.map((sample) => sample.rate)).toEqual([100]);
+ expect(restored?.baseline).toEqual(history.baseline);
+ });
+
+ it('evicts the least recently used session beyond the cap', () => {
+ clearRateHistoryCache();
+ const history = recordRunningTokenRate(begin(), {
+ ...input,
+ outputTokens: 100,
+ generationDurationMs: 1000,
+ });
+ for (let n = 0; n < 20; n++) saveCachedRateHistory(`cap-${n}`, history);
+ // 读 s0 让它变成最近使用,下一个新会话应淘汰 s1 而不是 s0。
+ expect(loadCachedRateHistory('cap-0')).not.toBeNull();
+ saveCachedRateHistory('cap-20', history);
+ expect(loadCachedRateHistory('cap-1')).toBeNull();
+ expect(loadCachedRateHistory('cap-0')).not.toBeNull();
+ expect(loadCachedRateHistory('cap-20')).not.toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx b/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx
new file mode 100644
index 0000000000..044ddf5a72
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx
@@ -0,0 +1,354 @@
+// @vitest-environment jsdom
+import React from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ RunningTokenRatePopover,
+ useRunningTokenRateHistory,
+} from '@/features/cc-agent/RunningTokenRatePopover';
+import {
+ clearRateHistoryCache,
+ emptyRateHistory,
+ recordRunningTokenRate,
+} from '@/features/cc-agent/lib/runningTokenRateHistory';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { rate?: string }) =>
+ key === 'chat.runningStatus.tokenRate' ? `${options?.rate} tok/s` : key,
+ }),
+}));
+afterEach(cleanup);
+
+it('distinguishes an unobserved peak from measured zero throughput', () => {
+ const props = {
+ elapsedText: '1s',
+ rate: null,
+ rateText: null,
+ averageRate: null,
+ outputTokens: 0,
+ };
+ let history = emptyRateHistory(1);
+ const { rerender } = render(<RunningTokenRatePopover {...props} history={history} />);
+ fireEvent.click(screen.getByRole('button'));
+ const peak = () => screen.getByText('chat.runningStatus.observedPeak').nextElementSibling;
+ expect(peak()?.textContent).toBe('—');
+ for (const generationDurationMs of [0, 1000]) {
+ history = recordRunningTokenRate(history, {
+ startedAt: 1,
+ outputTokens: 0,
+ generationDurationMs,
+ generationReliable: true,
+ });
+ }
+ rerender(<RunningTokenRatePopover {...props} history={history} />);
+ expect(peak()?.textContent).toBe('0 tok/s');
+});
+
+it('keeps pinned history while its trigger falls back to tokens or elapsed-only', () => {
+ const props = {
+ elapsedText: '10s',
+ rate: '100',
+ rateText: '100 tok/s',
+ averageRate: '100',
+ outputTokens: 1000,
+ history: {
+ startedAt: 1,
+ baseline: null,
+ peak: 100,
+ latestRate: 100,
+ samples: [{ durationMs: 1000, outputTokens: 100, rate: 100 }],
+ },
+ };
+ const { rerender } = render(<RunningTokenRatePopover {...props} />);
+ const trigger = screen.getByRole('button');
+ fireEvent.click(trigger);
+ const dialog = screen.getByRole('dialog');
+ rerender(
+ <RunningTokenRatePopover
+ {...props}
+ rate={null}
+ averageRate={null}
+ rateText="1.2k tok"
+ isTokenCount
+ />,
+ );
+ expect(screen.getByRole('dialog')).toBe(dialog);
+ expect(trigger.textContent).toContain('1.2k tok');
+ expect(trigger.getAttribute('aria-label')).not.toContain('currentRate');
+ expect(screen.getByRole('img').querySelector('circle')).toBeTruthy();
+ rerender(<RunningTokenRatePopover {...props} rateText={null} />);
+ expect(trigger.textContent).toBe('10s');
+ expect(screen.getByRole('dialog')).toBe(dialog);
+ rerender(<RunningTokenRatePopover {...props} />);
+ expect(trigger.textContent).toContain('100 tok/s');
+ expect(screen.getByRole('dialog')).toBe(dialog);
+});
+
+it('pins the card on click and dismisses with Escape, returning focus to the speed', async () => {
+ render(
+ <RunningTokenRatePopover
+ elapsedText="10s"
+ rate="100"
+ rateText="100 tok/s"
+ averageRate="110"
+ outputTokens={1000}
+ history={{
+ startedAt: 1,
+ baseline: { durationMs: 10000, outputTokens: 1000 },
+ peak: 120,
+ latestRate: 100,
+ samples: [
+ { durationMs: 1000, outputTokens: 120, rate: 120 },
+ { durationMs: 10000, outputTokens: 1000, rate: 100 },
+ ],
+ }}
+ />,
+ );
+ const trigger = screen.getByRole('button');
+ const elapsed = screen.getByText('10s');
+ expect(elapsed.closest('button')).toBe(trigger);
+ fireEvent.pointerMove(elapsed, { pointerType: 'mouse' });
+ await screen.findByRole('tooltip');
+ fireEvent.click(elapsed);
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(screen.getByRole('img').querySelectorAll('path')).toHaveLength(3);
+ fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' });
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(trigger));
+});
+
+it.each(['Escape', 'close'] as const)(
+ 'clears hover after pinned dismissal via %s and allows a fresh hover',
+ async (dismissal) => {
+ render(
+ <RunningTokenRatePopover
+ elapsedText="10s"
+ rate="100"
+ rateText="100 tok/s"
+ averageRate="110"
+ outputTokens={1000}
+ history={{ startedAt: 1, baseline: null, peak: 100, latestRate: null, samples: [] }}
+ />,
+ );
+ const trigger = screen.getByRole('button');
+ fireEvent.pointerMove(trigger, { pointerType: 'mouse' });
+ await screen.findByRole('tooltip');
+ fireEvent.click(trigger);
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ fireEvent.pointerLeave(trigger);
+ fireEvent.pointerMove(trigger, { pointerType: 'mouse' });
+ await act(() => new Promise((resolve) => setTimeout(resolve, 550)));
+ expect(screen.queryByRole('tooltip')).toBeNull();
+ if (dismissal === 'Escape') {
+ fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' });
+ } else {
+ fireEvent.click(screen.getByRole('button', { name: 'titleBar.close' }));
+ }
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(screen.queryByRole('tooltip')).toBeNull();
+ expect(screen.getByRole('button')).toBe(trigger);
+ fireEvent.pointerLeave(trigger);
+ fireEvent.pointerEnter(trigger);
+ fireEvent.pointerMove(trigger, { pointerType: 'mouse' });
+ await screen.findByRole('tooltip');
+ },
+);
+
+it('keeps the pinned card across turns while awaiting a fresh rate', async () => {
+ function Harness({
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ }: {
+ startedAt: number | null;
+ outputTokens: number;
+ generationDurationMs: number;
+ }) {
+ const history = useRunningTokenRateHistory({
+ sessionKey: null,
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ generationReliable: true,
+ });
+ return (
+ <RunningTokenRatePopover
+ elapsedText="10s"
+ rate={history.latestRate === null ? null : String(history.latestRate)}
+ rateText="speed"
+ averageRate="75"
+ outputTokens={outputTokens}
+ history={history}
+ />
+ );
+ }
+ const { rerender } = render(<Harness startedAt={1} outputTokens={0} generationDurationMs={0} />);
+ rerender(<Harness startedAt={1} outputTokens={100} generationDurationMs={1000} />);
+ const trigger = screen.getByRole('button');
+ fireEvent.click(trigger);
+ const dialog = screen.getByRole('dialog');
+ rerender(<Harness startedAt={null} outputTokens={150} generationDurationMs={2000} />);
+ expect(screen.getByRole('dialog')).toBe(dialog);
+ expect(screen.getByRole('button', { name: /speed/ })).toBe(trigger);
+ expect(dialog.textContent).toContain('50');
+ expect(screen.getByRole('img').querySelectorAll('path')).toHaveLength(3);
+ rerender(<Harness startedAt={2} outputTokens={0} generationDurationMs={0} />);
+ expect(screen.getByRole('dialog')).toBe(dialog);
+ const chart = screen.getByRole('img');
+ expect(chart.querySelectorAll('path')).toHaveLength(3);
+ expect(screen.getByRole('dialog').textContent).toContain('—');
+ const previousLine = chart.querySelectorAll('path')[2].getAttribute('d');
+ rerender(<Harness startedAt={2} outputTokens={20} generationDurationMs={500} />);
+ expect(screen.getByRole('dialog').textContent).toContain('40');
+ const nextLine = screen.getByRole('img').querySelectorAll('path')[2].getAttribute('d');
+ expect(nextLine).not.toBe(previousLine);
+ expect(nextLine?.match(/[ML]/g)).toHaveLength(3);
+});
+
+it('keeps a clicked panel open through outside clicks, focus changes and repeated trigger clicks', async () => {
+ const onPinnedChange = vi.fn();
+ render(
+ <>
+ <input aria-label="composer" />
+ <RunningTokenRatePopover
+ elapsedText="10s"
+ rate="100"
+ rateText="100 tok/s"
+ averageRate="110"
+ outputTokens={1000}
+ history={{ startedAt: 1, baseline: null, peak: 0, latestRate: null, samples: [] }}
+ onPinnedChange={onPinnedChange}
+ />
+ </>,
+ );
+ const trigger = screen.getByRole('button');
+ fireEvent.click(trigger);
+ expect(onPinnedChange).toHaveBeenLastCalledWith(true);
+ const dialog = screen.getByRole('dialog');
+ const composer = screen.getByRole('textbox');
+ fireEvent.pointerDown(composer);
+ fireEvent.pointerUp(composer);
+ fireEvent.click(composer);
+ act(() => composer.focus());
+ expect(document.activeElement).toBe(composer);
+ expect(screen.getByRole('dialog')).toBe(dialog);
+ fireEvent.click(trigger);
+ fireEvent.pointerLeave(trigger);
+ expect(screen.getByRole('dialog')).toBe(dialog);
+ expect(screen.queryByRole('tooltip')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'titleBar.close' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(onPinnedChange).toHaveBeenLastCalledWith(false);
+});
+
+it('restores speed history from the per-session cache after remounting', () => {
+ clearRateHistoryCache();
+ function Harness({
+ sessionKey,
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ }: {
+ sessionKey: string | null;
+ startedAt: number | null;
+ outputTokens: number;
+ generationDurationMs: number;
+ }) {
+ const history = useRunningTokenRateHistory({
+ sessionKey,
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ generationReliable: true,
+ });
+ return (
+ <RunningTokenRatePopover
+ elapsedText="10s"
+ rate={history.latestRate === null ? null : String(history.latestRate)}
+ rateText="speed"
+ averageRate={null}
+ outputTokens={outputTokens}
+ history={history}
+ />
+ );
+ }
+ const first = render(
+ <Harness sessionKey="cache-a" startedAt={1} outputTokens={0} generationDurationMs={0} />,
+ );
+ first.rerender(
+ <Harness sessionKey="cache-a" startedAt={1} outputTokens={100} generationDurationMs={1000} />,
+ );
+ first.rerender(
+ <Harness sessionKey="cache-a" startedAt={1} outputTokens={150} generationDurationMs={2000} />,
+ );
+ first.unmount();
+
+ // 切回同一会话:图表从缓存恢复,且恢复的 baseline 能继续算出新的配对速度。
+ const second = render(
+ <Harness sessionKey="cache-a" startedAt={1} outputTokens={200} generationDurationMs={3000} />,
+ );
+ fireEvent.click(screen.getByRole('button'));
+ expect(screen.getByRole('img').querySelectorAll('path')).toHaveLength(3);
+ expect(screen.getByRole('dialog').textContent).toContain('50');
+ second.unmount();
+
+ // 另一个会话没有历史:从零等待,不串会话。
+ const third = render(
+ <Harness sessionKey="cache-b" startedAt={1} outputTokens={0} generationDurationMs={0} />,
+ );
+ fireEvent.click(screen.getByRole('button'));
+ expect(screen.getByRole('img').querySelectorAll('path')).toHaveLength(1);
+ expect(screen.getByRole('dialog').textContent).toContain('—');
+});
+
+it('does not fabricate a rate when restoring an idle session whose next turn finished while away', () => {
+ clearRateHistoryCache();
+ function Harness({
+ sessionKey,
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ }: {
+ sessionKey: string | null;
+ startedAt: number | null;
+ outputTokens: number;
+ generationDurationMs: number;
+ }) {
+ const history = useRunningTokenRateHistory({
+ sessionKey,
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ generationReliable: true,
+ });
+ return (
+ <RunningTokenRatePopover
+ elapsedText="10s"
+ rate={history.latestRate === null ? null : String(history.latestRate)}
+ rateText="speed"
+ averageRate={null}
+ outputTokens={outputTokens}
+ history={history}
+ />
+ );
+ }
+ const first = render(
+ <Harness sessionKey="idle-a" startedAt={1} outputTokens={0} generationDurationMs={0} />,
+ );
+ first.rerender(
+ <Harness sessionKey="idle-a" startedAt={1} outputTokens={100} generationDurationMs={1000} />,
+ );
+ first.unmount();
+
+ // 切离期间会话在后台跑完新一轮;切回时已空闲,store 里是新轮的累计计数。
+ const second = render(
+ <Harness sessionKey="idle-a" startedAt={null} outputTokens={500} generationDurationMs={10000} />,
+ );
+ fireEvent.click(screen.getByRole('button'));
+ // 新轮计数减旧轮 baseline 得出的 44.4 tok/s 是伪造区间,不得追加;
+ // 图表仍只有缓存里的 1 个采样点(仅轴线),最新速度保持最后的真实测量。
+ expect(screen.getByRole('img').querySelectorAll('path')).toHaveLength(1);
+ expect(screen.getByRole('dialog').textContent).not.toContain('44.4');
+ expect(screen.getByRole('dialog').textContent).toContain('100');
+});
diff --git a/apps/desktop/src/renderer/__tests__/runningTokenUsage.test.ts b/apps/desktop/src/renderer/__tests__/runningTokenUsage.test.ts
index 752b1d2666..c46d97c4e1 100644
--- a/apps/desktop/src/renderer/__tests__/runningTokenUsage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/runningTokenUsage.test.ts
@@ -1,3 +1,4 @@
+import { formatRecentOutputTokenRate } from '@/features/cc-agent/lib/runningTokenUsage';
import { describe, expect, it } from 'vitest';
import {
@@ -69,3 +70,13 @@ describe('resolveRunningUsageMeta', () => {
).toEqual({ kind: 'none' });
});
});
+
+it.each([
+ [0.001, '<0.1'],
+ [0.049, '<0.1'],
+ [0.099, '<0.1'],
+ [0.1, '0.1'],
+ [0, '0'],
+] as const)('formats recent and peak rate %s as %s', (rate, expected) => {
+ expect(formatRecentOutputTokenRate(rate)).toBe(expected);
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 2c1ee8e63e..791e26c851 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -234,7 +234,12 @@ import { isRemoteSessionWriteBlocked } from './lib/remoteSessionWriteGuard';
import { getModelById, getDefaultModelForVendor, getModelsForVendor } from '@/lib/modelDefinitions';
import { resolveDisplayContextWindow } from '@/lib/contextWindow';
import { resolveSessionContextWindow } from '../../../shared/sessionContextWindow';
-import { formatRunningTokenCount, resolveRunningUsageMeta } from './lib/runningTokenUsage';
+import {
+ formatRecentOutputTokenRate,
+ formatRunningTokenCount,
+ resolveRunningUsageMeta,
+} from './lib/runningTokenUsage';
+import { RunningTokenRatePopover, useRunningTokenRateHistory } from './RunningTokenRatePopover';
import { matchNavigationCommandName, tryHandleNavigationCommand } from '@/lib/navigationCommands';
import { extractIpcError } from '@/utils/ipcError';
import { listActiveRunsForSession } from '@/features/learn/useLearnRun';
@@ -4724,6 +4729,7 @@ export function CCAgentSessionView({
) : !pendingPlanReview || (hasControlledBanner && controlledBannerCollapsed) ? (
<RunningStatusBar
key={sessionId}
+ sessionKey={sessionId ?? null}
status={composerStatus}
tokenUsage={agentStatus.tokenUsage}
outputTokens={agentStatus.outputTokens ?? 0}
@@ -5565,6 +5571,7 @@ function RunningStatusBar({
onStopBackgroundTasks,
rightLeadingSlot = null,
suppressContent = false,
+ sessionKey = null,
className,
}: {
status: string;
@@ -5605,6 +5612,8 @@ function RunningStatusBar({
rightLeadingSlot?: ReactNode;
/** 交互卡接管 composer 时立即隐藏旧运行文案/token,只保留折叠呼吸灯。 */
suppressContent?: boolean;
+ /** 会话身份:速度历史按它做进程内缓存,切任务再切回图表不清零。 */
+ sessionKey?: string | null;
className?: string;
}) {
const { t } = useTranslation();
@@ -5614,6 +5623,7 @@ function RunningStatusBar({
// component returns null below so the composer does not retain an empty line.
const [showContent, setShowContent] = useState(visible);
const [fading, setFading] = useState(false);
+ const [ratePanelPinned, setRatePanelPinned] = useState(false);
useEffect(() => {
if (visible) {
@@ -5635,7 +5645,7 @@ function RunningStatusBar({
// Local timer (F-SDK-3: render-side setInterval)
useEffect(() => {
if (!startedAt) {
- setElapsed(0);
+ // Keep the last completed turn duration visible while a pinned panel lingers.
return;
}
@@ -5721,24 +5731,35 @@ function RunningStatusBar({
// incrementing number. Rate does not use this: locally ticking the
// denominator would make a paused model look like decaying speed.
const animatedTokens = useAnimatedNumber(tokenUsage, 400);
+ const tokenCountText = t('chat.runningStatus.tokenCount', {
+ tokens: formatRunningTokenCount(animatedTokens),
+ });
+ const rateHistory = useRunningTokenRateHistory({
+ sessionKey,
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ generationReliable:
+ generationReliable &&
+ !sideTaskRunning &&
+ !backgroundTasksRunning &&
+ !workflowWaiting,
+ });
+ const latestRate = rateHistory.latestRate;
const usageMeta = resolveRunningUsageMeta({
outputTokens,
generationDurationMs,
generationReliable,
tokenUsage,
+ latestRate,
});
- const tokenCountText = t('chat.runningStatus.tokenCount', {
- tokens: formatRunningTokenCount(animatedTokens),
- });
- const tokenCountTipText = t('chat.messageActionBar.turnTokens', {
- tokens: formatRunningTokenCount(animatedTokens),
- });
+ const latestRateText = latestRate !== null ? formatRecentOutputTokenRate(latestRate) : null;
const rateText =
- usageMeta.kind === 'rate' ? t('chat.runningStatus.tokenRate', { rate: usageMeta.rate }) : null;
- const rateTipText = [
- t('chat.runningStatus.tokenRateDescription'),
- ...(tokenUsage > 0 ? [tokenCountTipText] : []),
- ].join('\n');
+ !isHidden && usageMeta.kind === 'rate'
+ ? latestRateText !== null
+ ? t('chat.runningStatus.tokenRate', { rate: latestRateText })
+ : t('chat.runningStatus.waitingSample')
+ : null;
// 淡入淡出/隐藏占位样式 —— 同时作用于左(状态)、右(elapsed/tokens)两段。
// visibility:hidden 只隐藏不收高,让 linger / fade 阶段稳定;淡出结束后整个
@@ -5749,9 +5770,17 @@ function RunningStatusBar({
transition: isHidden ? 'none' : `opacity ${STATUS_BAR_FADE_MS}ms ease-out`,
pointerEvents: isHidden ? 'none' : 'auto',
};
+ const showRatePanel =
+ ratePanelPinned ||
+ (!workflowWaiting &&
+ !sideTaskRunning &&
+ !backgroundTasksRunning &&
+ Boolean(rateText) &&
+ usageMeta.kind === 'rate');
+ // A pinned panel keeps its anchor mounted through idle and subsequent turns.
// 空闲后真正收起,不再给输入框上方留下固定空行。overlay 的 ResizeObserver 会在
// DOM 尺寸变化后补齐 MessageStream 的 bottomPadding,因此不靠硬编码高度制造跳变。
- if (isHidden && !rightLeadingSlot) return null;
+ if (!rightLeadingSlot && (suppressContent || (isHidden && !ratePanelPinned))) return null;
// 两段式布局:左(运行状态) / 右(elapsed·tokens)。
// - 左段 min-w-0(可收缩):status 并非短枚举 —— turn-start 文案带用户名(可含中文长句)、
@@ -5810,13 +5839,31 @@ function RunningStatusBar({
走 LLM, 显示残留 token 计数会误导用户以为也耗了 token。 */}
<div className="flex min-w-0 items-center justify-self-end gap-2">
{rightLeadingSlot}
- {!isHidden && (
+ {(!suppressContent && (!isHidden || ratePanelPinned)) && (
<div
data-running-status-meta="true"
className="flex min-w-0 items-center gap-[6px]"
- style={fadeStyle}
- aria-hidden={isHidden}
+ style={ratePanelPinned ? undefined : fadeStyle}
+ aria-hidden={isHidden && !ratePanelPinned}
>
+ {showRatePanel && (
+ <RunningTokenRatePopover
+ elapsedText={elapsedText}
+ rate={latestRateText}
+ rateText={
+ workflowWaiting || sideTaskRunning || backgroundTasksRunning
+ ? null
+ : usageMeta.kind === 'tokens'
+ ? tokenCountText
+ : rateText
+ }
+ isTokenCount={usageMeta.kind === 'tokens'}
+ averageRate={usageMeta.kind === 'rate' ? usageMeta.rate : null}
+ outputTokens={outputTokens}
+ history={rateHistory}
+ onPinnedChange={setRatePanelPinned}
+ />
+ )}
{backgroundTasksRunning ? (
// 后台子任务模式:elapsed 是上一轮 turn 的残留计时、tokens 是残留计数,
// 都不成立 —— 整段换成「全部停止」入口(原横幅唯一操作,横幅已删)。
@@ -5840,7 +5887,7 @@ function RunningStatusBar({
? t('chat.backgroundActivity.stopping')
: t('chat.backgroundActivity.stopAll')}
</button>
- ) : workflowWaiting ? null : (
+ ) : workflowWaiting || showRatePanel ? null : (
<>
<span className="text-13 font-medium text-[var(--status-bar-meta)]">
{elapsedText}
@@ -5850,20 +5897,10 @@ function RunningStatusBar({
<span className="text-13 font-medium text-[var(--status-bar-meta)]">
&middot;
</span>
- {rateText ? (
- <Tip text={rateTipText} side="top" contentClassName="whitespace-pre-line">
- <span className="text-13 font-medium text-[var(--status-bar-meta)]">
- {rateText}
- </span>
- </Tip>
- ) : (
- <>
- <ArrowDown size={13} className="shrink-0 text-[var(--status-bar-meta)]" />
- <span className="text-13 font-medium text-[var(--status-bar-meta)]">
- {tokenCountText}
- </span>
- </>
- )}
+ <ArrowDown size={13} className="shrink-0 text-[var(--status-bar-meta)]" />
+ <span className="text-13 font-medium text-[var(--status-bar-meta)]">
+ {tokenCountText}
+ </span>
</>
)}
</>
diff --git a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx
new file mode 100644
index 0000000000..70c9604e53
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx
@@ -0,0 +1,225 @@
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Activity, ArrowDown, X } from 'lucide-react';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { Tooltip } from '@/components/ui/tooltip';
+import { formatRecentOutputTokenRate, formatRunningTokenCount } from './lib/runningTokenUsage';
+import {
+ emptyRateHistory,
+ loadCachedRateHistory,
+ recordRunningTokenRate,
+ saveCachedRateHistory,
+ type RateHistory,
+} from './lib/runningTokenRateHistory';
+
+export function useRunningTokenRateHistory(input: {
+ /** 会话身份:用于进程内缓存速度历史,切任务再切回不清零(重启应用清零)。 */
+ sessionKey: string | null;
+ startedAt: number | null;
+ outputTokens: number;
+ generationDurationMs: number;
+ generationReliable: boolean;
+}) {
+ const { sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable } = input;
+ // 挂载时从按会话的进程内缓存播种:RunningStatusBar 以 sessionId 为 key,
+ // 切走再切回是全新挂载,历史从缓存恢复而不是从零开始。
+ const [history, setHistory] = useState<RateHistory>(() => {
+ const cached = sessionKey ? loadCachedRateHistory(sessionKey) : null;
+ if (!cached) return emptyRateHistory(null);
+ // 空闲态恢复时必须丢弃 baseline:此时看不到计数属于哪一轮,若会话在
+ // 后台跑完了新一轮,用旧轮 baseline 去减新轮累计计数会伪造区间速度。
+ return startedAt === null ? { ...cached, baseline: null } : cached;
+ });
+ useEffect(() => {
+ setHistory((previous) =>
+ recordRunningTokenRate(previous, {
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ generationReliable,
+ }),
+ );
+ }, [startedAt, outputTokens, generationDurationMs, generationReliable]);
+ useEffect(() => {
+ if (sessionKey) saveCachedRateHistory(sessionKey, history);
+ }, [sessionKey, history]);
+ return startedAt === null || history.startedAt === startedAt
+ ? history
+ : { ...history, startedAt, baseline: null, latestRate: null };
+}
+
+export function RunningTokenRatePopover({
+ elapsedText,
+ rate,
+ rateText,
+ isTokenCount = false,
+ averageRate,
+ outputTokens,
+ history,
+ onPinnedChange,
+}: {
+ elapsedText: string;
+ rate: string | null;
+ rateText: string | null;
+ isTokenCount?: boolean;
+ averageRate: string | null;
+ outputTokens: number;
+ history: RateHistory;
+ onPinnedChange?: (pinned: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const [mode, setMode] = useState<'idle' | 'hover' | 'pinned' | 'dismissed'>('idle');
+ const open = mode === 'pinned';
+ useEffect(() => onPinnedChange?.(open), [open, onPinnedChange]);
+ const samples = history.samples;
+ const firstTime = samples[0]?.durationMs ?? 0;
+ const span = (samples.at(-1)?.durationMs ?? 0) - firstTime;
+ const ceiling = Math.max(1, ...samples.map((sample) => sample.rate));
+ const points = samples.map((sample) => ({
+ x: span > 0 ? 4 + ((sample.durationMs - firstTime) / span) * 108 : 112,
+ y: 44 - (sample.rate / ceiling) * 36,
+ }));
+ const line = points.map((point, index) => `${index ? 'L' : 'M'}${point.x},${point.y}`).join(' ');
+ const last = points.at(-1);
+ const card = (
+ <div
+ aria-description={t('chat.runningStatus.tokenRateDescription')}
+ className="grid grid-cols-[minmax(0,1fr)_128px] gap-x-3 gap-y-3 pr-1"
+ >
+ <div className="contents">
+ <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')}
+ </div>
+ <div className="flex items-baseline gap-1.5 tabular-nums">
+ <span className="text-28 font-medium leading-none">{rate ?? '—'}</span>
+ <span className="text-12 text-[var(--text-secondary)]">
+ {t('chat.runningStatus.tokenRateUnit')}
+ </span>
+ </div>
+ </div>
+ <svg
+ viewBox="0 0 120 48"
+ className="col-start-2 row-start-1 h-12 w-32 self-center text-[var(--text-primary)]"
+ role="img"
+ aria-label={t('chat.runningStatus.rateHistory')}
+ >
+ <path d="M4 44H112" stroke="currentColor" opacity="0.12" />
+ {points.length > 1 && (
+ <>
+ <path d={`${line} L112,44 L${points[0].x},44 Z`} fill="currentColor" opacity="0.08" />
+ <path
+ d={line}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinejoin="round"
+ />
+ </>
+ )}
+ {last && <circle cx={last.x} cy={last.y} r="2.5" fill="currentColor" />}
+ </svg>
+ <dl className="col-span-2 col-start-1 row-start-2 grid grid-cols-3 gap-2 text-12 tabular-nums [&>div]:flex-col [&>div]:items-start [&>div]:gap-1">
+ <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 }) : '—'}
+ </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),
+ })}
+ </dd>
+ </div>
+ <div className="flex items-center gap-2">
+ <dt className="text-[var(--text-secondary)]">{t('chat.runningStatus.observedPeak')}</dt>
+ <dd className="font-medium">
+ {samples.length > 0
+ ? t('chat.runningStatus.tokenRate', {
+ rate: formatRecentOutputTokenRate(history.peak),
+ })
+ : '—'}
+ </dd>
+ </div>
+ </dl>
+ </div>
+ </div>
+ );
+ const surface =
+ 'w-[320px] max-w-[calc(100vw-32px)] rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3 text-[var(--text-primary)] shadow-[var(--shadow-menu)]';
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ if (next) setMode('pinned');
+ }}
+ >
+ <Tooltip.Provider>
+ <Tooltip.Root
+ open={mode === 'hover'}
+ onOpenChange={(next) =>
+ setMode((current) =>
+ current === 'pinned' || current === 'dismissed' ? current : next ? 'hover' : 'idle',
+ )
+ }
+ >
+ <PopoverTrigger asChild>
+ <Tooltip.Trigger asChild>
+ <button
+ type="button"
+ onPointerEnter={() =>
+ setMode((current) => (current === 'dismissed' ? 'idle' : current))
+ }
+ onBlur={() => setMode((current) => (current === 'dismissed' ? 'idle' : current))}
+ className="inline-flex min-h-6 min-w-6 items-center justify-center gap-[6px] whitespace-nowrap rounded-full px-1 text-13 font-medium tabular-nums text-[var(--status-bar-meta)] hover:bg-[var(--button-secondary-hover)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--text-secondary)]"
+ aria-label={
+ rateText
+ ? `${elapsedText} · ${isTokenCount ? rateText : `${t('chat.runningStatus.currentRate')}: ${rateText}`}`
+ : elapsedText
+ }
+ >
+ <span>{elapsedText}</span>
+ {rateText && (
+ <>
+ <span aria-hidden="true">&middot;</span>
+ {isTokenCount && <ArrowDown size={13} aria-hidden="true" />}
+ <span>{rateText}</span>
+ </>
+ )}
+ </button>
+ </Tooltip.Trigger>
+ </PopoverTrigger>
+ <Tooltip.Content side="top" className={`${surface} break-normal`}>
+ {card}
+ </Tooltip.Content>
+ </Tooltip.Root>
+ </Tooltip.Provider>
+ <PopoverContent
+ side="top"
+ align="end"
+ sideOffset={8}
+ className={`${surface} relative`}
+ aria-label={t('chat.runningStatus.rateHistory')}
+ onInteractOutside={(event) => event.preventDefault()}
+ onEscapeKeyDown={(event) => {
+ event.preventDefault();
+ setMode('dismissed');
+ }}
+ >
+ <button
+ type="button"
+ aria-label={t('titleBar.close')}
+ onClick={() => setMode('dismissed')}
+ className="absolute right-2 top-2 inline-flex size-6 items-center justify-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--button-secondary-hover)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--text-secondary)]"
+ >
+ <X size={12} aria-hidden="true" />
+ </button>
+ {card}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/localizeAgentStatus.ts b/apps/desktop/src/renderer/features/cc-agent/lib/localizeAgentStatus.ts
index 290e750d3d..3183ad6486 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/localizeAgentStatus.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/localizeAgentStatus.ts
@@ -9,6 +9,8 @@ const STATUS_KEYS = new Map<string, string>([
['compacting', 'ccAgent.agentStatus.compacting'],
['spawning agent', 'ccAgent.agentStatus.spawningAgent'],
['done', 'ccAgent.agentStatus.done'],
+ ['waiting on approval', 'ccAgent.sidebar.card.awaitingPermission'],
+ ['waiting on input', 'ccAgent.sidebar.card.awaitingQuestion'],
['just wait', 'ccAgent.agentStatus.waiting'],
['working', 'ccAgent.agentStatus.working'],
['running', 'ccAgent.agentStatus.running'],
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts b/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts
new file mode 100644
index 0000000000..6351e26a7f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts
@@ -0,0 +1,118 @@
+export interface RateSample {
+ /** Cumulative measured generation time across turns, excluding unmeasured gaps. */
+ durationMs: number;
+ outputTokens: number;
+ rate: number;
+}
+
+export interface RateHistory {
+ startedAt: number | null;
+ baseline: { durationMs: number; outputTokens: number } | null;
+ samples: RateSample[];
+ peak: number;
+ latestRate: number | null;
+}
+
+export function emptyRateHistory(startedAt: number | null): RateHistory {
+ return { startedAt, baseline: null, samples: [], peak: 0, latestRate: null };
+}
+
+const MAX_RATE_SAMPLES = 60;
+
+/** Real usage reports are sparse: this is the latest measured interval, not an instantaneous rate. */
+export function recordRunningTokenRate(
+ history: RateHistory,
+ input: {
+ startedAt: number | null;
+ outputTokens: number;
+ generationDurationMs: number;
+ generationReliable: boolean;
+ },
+): RateHistory {
+ const { outputTokens, generationDurationMs, generationReliable } = input;
+ // Terminal status clears startedAt before the status bar finishes its linger/fade.
+ // Keep its identity so a final paired usage report can still be recorded.
+ const startedAt = input.startedAt ?? history.startedAt;
+ const previous = history.baseline;
+ const reset =
+ history.startedAt !== startedAt ||
+ (previous !== null &&
+ (generationDurationMs < previous.durationMs || outputTokens < previous.outputTokens));
+ // Reset only the measurement baseline; completed intervals remain in the chart.
+ const current = reset ? { ...history, startedAt, baseline: null, latestRate: null } : history;
+ if (
+ !generationReliable ||
+ startedAt === null ||
+ !Number.isFinite(outputTokens) ||
+ !Number.isFinite(generationDurationMs) ||
+ outputTokens < 0 ||
+ generationDurationMs < 0
+ ) {
+ return current.baseline || current.latestRate !== null
+ ? { ...current, baseline: null, latestRate: null }
+ : current;
+ }
+ const baseline = { durationMs: generationDurationMs, outputTokens };
+ if (!current.baseline) {
+ // Opening midway through a turn must not label its cumulative average as a recent sample.
+ return { ...current, baseline };
+ }
+ const durationDelta = generationDurationMs - current.baseline.durationMs;
+ const tokenDelta = outputTokens - current.baseline.outputTokens;
+ if (durationDelta === 0 && tokenDelta === 0) return current;
+ if (durationDelta === 0) {
+ // A corrected count without a matching time cannot produce a rate.
+ return { ...current, baseline };
+ }
+ const rate = (tokenDelta * 1000) / durationDelta;
+ if (!Number.isFinite(rate)) return { ...current, baseline };
+ const samples = [
+ ...current.samples.slice(-(MAX_RATE_SAMPLES - 1)),
+ {
+ durationMs: (current.samples.at(-1)?.durationMs ?? 0) + durationDelta,
+ outputTokens,
+ rate,
+ },
+ ];
+ return {
+ startedAt,
+ baseline,
+ samples,
+ peak: Math.max(...samples.map((sample) => sample.rate)),
+ latestRate: rate,
+ };
+}
+
+const MAX_CACHED_SESSIONS = 20;
+
+/**
+ * 进程内按会话缓存速度历史:切到其他任务再切回同一任务时图表不清零。
+ * 刻意不落盘(磁盘持久化超出本功能边界),应用重启后自然清零。
+ */
+const rateHistoryBySession = new Map<string, RateHistory>();
+
+export function loadCachedRateHistory(sessionKey: string): RateHistory | null {
+ const cached = rateHistoryBySession.get(sessionKey);
+ if (!cached) return null;
+ // Map 按插入序迭代:读到的会话移到队尾,淘汰从队头取最久未用的。
+ rateHistoryBySession.delete(sessionKey);
+ rateHistoryBySession.set(sessionKey, cached);
+ return cached;
+}
+
+export function saveCachedRateHistory(sessionKey: string, history: RateHistory): void {
+ // 没有采样点就没有可恢复的图表,不必占缓存名额。
+ if (history.samples.length === 0) return;
+ rateHistoryBySession.delete(sessionKey);
+ rateHistoryBySession.set(sessionKey, history);
+ while (rateHistoryBySession.size > MAX_CACHED_SESSIONS) {
+ const oldestKey = rateHistoryBySession.keys().next().value;
+ if (oldestKey === undefined) break;
+ rateHistoryBySession.delete(oldestKey);
+ }
+}
+
+/** 整体清空;供测试与将来的登出/数据清理流程使用。 */
+export function clearRateHistoryCache(): void {
+ rateHistoryBySession.clear();
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenUsage.ts b/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenUsage.ts
index 1e6e507aa1..aa3a5a3258 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenUsage.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenUsage.ts
@@ -1,9 +1,7 @@
import { formatOutputTokenRateValue } from '@/lib/turnUsageTooltip';
export function formatRunningTokenCount(tokenUsage: number): string {
- return tokenUsage >= 1000
- ? `${(tokenUsage / 1000).toFixed(1)}k`
- : `${tokenUsage}`;
+ return tokenUsage >= 1000 ? `${(tokenUsage / 1000).toFixed(1)}k` : `${tokenUsage}`;
}
export function formatLiveOutputTokenRate(
@@ -16,9 +14,7 @@ export function formatLiveOutputTokenRate(
}
export type RunningUsageMeta =
- | { kind: 'rate'; rate: string }
- | { kind: 'tokens' }
- | { kind: 'none' };
+ { kind: 'rate'; rate: string } | { kind: 'tokens' } | { kind: 'none' };
/**
* Live status prefers generation-only TPS when the harness can prove it.
@@ -31,6 +27,8 @@ export function resolveRunningUsageMeta(input: {
generationDurationMs: number;
generationReliable: boolean;
tokenUsage: number;
+ /** Latest paired sample for the current turn; historical points alone are insufficient. */
+ latestRate?: number | null;
}): RunningUsageMeta {
const rate = formatLiveOutputTokenRate(
input.outputTokens,
@@ -38,6 +36,19 @@ export function resolveRunningUsageMeta(input: {
input.generationReliable,
);
if (rate) return { kind: 'rate', rate };
+ if (
+ input.latestRate === 0 &&
+ input.outputTokens === 0 &&
+ input.generationReliable &&
+ Number.isFinite(input.generationDurationMs) &&
+ input.generationDurationMs > 0
+ )
+ return { kind: 'rate', rate: '0' };
if (input.tokenUsage > 0) return { kind: 'tokens' };
return { kind: 'none' };
}
+
+/** Keep recent and peak rates consistent with the cumulative rate's low-speed threshold. */
+export function formatRecentOutputTokenRate(rate: number): string | null {
+ return rate === 0 ? '0' : formatOutputTokenRateValue(rate, 1000);
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fc6c88f707..6ac049852e 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8591,8 +8591,15 @@
}
},
"runningStatus": {
+ "currentRate": "Latest speed",
+ "waitingSample": "Sampling",
+ "averageRate": "Turn average",
+ "rateHistory": "Generation speed history",
+ "outputTotal": "Output",
+ "observedPeak": "Peak",
"tokenRate": "{{rate}} tok/s",
- "tokenRateDescription": "The main Agent’s average generation speed for this turn, including thinking and excluding tool execution and approval waits. Updated with reported usage; the adjacent timer shows total turn time.",
+ "tokenRateUnit": "tok/s",
+ "tokenRateDescription": "Latest generation interval. Excludes tools and waits.",
"tokenCount": "{{tokens}} tok"
},
"shareImage": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 968681d771..d3bd823ee9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8586,8 +8586,15 @@
}
},
"runningStatus": {
+ "currentRate": "直近の速度",
+ "waitingSample": "計測中",
+ "averageRate": "このターンの平均",
+ "rateHistory": "生成速度の推移",
+ "outputTotal": "累計出力",
+ "observedPeak": "ピーク",
"tokenRate": "{{rate}} tok/s",
- "tokenRateDescription": "このターンのメイン Agent の平均生成速度です。思考を含み、ツール実行と承認待ちは除きます。使用量の報告に合わせて更新され、隣にはターン全体の経過時間が表示されます。",
+ "tokenRateUnit": "tok/s",
+ "tokenRateDescription": "直近の生成区間の速度。ツール実行と待機は除きます。",
"tokenCount": "{{tokens}} tok"
},
"shareImage": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 93de7a4cc2..7d168782f0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8586,8 +8586,15 @@
}
},
"runningStatus": {
+ "currentRate": "최근 속도",
+ "waitingSample": "측정 중",
+ "averageRate": "이번 턴 평균",
+ "rateHistory": "생성 속도 추이",
+ "outputTotal": "누적 출력",
+ "observedPeak": "최고",
"tokenRate": "{{rate}} tok/s",
- "tokenRateDescription": "이번 턴에서 메인 Agent의 평균 생성 속도입니다. 사고 과정을 포함하며 도구 실행과 승인 대기 시간은 제외합니다. 사용량 보고에 따라 갱신되며, 옆에는 턴의 전체 경과 시간이 표시됩니다.",
+ "tokenRateUnit": "tok/s",
+ "tokenRateDescription": "최근 생성 구간의 속도. 도구 실행과 대기는 제외합니다.",
"tokenCount": "{{tokens}} tok"
},
"shareImage": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 0c7eb68ee3..8667db9042 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8582,8 +8582,15 @@
}
},
"runningStatus": {
+ "currentRate": "最近速度",
+ "waitingSample": "采样中",
+ "averageRate": "本轮平均",
+ "rateHistory": "生成速度历史",
+ "outputTotal": "累计输出",
+ "observedPeak": "峰值",
"tokenRate": "{{rate}} tok/s",
- "tokenRateDescription": "本轮主 Agent 的平均生成速度,含思考,排除工具执行和审批等待。随用量回报更新;旁边显示本轮总耗时。",
+ "tokenRateUnit": "tok/s",
+ "tokenRateDescription": "最近一段生成速度,不含工具执行与等待。",
"tokenCount": "{{tokens}} tok"
},
"shareImage": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 6ee19b6003..8e117ecd77 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8581,8 +8581,15 @@
}
},
"runningStatus": {
+ "currentRate": "最近速度",
+ "waitingSample": "取樣中",
+ "averageRate": "本輪平均",
+ "rateHistory": "生成速度歷史",
+ "outputTotal": "累計輸出",
+ "observedPeak": "峰值",
"tokenRate": "{{rate}} tok/s",
- "tokenRateDescription": "本輪主 Agent 的平均生成速度,含思考,排除工具執行與審批等待。隨用量回報更新;旁邊顯示本輪總耗時。",
+ "tokenRateUnit": "tok/s",
+ "tokenRateDescription": "最近一段生成速度,不含工具執行與等待。",
"tokenCount": "{{tokens}} tok"
},
"shareImage": {