Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 与桌面统一近期 token 速度采样 (#4900)
Dashe16d7d962aa0
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 206f197a77..ad4768a9d9 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -1,5 +1,6 @@import { RunningTokenRatePopover } from '@/session/RunningTokenRatePopover';import { companionConversationItems } from '@/session/companionConversationPresentation';+import { useRunningTokenRateHistory } from '@/session/useRunningTokenRateHistory';import { HomeHeaderGlassButton } from '@/session/HomeHeaderGlassButton';import { HomeNewTaskButton } from '@/session/HomeNewTaskButton';import { RecentMessageHistories, MessageHistoryOverlay } from '@/session/RecentMessageHistories';@@ -9479,6 +9480,8 @@ export default function SessionScreen() {reconnectAttempt={remoteSessionRunStatus.reconnectAttempt}sideTaskRunning={remoteSessionRunStatus.sideTaskRunning}startedAt={composerActivityStartedAtMs}+ rateStartedAt={remoteSessionRunStatus.startedAt}+ streaming={isSessionStreaming}tokenUsage={composerActivityTokenUsage}outputTokens={remoteSessionRunStatus.outputTokens}generationDurationMs={remoteSessionRunStatus.generationDurationMs}@@ -11230,6 +11233,8 @@ function ComposerActivityStatus({reconnectAttempt,sideTaskRunning,startedAt,+ rateStartedAt = startedAt,+ streaming = false,tokenUsage,outputTokens,generationDurationMs,@@ -11237,11 +11242,13 @@ function ComposerActivityStatus({generationActive,visible,}: {- availableRegion: LayoutRect;+ availableRegion?: LayoutRect;sessionKey: string;reconnectAttempt: RemoteSessionRunStatus['reconnectAttempt'];sideTaskRunning: boolean;startedAt: number | null;+ rateStartedAt?: number | null;+ streaming?: boolean;tokenUsage: number;outputTokens: number;generationDurationMs: number;@@ -11267,6 +11274,18 @@ function ComposerActivityStatus({return () => clearInterval(interval);}, [startedAt, visible]);+ // 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({+ sessionKey,+ startedAt: samplerStartedAt,+ outputTokens,+ generationDurationMs,+ generationReliable: generationReliable && visible && !reconnectAttempt && !sideTaskRunning,+ streaming,+ });+if (!visible) return null;const elapsedText = formatComposerActivityElapsed(elapsed);@@ -11274,16 +11293,17 @@ function ComposerActivityStatus({const tokenText = t('session.screen.tokenCount', { tokens: tokenCount });const tokenA11yText = t('session.screen.tokenCountFull', { tokens: tokenCount });const showElapsedOnly = sideTaskRunning || Boolean(reconnectAttempt);- const rateValue = formatComposerActivityRateValue(- outputTokens,- generationDurationMs,- generationReliable && !showElapsedOnly,- );+ const rateValue = formatComposerActivityRateValue(showElapsedOnly ? null : rateHistory.latestRate);+ const canShowRateDetails = !showElapsedOnly+ && generationReliable+ && outputTokens > 0+ && Number.isFinite(outputTokens)+ && Number.isFinite(generationDurationMs)+ && generationDurationMs > 0;const rateText = rateValue? t('session.screen.tokenRate', { rate: rateValue }): null;const showUsageMeta = !showElapsedOnly && (Boolean(rateText) || tokenUsage > 0);- const canShowRateDetails = rateValue !== null;const usageMeta = (<View style={[styles.composerActivityPill, styles.composerActivityMeta]}><BlurBackdrop intensity={20} overlayColor={colors.surfaceTranslucent} style={styles.composerActivityPillBackdrop} />@@ -11346,7 +11366,8 @@ function ComposerActivityStatus({enabled={canShowRateDetails}availableRegion={availableRegion}sessionKey={sessionKey}- startedAt={startedAt}+ startedAt={samplerStartedAt}+ history={rateHistory}outputTokens={outputTokens}generationDurationMs={generationDurationMs}generationReliable={generationReliable && !showElapsedOnly}@@ -11376,16 +11397,9 @@ function formatComposerActivityTokenCount(tokenUsage: number): string {return safeTokens >= 1000 ? `${(safeTokens / 1000).toFixed(1)}k` : `${safeTokens}`;}-function formatComposerActivityRateValue(- outputTokens: number,- durationMs: number,- generationReliable: boolean,-): string | null {- if (!generationReliable || outputTokens <= 0 || !Number.isFinite(durationMs) || durationMs <= 0) {- return null;- }- const rate = (outputTokens * 1000) / durationMs;- if (!Number.isFinite(rate) || rate <= 0) return null;+function formatComposerActivityRateValue(rate: number | null): string | null {+ if (rate === null || !Number.isFinite(rate) || rate < 0) return null;+ if (rate === 0) return '0';return rate < 0.1 ? '<0.1' : rate >= 100 ? rate.toFixed(0) : rate.toFixed(1).replace(/\.0$/, '');}diff --git a/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx b/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsxnew file mode 100644index 0000000000..2f90f5e316--- /dev/null+++ b/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx@@ -0,0 +1,149 @@+// @vitest-environment jsdom+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { clearRateHistoryCache } from '@cindy/maker-shared';+import { useRunningTokenRateHistory } from '../session/useRunningTokenRateHistory';++type Input = Parameters<typeof useRunningTokenRateHistory>[0];+const initial: Input = {+ sessionKey: 'owner/device/task',+ startedAt: 1,+ outputTokens: 1000,+ generationDurationMs: 10_000,+ generationReliable: true,+};+let root: ReturnType<typeof createRoot>;+let host: HTMLDivElement;+let current: Input;+function Probe(props: Input) {+ const history = useRunningTokenRateHistory(props);+ return <span>{history.latestRate ?? 'waiting'}</span>;+}+function report(patch: Partial<Input> = {}) {+ current = { ...current, ...patch };+ act(() => root.render(<Probe key={current.sessionKey} {...current} />));+ return host.textContent;+}+beforeEach(() => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ vi.useFakeTimers();+ vi.setSystemTime(100_000);+ clearRateHistoryCache();+ host = document.createElement('div');+ root = createRoot(host);+ current = { ...initial };+});+afterEach(() => {+ act(() => root.unmount());+ clearRateHistoryCache();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++it('waits for a paired interval and shows its rate instead of the turn average', () => {+ expect(report()).toBe('waiting');+ expect(report({ outputTokens: 1025, generationDurationMs: 10_500 })).toBe('waiting');+ 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(report({ outputTokens: 1140 })).toBe('20');+});++it('expires stale samples after 60 seconds and resumes on a new paired report', () => {+ report();+ report({ outputTokens: 1100, generationDurationMs: 12_000 });+ act(() => vi.advanceTimersByTime(59_999));+ expect(host.textContent).toBe('50');+ act(() => vi.advanceTimersByTime(1));+ expect(host.textContent).toBe('waiting');+ expect(report({ outputTokens: 1140, generationDurationMs: 14_000 })).toBe('20');+});++it('resets the baseline for a new turn and for counter rollback', () => {+ report();+ report({ outputTokens: 1100, generationDurationMs: 12_000 });+ expect(report({ startedAt: 2, outputTokens: 0, generationDurationMs: 0 })).toBe('waiting');+ expect(report({ outputTokens: 100, generationDurationMs: 1000 })).toBe('100');+ expect(report({ outputTokens: 10, generationDurationMs: 100 })).toBe('waiting');+});++it('records the final interval when the terminal report clears the remote start', () => {+ report();+ expect(report({ outputTokens: 1100, generationDurationMs: 12_000 })).toBe('50');+ expect(report({ startedAt: null, outputTokens: 1140, generationDurationMs: 14_000 })).toBe('20');+ act(() => vi.advanceTimersByTime(600));+ expect(report()).toBe('20');+ // A real next turn still resets the terminal sample.+ expect(report({ startedAt: 2, outputTokens: 0, generationDurationMs: 0 })).toBe('waiting');+});++it('discards unreliable or reconnecting measurements instead of reviving the old rate', () => {+ report();+ report({ outputTokens: 1100, generationDurationMs: 12_000 });+ expect(report({ generationReliable: false })).toBe('waiting');+ expect(report({ generationReliable: true })).toBe('waiting');+ expect(report({ outputTokens: 1140, generationDurationMs: 14_000 })).toBe('20');+});++it('isolates tasks and restores only fresh cached measurements on return', () => {+ report();+ report({ outputTokens: 1100, generationDurationMs: 12_000 });+ expect(report({ sessionKey: 'other/device/task' })).toBe('waiting');+ expect(report({ sessionKey: initial.sessionKey })).toBe('50');+ report({ sessionKey: 'other/device/task' });+ act(() => vi.advanceTimersByTime(60_000));+ expect(report({ sessionKey: initial.sessionKey })).toBe('waiting');+});++it('keeps measured zero distinct from missing data', () => {+ expect(report({ outputTokens: 0, generationDurationMs: 0 })).toBe('waiting');+ expect(report({ generationDurationMs: 1000 })).toBe('0');+});++it('does not show the previous rate before the next remote turn starts', () => {+ report();+ expect(report({ outputTokens: 1100, generationDurationMs: 12_000 })).toBe('50');+ act(() => root.unmount());+ root = createRoot(host);+ current = {+ ...current,+ startedAt: null,+ streaming: true,+ outputTokens: 1100,+ generationDurationMs: 12_000,+ };+ act(() => root.render(<Probe key={current.sessionKey} {...current} />));+ expect(host.textContent).toBe('waiting');++ act(() => root.unmount());+ root = createRoot(host);+ current = { ...current, streaming: false };+ act(() => root.render(<Probe key={current.sessionKey} {...current} />));+ expect(host.textContent).toBe('waiting');+});++it('drops the previous rate when a new local turn starts during the terminal linger', () => {+ report();+ expect(report({ outputTokens: 1100, generationDurationMs: 12_000 })).toBe('50');+ expect(+ report({+ startedAt: null,+ outputTokens: 1140,+ generationDurationMs: 14_000,+ streaming: false,+ }),+ ).toBe('20');+ expect(report({ streaming: true })).toBe('waiting');+ expect(+ report({+ startedAt: 2,+ outputTokens: 0,+ generationDurationMs: 0,+ streaming: true,+ }),+ ).toBe('waiting');+ expect(report({ outputTokens: 40, generationDurationMs: 1000 })).toBe('40');+});diff --git a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsxindex 7c61d3db72..0e38c576e7 100644--- a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx+++ b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx@@ -13,6 +13,7 @@ import ts from "typescript";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vitest";import { clearRateHistoryCache, loadCachedRateHistory } from "@cindy/maker-shared/usage-format";+import { useRunningTokenRateHistory } from "../session/useRunningTokenRateHistory";import { RunningTokenRatePopover } from "@/session/RunningTokenRatePopover";import { keyboardControlRegion, type ReservedRegion } from "@/platform/windowGeometry";@@ -142,6 +143,7 @@ const bindings = {iconSize: {},iconStroke: {},RunningTokenRatePopover,+ useRunningTokenRateHistory,formatComposerActivityElapsed: () => "1s",formatComposerActivityTokenCount: () => "100",};diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.tsindex 1957226825..3520191064 100644--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts@@ -223,12 +223,15 @@ describe('mobile session composer desktop-first surface', () => {expect(source).toContain('reconnectAttempt={remoteSessionRunStatus.reconnectAttempt}');expect(source).toContain('sideTaskRunning={remoteSessionRunStatus.sideTaskRunning}');expect(source).toContain('startedAt={composerActivityStartedAtMs}');+ expect(source).toContain('rateStartedAt={remoteSessionRunStatus.startedAt}');+ expect(source).toContain('streaming={isSessionStreaming}');+ expect(source).toContain('startedAt: samplerStartedAt,');expect(source).toContain('tokenUsage={composerActivityTokenUsage}');expect(source).toContain('outputTokens={remoteSessionRunStatus.outputTokens}');expect(source).toContain('generationDurationMs={remoteSessionRunStatus.generationDurationMs}');expect(source).toContain('ArrowDown');expect(source).toContain('const showElapsedOnly = sideTaskRunning || Boolean(reconnectAttempt);');- expect(source).toContain('const canShowRateDetails = rateValue !== null;');+ expect(source).toContain('const canShowRateDetails = !showElapsedOnly');expect(source).toContain('enabled={canShowRateDetails}');expect(source).toContain('generationActive={remoteSessionRunStatus.generationActive}');expect(source).toContain('const showUsageMeta = !showElapsedOnly && (Boolean(rateText) || tokenUsage > 0);');diff --git a/apps/mobile/src/session/RunningTokenRatePopover.tsx b/apps/mobile/src/session/RunningTokenRatePopover.tsxindex 2e801a5adb..0defe30b3c 100644--- a/apps/mobile/src/session/RunningTokenRatePopover.tsx+++ b/apps/mobile/src/session/RunningTokenRatePopover.tsx@@ -16,6 +16,7 @@ import {recordRunningTokenRate,saveCachedRateHistory,RATE_SAMPLE_FRESH_MS,+ type RateHistory,} from "@cindy/maker-shared/usage-format";import { useTheme, useThemedStyles, type ThemeColors } from "@/theme";import {@@ -51,6 +52,7 @@ export function RunningTokenRatePopover({label,availableRegion,enabled = true,+ history: managedHistory,}: {sessionKey: string;startedAt: number | null;@@ -61,6 +63,8 @@ export function RunningTokenRatePopover({label: string;availableRegion?: LayoutRect;enabled?: boolean;+ /** When the status row already sampled, reuse that history instead of recording twice. */+ history?: RateHistory;}) {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();@@ -131,14 +135,15 @@ export function RunningTokenRatePopover({);const longPressed = useRef(false);const touchStart = useRef<{ x: number; y: number } | null>(null);- const [history, setHistory] = useState(() => {+ const [internalHistory, setInternalHistory] = useState(() => {const cached = loadCachedRateHistory(sessionKey);return cached? { ...cached, baseline: null, lastReport: null, latestRate: null }: emptyRateHistory(null);});useEffect(() => {- setHistory((previous) =>+ if (managedHistory) return;+ setInternalHistory((previous) =>recordRunningTokenRate(previous, {startedAt,outputTokens,@@ -146,10 +151,12 @@ export function RunningTokenRatePopover({generationReliable,}),);- }, [startedAt, outputTokens, generationDurationMs, generationReliable]);+ }, [managedHistory, startedAt, outputTokens, generationDurationMs, generationReliable]);+ const history = managedHistory ?? internalHistory;useEffect(() => {- saveCachedRateHistory(sessionKey, history);- }, [sessionKey, history]);+ if (managedHistory) return;+ saveCachedRateHistory(sessionKey, internalHistory);+ }, [managedHistory, sessionKey, internalHistory]);const [now, setNow] = useState(Date.now);useEffect(() => {if (history.latestSampleAt === undefined) return;diff --git a/apps/mobile/src/session/useRunningTokenRateHistory.ts b/apps/mobile/src/session/useRunningTokenRateHistory.tsnew file mode 100644index 0000000000..2fbcca018b--- /dev/null+++ b/apps/mobile/src/session/useRunningTokenRateHistory.ts@@ -0,0 +1,98 @@+import { useEffect, useRef, useState } from 'react';+import {+ emptyRateHistory,+ loadCachedRateHistory,+ recordRunningTokenRate,+ saveCachedRateHistory,+ RATE_SAMPLE_FRESH_MS,+ type RateHistory,+} from '@cindy/maker-shared';++export function useRunningTokenRateHistory(input: {+ /** 会话身份:用于进程内缓存速度历史,切任务再切回不清零(重启应用清零)。 */+ sessionKey: string | null;+ startedAt: number | null;+ outputTokens: number;+ generationDurationMs: number;+ generationReliable: boolean;+ /** 本地发送或队列已让活动条出现,但远端本轮 startedAt 可能仍是 null。 */+ streaming?: boolean;+}) {+ const {+ sessionKey,+ startedAt,+ outputTokens,+ generationDurationMs,+ generationReliable,+ streaming = false,+ } = input;+ // 挂载时从按会话的进程内缓存播种:ComposerActivityStatus 以账号、设备和任务身份为 key,+ // 切走再切回是全新挂载,历史从缓存恢复而不是从零开始。+ const [history, setHistory] = useState<RateHistory>(() => {+ const cached = sessionKey ? loadCachedRateHistory(sessionKey) : null;+ if (!cached) return emptyRateHistory(null);+ // 空闲态恢复时丢弃两个计数起点:无法判断计数属于哪一轮,既不能+ // 用旧 baseline 计算区间,也不能用旧 lastReport 判定当前轮计数回退。+ // 同时也丢掉上一轮速率。活动条会在远端 startedAt 到达前因本地发送重新挂载,+ // 空闲切回同样没有当前轮可归属的速率。+ if (startedAt !== null) return cached;+ return { ...cached, baseline: null, lastReport: null, latestRate: null };+ });+ const loadedSessionKey = useRef(sessionKey);+ useEffect(() => {+ setHistory((previous) => {+ const switched = loadedSessionKey.current !== sessionKey;+ loadedSessionKey.current = sessionKey;+ const cached = switched && sessionKey ? loadCachedRateHistory(sessionKey) : null;+ const seeded = !switched+ ? previous+ : !cached+ ? emptyRateHistory(startedAt)+ : startedAt === null+ ? { ...cached, baseline: null, lastReport: null, latestRate: null }+ : cached;+ const recorded = recordRunningTokenRate(seeded, {+ startedAt,+ outputTokens,+ generationDurationMs,+ generationReliable,+ });+ // 同一挂载在 600ms 收尾粘滞内再次发送时不会重新播种。本地活动已开始而+ // 远端 startedAt 仍为 null 时,上一轮速率不能继续当作当前速度。+ if (+ streaming &&+ startedAt === null &&+ (recorded.latestRate !== null || recorded.baseline !== null || recorded.lastReport !== null)+ ) {+ return { ...recorded, baseline: null, lastReport: null, latestRate: null };+ }+ return recorded;+ });+ }, [sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, streaming]);+ useEffect(() => {+ if (sessionKey) saveCachedRateHistory(sessionKey, history);+ }, [sessionKey, history]);+ const [now, setNow] = useState(Date.now);+ useEffect(() => {+ const timestamp = history.latestSampleAt;+ if (timestamp === undefined || history.latestRate === null) return;+ setNow(Date.now());+ const timer = setTimeout(+ () => setNow(Date.now()),+ Math.max(0, timestamp + RATE_SAMPLE_FRESH_MS - Date.now()),+ );+ return () => clearTimeout(timer);+ }, [history.latestSampleAt, history.latestRate]);+ const visibleHistory =+ history.latestSampleAt === undefined ||+ Math.max(now, Date.now()) - history.latestSampleAt >= RATE_SAMPLE_FRESH_MS+ ? { ...history, latestRate: null }+ : history;+ const displayed =+ startedAt === null || history.startedAt === startedAt+ ? visibleHistory+ : { ...history, startedAt, baseline: null, latestRate: null };+ return streaming && startedAt === null+ ? { ...displayed, baseline: null, lastReport: null, latestRate: null }+ : displayed;+}diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.tsindex 8d2ce10c64..4805502f7b 100644--- a/packages/maker-shared/src/index.ts+++ b/packages/maker-shared/src/index.ts@@ -63,3 +63,4 @@ export * from './sessionPrRefs.js';export * from './taskTags';export * from './workingStatus.js';+export * from './runningTokenRateHistory.js';