Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): cancel stale list performance sweeps
elfcv93fca8f7575a
diff --git a/apps/mobile/app/listperf.tsx b/apps/mobile/app/listperf.tsxindex b5270af91e..c623318bf3 100644--- a/apps/mobile/app/listperf.tsx+++ b/apps/mobile/app/listperf.tsx@@ -42,7 +42,6 @@ export default function ListPerfHarness() {const items = useMemo(() => buildListPerfRenderItems(turns, { media }), [turns, media]);const runKey = `${turns}|${media ? 1 : 0}|${pxPerFrame}|${recycle ? 1 : 0}|${params.run ?? '0'}`;const apiRef = useRef<ListApi | null>(null);- const startedKeyRef = useRef<string | null>(null);const [stats, setStats] = useState<FrameStats | null>(null);const [webViewMetrics, setWebViewMetrics] = useState<MobileMessageWebViewMetrics | null>(null);const [markdownMetrics, setMarkdownMetrics] = useState<MobileMarkdownRenderMetrics | null>(null);@@ -53,11 +52,14 @@ export default function ListPerfHarness() {}, []);useEffect(() => {- if (!auto || startedKeyRef.current === runKey) return undefined;let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let cancelSweep: (() => void) | undefined;setStats(null);setWebViewMetrics(null);setMarkdownMetrics(null);+ setPhase(auto ? 'waiting…' : 'manual');+ if (!auto) return undefined;// Counters are process-global so repeated A/B deeplinks must start from a// clean window; otherwise B includes all parses performed by A.resetMobileMarkdownRenderMetrics();@@ -69,28 +71,28 @@ export default function ListPerfHarness() {const ready = !!m && m.contentHeight > m.viewportHeight * 2 && m.viewportHeight > 0;if (!ready) {if (attempt > 40) { setPhase('list never settled'); return; }- setTimeout(() => waitAndRun(attempt + 1), 200);+ timer = setTimeout(() => waitAndRun(attempt + 1), 200);return;}- startedKeyRef.current = runKey;// 从顶向下匀速扫:持续挂载「尚未渲染」的 cell(变高虚拟化下 contentHeight 会低估,// 不能靠它算底部;从顶向下 +vel 推进 maxFrames 帧,保证测的是冷挂载稳态)。setPhase(`sweeping top→down @${pxPerFrame}px/f`);api!.scrollTo(0);- setTimeout(() => {- runScrollSweep({+ timer = setTimeout(() => {+ if (cancelled) return;+ cancelSweep = runScrollSweep({label: `list=Legend turns=${turns} media=${media ? 1 : 0} recycle=${recycle ? 1 : 0} vel=${pxPerFrame}`,fromY: 0,toY: 1_000_000,pxPerFrame,maxFrames: 150,- scrollTo: (y) => apiRef.current?.scrollTo(y),+ scrollTo: (y) => api!.scrollTo(y),onDone: (s) => {if (cancelled) return;setStats(s);- const currentWebViewMetrics = apiRef.current?.getWebViewMetrics();+ const currentWebViewMetrics = api!.getWebViewMetrics();if (currentWebViewMetrics) setWebViewMetrics(currentWebViewMetrics);- const currentMarkdownMetrics = apiRef.current?.getMarkdownMetrics();+ const currentMarkdownMetrics = api!.getMarkdownMetrics();if (currentMarkdownMetrics) setMarkdownMetrics(currentMarkdownMetrics);setPhase('done');// 打到 Metro 日志,便于抓取。@@ -101,7 +103,11 @@ export default function ListPerfHarness() {}, 400);};waitAndRun(0);- return () => { cancelled = true; };+ return () => {+ cancelled = true;+ clearTimeout(timer);+ cancelSweep?.();+ };}, [auto, pxPerFrame, media, turns, runKey]);if (!__DEV__) {diff --git a/apps/mobile/src/__tests__/listPerfHarness.test.tsx b/apps/mobile/src/__tests__/listPerfHarness.test.tsxnew file mode 100644index 0000000000..6e7145c5f1--- /dev/null+++ b/apps/mobile/src/__tests__/listPerfHarness.test.tsx@@ -0,0 +1,108 @@+// @vitest-environment jsdom+// Regression #7086: a changed route must own its scroll window. Existing tail+// controller tests never mount this harness or cancel its delayed/rAF sweep.+// Real ListPerfHarness + runScrollSweep; only native/router ports are replaced.+// Minimal failures: leave during the 400ms settle delay or during an active sweep.+// Tier: unit, virtual timers; native scrolling remains simulator acceptance.+import { act, useEffect, useMemo } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import ListPerfHarness from '../../app/listperf';++const state = vi.hoisted(() => ({+ params: { turns: '40', media: '0', auto: '1', run: 'one' } as Record<string, string>,+ lists: [] as { offsets: number[]; recycle: boolean; focus?: string }[],+}));+vi.mock('expo-router', () => ({ useLocalSearchParams: () => state.params }));+vi.mock('react-native', () => ({ View: 'div', Text: 'span', StyleSheet: { create: (v: unknown) => v } }));+vi.mock('react-native-safe-area-context', () => ({ SafeAreaView: 'section' }));+vi.mock('@/debug/listPerfFixture', () => ({ buildListPerfRenderItems: () => [{ key: 'first' }] }));+vi.mock('@/session/mobileMarkdownRenderMetrics', () => ({ resetMobileMarkdownRenderMetrics: vi.fn() }));+vi.mock('@/session/MessageRenderer', () => ({+ MessageRenderer: ({ devExposeList, devRecycleItems, focusedItemKey }: {+ devExposeList: (api: unknown) => void; devRecycleItems: boolean; focusedItemKey?: string;+ }) => {+ const list = useMemo(() => {+ const next = { offsets: [] as number[], recycle: devRecycleItems, focus: focusedItemKey };+ state.lists.push(next);+ return next;+ }, []);+ useEffect(() => {+ devExposeList({+ scrollTo: (y: number) => list.offsets.push(y),+ getMetrics: () => ({ contentHeight: 20000, viewportHeight: 800, offsetY: list.offsets.at(-1) ?? 0 }),+ getWebViewMetrics: () => null,+ getMarkdownMetrics: () => null,+ });+ }, [devExposeList, list]);+ return <div>native list</div>;+ },+}));+let root: Root;+let container: HTMLDivElement;+const render = () => act(() => root.render(<ListPerfHarness />));+const advance = (ms: number) => act(() => vi.advanceTimersByTime(ms));+beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal('__DEV__', true);+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ vi.stubGlobal('requestAnimationFrame', (fn: FrameRequestCallback) => setTimeout(() => fn(performance.now()), 16));+ vi.stubGlobal('cancelAnimationFrame', (id: ReturnType<typeof setTimeout>) => clearTimeout(id));+ vi.spyOn(console, 'log').mockImplementation(() => {});+ state.params = { turns: '40', media: '0', auto: '1', run: 'one' };+ state.lists = [];+ container = document.createElement('div');+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++it.each([100, 600])('cancels the old run when switching to manual after %ims', elapsed => {+ render();+ advance(elapsed);+ const old = state.lists[0];+ const count = old.offsets.length;+ state.params = { ...state.params, run: 'manual', auto: '0', turns: '41' };+ render();+ const next = state.lists.at(-1)!;+ advance(4000);+ expect(old.offsets).toHaveLength(count);+ expect(next.offsets).toEqual([]);+ expect(container.textContent).toContain('manual');+ expect(vi.getTimerCount()).toBe(0);+});++it('releases a pending sweep on unmount', () => {+ render();+ advance(100);+ act(() => root.render(null));+ const count = state.lists[0].offsets.length;+ advance(4000);+ expect(state.lists[0].offsets).toHaveLength(count);+ expect(vi.getTimerCount()).toBe(0);+});++it('finishes each keyed run separately and keeps recycling opt-in', () => {+ render();+ advance(4000);+ const first = state.lists[0];+ expect(first.recycle).toBe(false);+ expect(first.focus).toBe('first');+ expect(first.offsets.slice(0, 4)).toEqual([0, 0, 45, 90]);+ expect(container.textContent).toContain('done');+ const count = first.offsets.length;+ state.params = { ...state.params, run: 'two', recycle: '1' };+ render();+ advance(4000);+ const second = state.lists.at(-1)!;+ expect(second).not.toBe(first);+ expect(second.recycle).toBe(true);+ expect(second.offsets).toEqual(first.offsets);+ expect(first.offsets).toHaveLength(count);+ expect(container.textContent).toContain('done');+ expect(vi.getTimerCount()).toBe(0);+});diff --git a/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.ts b/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.tsindex 7cf7be3a96..5a9e131915 100644--- a/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.ts+++ b/apps/mobile/src/__tests__/messageNativeLifecycleContracts.test.ts@@ -61,7 +61,7 @@ it('uses LegendList virtualization with platform-scoped history anchoring', () =// 重挂仍属于旧父节点的原生 child;listperf 仍可显式做 on/off A/B。expect(source).toContain('devRecycleItems = false,');expect(source).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : false;');- expect(perfHarness).toContain("const recycle = params.recycle !== '0';");+ expect(perfHarness).toContain("const recycle = params.recycle === '1';");expect(listSource).toContain('recycleItems={recycleItems}');expect(listSource).toContain('getItemType={mobileMessageListItemType}');expect(source).toContain('useRecyclingState');diff --git a/apps/mobile/src/debug/scrollProfiler.ts b/apps/mobile/src/debug/scrollProfiler.tsindex 05a5a5f3bd..4f91dd0040 100644--- a/apps/mobile/src/debug/scrollProfiler.ts+++ b/apps/mobile/src/debug/scrollProfiler.ts@@ -47,6 +47,7 @@ function summarize(label: string, intervals: number[], durationMs: number): Fram* 从 fromY 以固定速度(pxPerFrame,向 toY 方向)滚动,每帧推进一小段并记录帧间隔。* scrollTo 用 animated:false(自己控制匀速推进,精确测 JS 帧时)。* warmup:跳过前 N 帧(首帧跳到 fromY 会一次挂载一批,不算稳态)。+ * 返回取消函数;调用后停止滚动,也不发布未完成的测量。*/export function runScrollSweep(opts: {label: string;@@ -57,7 +58,7 @@ export function runScrollSweep(opts: {onDone: (stats: FrameStats) => void;warmup?: number;maxFrames?: number;-}): void {+}): () => void {const { label, fromY, toY, pxPerFrame, scrollTo, onDone } = opts;const warmup = opts.warmup ?? 3;const maxFrames = opts.maxFrames ?? 400;@@ -68,12 +69,15 @@ export function runScrollSweep(opts: {let lastTs = 0;let frameIdx = 0;let measureStartTs = 0;+ let cancelled = false;+ let frame: ReturnType<typeof requestAnimationFrame>;const tick = (ts: number) => {+ if (cancelled) return;if (lastTs === 0) {lastTs = ts;scrollTo(y);- requestAnimationFrame(tick);+ frame = requestAnimationFrame(tick);return;}const dt = ts - lastTs;@@ -91,7 +95,11 @@ export function runScrollSweep(opts: {return;}scrollTo(y);- requestAnimationFrame(tick);+ frame = requestAnimationFrame(tick);+ };+ frame = requestAnimationFrame(tick);+ return () => {+ cancelled = true;+ cancelAnimationFrame(frame);};- requestAnimationFrame(tick);}