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。

fix(mobile): 长时间使用后不再越用越卡

Dash0cf6562d49ee
diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
index 9f55e076e2..35a7e71d72 100644
--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
@@ -474,7 +474,7 @@ describe('mobileSessionMessageCache', () => {
await import('@/session/mobileSessionMessageCache');
const { remoteSessionStore } = await import('@/session/remoteSessionStore');
remoteSessionStore.clear();
- const sessions = Array.from({ length: 9 }, (_, index) => makeSession(`s${index}`));
+ const sessions = Array.from({ length: 13 }, (_, index) => makeSession(`s${index}`));
remoteSessionStore.setDeviceSessions('host-a', 'Mac', sessions);
const cached = makeMessage({ id: 'cached-s0', sessionId: 's0', createdAt: isoAt(1) });
await cacheSessionMessages('host-a', 's0', [cached]);
@@ -482,7 +482,7 @@ describe('mobileSessionMessageCache', () => {
for (const item of sessions) {
remoteSessionStore.setMessages(
item.id,
- Array.from({ length: 100 }, (_, index) => makeMessage({
+ Array.from({ length: 80 }, (_, index) => makeMessage({
id: `${item.id}-${index}`,
sessionId: item.id,
createdAt: isoAt(index),
@@ -630,7 +630,7 @@ describe('mobileSessionMessageCache', () => {
await import('@/session/mobileSessionMessageCache');
const { remoteSessionStore } = await import('@/session/remoteSessionStore');
remoteSessionStore.clear();
- const sessions = Array.from({ length: 9 }, (_, index) => makeSession(`s${index}`));
+ const sessions = Array.from({ length: 13 }, (_, index) => makeSession(`s${index}`));
remoteSessionStore.setDeviceSessions('host-a', 'Mac', sessions);
const cached = makeMessage({
id: 'deleted-row',
@@ -642,7 +642,7 @@ describe('mobileSessionMessageCache', () => {
for (const item of sessions) {
remoteSessionStore.setMessages(
item.id,
- Array.from({ length: 100 }, (_, index) => makeMessage({
+ Array.from({ length: 80 }, (_, index) => makeMessage({
id: `${item.id}-${index}`,
sessionId: item.id,
createdAt: isoAt(index),
diff --git a/apps/mobile/src/__tests__/recentMessageHistories.test.tsx b/apps/mobile/src/__tests__/recentMessageHistories.test.tsx
index 9238dfaa8e..8b21e12ee4 100644
--- a/apps/mobile/src/__tests__/recentMessageHistories.test.tsx
+++ b/apps/mobile/src/__tests__/recentMessageHistories.test.tsx
@@ -25,7 +25,8 @@ vi.mock('@/session/useHomeMode', () => ({ useHomeMode: () => ({ mode: 'tasks' })
vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));
vi.mock('@/session/sessionPaneLayout', () => ({ sessionPaneLayout: () => ({ persistent: true }) }));
vi.mock('@/session/remoteSessionStore', () => ({
- RemoteSessionStoreSubscriptionGate: ({ children }: { children: ReactNode }) => children,
+ RemoteSessionStoreSubscriptionGate: ({ children, enabled }: { children: ReactNode; enabled: boolean }) =>
+ <div data-store-gate={String(enabled)}>{children}</div>,
}));
vi.mock('react-native-reanimated', () => ({
default: {
@@ -108,6 +109,18 @@ describe('resident five-task message lists outside route lifetimes', () => {
expect(original.textContent).toBe('updated:420');
expect(mounts.get('a')).toBe(1);
});
+ it('pauses store subscriptions of every retained list that is not the visible task', async () => {
+ const gateOf = (id: string) => container.querySelector(`[data-task="${id}"]`)!
+ .closest<HTMLElement>('[data-store-gate]')!.dataset.storeGate;
+ await show('a'); await show('b');
+ expect(gateOf('a')).toBe('false');
+ expect(gateOf('b')).toBe('true');
+ await show(null);
+ expect(gateOf('a')).toBe('false');
+ expect(gateOf('b')).toBe('false');
+ await show('a');
+ expect(gateOf('a')).toBe('true');
+ });
it('resizes the same list on rotation without changing its state', async () => {
await show('a');
const original = container.querySelector<HTMLButtonElement>('button')!;
@@ -175,7 +188,8 @@ describe('resident five-task message lists outside route lifetimes', () => {
const original = container.querySelector<HTMLButtonElement>('button')!;
expect(original.textContent).toBe('cached:0');
expect(original.dataset.active).toBe('false');
- expect(original.parentElement?.parentElement?.getAttribute('data-layout')).toContain('\"top\":90');
+ expect(original.closest('[data-store-gate]')?.parentElement?.parentElement?.getAttribute('data-layout'))
+ .toContain('\"top\":90');
expect(original.closest('[data-input="none"]')).not.toBeNull();
await show('a', 'fresh'); expect(original.textContent).toBe('fresh:0');
});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 13b4a0fadd..bbc9849f6f 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -5730,8 +5730,34 @@ describe('任务消息内存治理', () => {
expect(rows.at(-1)?.id).toBe('s1-m-99');
});
+ it('后台运行中的 regular 任务持续收到列表推送,内存窗口不超过一页', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ remoteSessionStore.setSessionRunning('s1', true);
+ const pushed = manyMessages('s1', 300);
+ for (const row of pushed) {
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {
+ sessionId: 's1', listMessage: true, message: row,
+ });
+ }
+ const rows = remoteSessionStore.getMessages('s1');
+ expect(rows).toHaveLength(80);
+ expect(rows.at(-1)?.id).toBe('s1-m-299');
+ });
+
+ it('正在看的 regular 任务不受后台单窗上限影响', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ remoteSessionStore.setSessionRunning('s1', true);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', manyMessages('s1', 120), { authority });
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {
+ sessionId: 's1', listMessage: true, message: messageAt('s1-new', 's1', '2026-01-01T01:00:00.000Z'),
+ });
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(121);
+ });
+
it('regular 全局 LRU 不淘汰当前详情,且总量压回约 800 条', () => {
- const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));
+ // 后台任务各自封顶一页(80),要 11 个以上后台任务才会触发全局淘汰。
+ const sessions = Array.from({ length: 13 }, (_, index) => session(`s${index}`));
remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);
remoteSessionStore.enterSessionMessageDetail('s0');
for (const item of sessions) {
@@ -5748,17 +5774,17 @@ describe('任务消息内存治理', () => {
});
it('notifies an evicted session preview subscriber when another session exceeds the LRU budget', () => {
- const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));
+ const sessions = Array.from({ length: 13 }, (_, index) => session(`s${index}`));
remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);
const previewChanged = vi.fn();
const unsubscribe = remoteSessionStore.subscribeSessionMessagePreview('s0', previewChanged);
try {
- remoteSessionStore.setMessages('s0', manyMessages('s0', 100));
+ remoteSessionStore.setMessages('s0', manyMessages('s0', 80));
expect(remoteSessionStore.getSessionMessagePreview('s0')).toBeDefined();
previewChanged.mockClear();
for (const item of sessions.slice(1)) {
- remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));
+ remoteSessionStore.setMessages(item.id, manyMessages(item.id, 80));
}
expect(remoteSessionStore.getMessages('s0')).toEqual([]);
@@ -5796,18 +5822,18 @@ describe('任务消息内存治理', () => {
});
it('regular LRU 只淘汰可重取正文,不丢尚未落盘的本地系统卡', () => {
- const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));
+ const sessions = Array.from({ length: 13 }, (_, index) => session(`s${index}`));
remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);
const localCard = {
...messageAt('mobile-system-local-only', 's0', '2025-12-31T23:59:59.000Z'),
role: 'system' as const,
};
- remoteSessionStore.setMessages('s0', [localCard, ...manyMessages('s0', 99)]);
+ remoteSessionStore.setMessages('s0', [localCard, ...manyMessages('s0', 79)]);
for (const item of sessions.slice(1)) {
- remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));
+ remoteSessionStore.setMessages(item.id, manyMessages(item.id, 80));
}
- expect(remoteSessionStore.getMessages('s0')).toHaveLength(100);
+ expect(remoteSessionStore.getMessages('s0')).toHaveLength(80);
expect(remoteSessionStore.getMessages('s0').some((row) => row.id === localCard.id)).toBe(true);
});
diff --git a/apps/mobile/src/debug/jankMetrics.test.ts b/apps/mobile/src/debug/jankMetrics.test.ts
new file mode 100644
index 0000000000..8e208627e6
--- /dev/null
+++ b/apps/mobile/src/debug/jankMetrics.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ recordInvokeSent,
+ recordPushHandled,
+ setJankMetricsEnabled,
+ setRemoteSessionStoreSizeSource,
+ takeJankMetrics,
+} from "./jankMetrics";
+
+describe("jank metrics", () => {
+ afterEach(() => setJankMetricsEnabled(false));
+
+ it("records nothing while diagnostics are off", () => {
+ recordPushHandled("local-db:messages:created", 5);
+ setJankMetricsEnabled(true);
+ expect(takeJankMetrics()).toMatchObject({
+ pushCount: 0,
+ invokeCount: 0,
+ pushes: {},
+ invokes: {},
+ });
+ });
+
+ it("reports per-channel push time and request counts for one interval, then resets", () => {
+ setJankMetricsEnabled(true);
+ setRemoteSessionStoreSizeSource(() => ({
+ sessions: 2,
+ messages: 120,
+ maxSessionMessages: 80,
+ storeSubscribers: 40,
+ }));
+ recordPushHandled("local-db:messages:created", 4);
+ recordPushHandled("local-db:messages:created", 10);
+ recordPushHandled("maker:event", 1);
+ recordInvokeSent("git-context:pr-status");
+ recordInvokeSent("git-context:pr-status");
+
+ expect(takeJankMetrics()).toEqual({
+ store: {
+ sessions: 2,
+ messages: 120,
+ maxSessionMessages: 80,
+ storeSubscribers: 40,
+ },
+ pushCount: 3,
+ pushMs: 15,
+ pushes: {
+ "local-db:messages:created": { count: 2, totalMs: 14, maxMs: 10 },
+ "maker:event": { count: 1, totalMs: 1, maxMs: 1 },
+ },
+ invokeCount: 2,
+ invokes: { "git-context:pr-status": 2 },
+ });
+ expect(takeJankMetrics()).toMatchObject({ pushCount: 0, invokeCount: 0 });
+ });
+});
diff --git a/apps/mobile/src/debug/jankMetrics.ts b/apps/mobile/src/debug/jankMetrics.ts
new file mode 100644
index 0000000000..4330cee6cd
--- /dev/null
+++ b/apps/mobile/src/debug/jankMetrics.ts
@@ -0,0 +1,107 @@
+/**
+ * Interval counters for the local diagnostic log, aimed at "the app got slower the longer it ran".
+ *
+ * A `js stall` alone cannot tell which work starved the JS thread. While diagnostics are recording,
+ * this keeps per-channel push handling time, business request counts and the remote session store's
+ * retained size, and the diagnostic tick logs and resets them. Only fixed channel names and numbers
+ * are kept: no payloads, arguments, device ids or session ids.
+ *
+ * Disabled (the default) every record call is a single boolean check.
+ */
+
+export interface RemoteSessionStoreSizeMetrics {
+ /** Sessions holding an in-memory message window. */
+ sessions: number;
+ messages: number;
+ /** Largest single in-memory window, the one every push to that task re-sorts. */
+ maxSessionMessages: number;
+ storeSubscribers: number;
+}
+
+interface ChannelTiming {
+ count: number;
+ totalMs: number;
+ maxMs: number;
+}
+
+const TOP_CHANNELS = 6;
+
+let enabled = false;
+let pushes = new Map<string, ChannelTiming>();
+let invokes = new Map<string, number>();
+let storeSizeSource: (() => RemoteSessionStoreSizeMetrics) | null = null;
+
+export function setJankMetricsEnabled(next: boolean): void {
+ if (enabled === next) return;
+ enabled = next;
+ pushes = new Map();
+ invokes = new Map();
+}
+
+export function jankMetricsEnabled(): boolean {
+ return enabled;
+}
+
+export function recordPushHandled(channel: string, durationMs: number): void {
+ if (!enabled) return;
+ const entry = pushes.get(channel) ?? { count: 0, totalMs: 0, maxMs: 0 };
+ entry.count += 1;
+ entry.totalMs += durationMs;
+ entry.maxMs = Math.max(entry.maxMs, durationMs);
+ pushes.set(channel, entry);
+}
+
+export function recordInvokeSent(channel: string): void {
+ if (!enabled) return;
+ invokes.set(channel, (invokes.get(channel) ?? 0) + 1);
+}
+
+/** The store registers itself so this module does not import the store's module graph. */
+export function setRemoteSessionStoreSizeSource(
+ source: () => RemoteSessionStoreSizeMetrics,
+): void {
+ storeSizeSource = source;
+}
+
+function topChannels<T>(
+ map: Map<string, T>,
+ weight: (value: T) => number,
+): Record<string, T> {
+ return Object.fromEntries(
+ [...map]
+ .sort((left, right) => weight(right[1]) - weight(left[1]))
+ .slice(0, TOP_CHANNELS),
+ );
+}
+
+/** Read and reset the interval counters. */
+export function takeJankMetrics(): {
+ store: RemoteSessionStoreSizeMetrics | null;
+ pushCount: number;
+ pushMs: number;
+ pushes: Record<string, ChannelTiming>;
+ invokeCount: number;
+ invokes: Record<string, number>;
+} {
+ let pushCount = 0;
+ let pushMs = 0;
+ for (const entry of pushes.values()) {
+ pushCount += entry.count;
+ pushMs += entry.totalMs;
+ entry.totalMs = Math.round(entry.totalMs);
+ entry.maxMs = Math.round(entry.maxMs);
+ }
+ let invokeCount = 0;
+ for (const count of invokes.values()) invokeCount += count;
+ const snapshot = {
+ store: storeSizeSource?.() ?? null,
+ pushCount,
+ pushMs: Math.round(pushMs),
+ pushes: topChannels(pushes, (entry) => entry.totalMs),
+ invokeCount,
+ invokes: topChannels(invokes, (count) => count),
+ };
+ pushes = new Map();
+ invokes = new Map();
+ return snapshot;
+}
diff --git a/apps/mobile/src/debug/localDiagnostics.ts b/apps/mobile/src/debug/localDiagnostics.ts
index e204d433d7..4d1024c492 100644
--- a/apps/mobile/src/debug/localDiagnostics.ts
+++ b/apps/mobile/src/debug/localDiagnostics.ts
@@ -12,6 +12,7 @@ import {
} from "./mobileDebugFiles";
import { getMobileMarkdownRenderMetrics } from "../session/mobileMarkdownRenderMetrics";
import { getMobileMessageWebViewMetrics } from "../session/mobileMessageWebViewMetrics";
+import { setJankMetricsEnabled, takeJankMetrics } from "./jankMetrics";
import {
MAX_DIAGNOSTIC_EVENTS,
projectDiagnostic,
@@ -36,6 +37,8 @@ let debugBatch = "";
let debugBytes = 0;
let dropped = 0;
const MAX_PENDING_BYTES = 512 * 1024;
+/** About every 30 s on the 2 s probe, plus immediately after any stall. */
+const JANK_METRICS_EVERY_TICKS = 15;
function updateDebugSink(): void {
setMobileDebugSink(
@@ -253,9 +256,11 @@ export function startLocalDiagnostics(): () => void {
void flushDiagnostics().catch(() => {});
});
let timer: ReturnType<typeof setInterval> | undefined;
+ let ticksSinceJankMetrics = 0;
const tick = () => {
const now = performance.now();
- if (state === "active" && now - lastTick > 3000)
+ const stalled = state === "active" && now - lastTick > 3000;
+ if (stalled)
mobileDebugLog("warn", "lifecycle", "js stall", {
elapsedMs: now - lastTick - 2000,
// A timer gap alone cannot distinguish busy JS from process suspension.
@@ -269,9 +274,20 @@ export function startLocalDiagnostics(): () => void {
markdown: getMobileMarkdownRenderMetrics(),
webViews: getMobileMessageWebViewMetrics(),
});
+ // Counters cover the interval since the previous line, so a line written
+ // right after a stall attributes the work that ran during it.
+ ticksSinceJankMetrics += 1;
+ if (
+ enabled &&
+ (stalled || ticksSinceJankMetrics >= JANK_METRICS_EVERY_TICKS)
+ ) {
+ ticksSinceJankMetrics = 0;
+ mobileDebugLog("debug", "performance", "jank metrics", takeJankMetrics());
+ }
void flushDiagnostics().catch(() => {});
};
const syncProbe = () => {
+ setJankMetricsEnabled(enabled && !stopped);
if (!enabled || stopped) {
if (timer !== undefined) clearInterval(timer);
timer = undefined;
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 02e38501a5..9e3c181e31 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -171,6 +171,7 @@ import type { InputProjection, PendingInteraction, RemoteMessage } from '@/sessi
import { prepareVisualMockDeviceLinkContext } from '@/debug/visualMock';
import { meterDeviceLinkInvokes, recordDeviceLinkPush } from '@/debug/deviceLinkTraffic';
import { decodeGzipBase64TextBounded } from '@/utils/gzipBase64';
+import { jankMetricsEnabled, recordInvokeSent, recordPushHandled } from '@/debug/jankMetrics';
export interface DeviceLinkContextValue {
status: DeviceLinkStatus;
@@ -1167,7 +1168,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}
};
};
- const offFrame = client.onFrame((env) => routeFrame(env, {
+ const offFrame = client.onFrame((env) => routeFrameMeasured(env, {
currentDataOwnerId: currentDataOwnerIdRef.current,
onAccessRevoked: (deviceId) => {
clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
@@ -1637,13 +1638,30 @@ function VisualMockDeviceLinkProvider({ children }: { children: ReactNode }) {
return <DeviceLinkContext.Provider value={value}>{children}</DeviceLinkContext.Provider>;
}
-export function routeFrame(env: Envelope, handlers: {
+type RouteFrameHandlers = {
currentDataOwnerId?: string | null;
onAccessRevoked?: (deviceId: string) => void;
onLinkClosed?: (deviceId: string, reason?: string) => void;
onProviderChanged?: (deviceId: string) => void;
onAgentsChanged?: (deviceId: string) => void;
-} = {}): void {
+};
+
+/** routeFrame plus per-channel push handling time while local diagnostics record. */
+function routeFrameMeasured(env: Envelope, handlers: RouteFrameHandlers): void {
+ if (!jankMetricsEnabled() || env.kind !== 'push') {
+ routeFrame(env, handlers);
+ return;
+ }
+ const started = performance.now();
+ try {
+ routeFrame(env, handlers);
+ } finally {
+ const channel = (env.payload as PushPayload | null)?.channel;
+ recordPushHandled(typeof channel === 'string' ? channel : '(unknown)', performance.now() - started);
+ }
+}
+
+export function routeFrame(env: Envelope, handlers: RouteFrameHandlers = {}): void {
const peerLinkClosed = handlePeerLinkCloseFrame(
env,
(deviceId, reason) => handlers.onLinkClosed?.(deviceId, reason),
@@ -2027,6 +2045,7 @@ async function sendInvoke<T>(
args: unknown[],
opts?: SendInvokeOptions,
): Promise<T> {
+ recordInvokeSent(channel);
// 熔断门禁放在连接等待之前:open 时快速失败,不消耗 1.5s 重连等待也不上管道。
// 同一轮显式 fan-out 复用 cohort;普通调用省略时每次 acquire 都是独立观测。
const slot = acquireDeviceSendSlot(deviceId, opts?.responsivenessCohort, {
diff --git a/apps/mobile/src/session/RecentMessageHistories.tsx b/apps/mobile/src/session/RecentMessageHistories.tsx
index c4bcb0eaa9..6875579f40 100644
--- a/apps/mobile/src/session/RecentMessageHistories.tsx
+++ b/apps/mobile/src/session/RecentMessageHistories.tsx
@@ -6,6 +6,7 @@ import { PaneViewportProvider, usePaneViewport } from '@/platform/AdaptiveWindow
import { getRecentTasks, recentTaskKey, subscribeRecentTasks } from './recentTasks';
import { NativeHistoryHost, NativeHistorySlot, needsResidentHistoryUpgrade } from './NativeResidentHistory';
import { useResidentHomeListContextBridge } from './ResidentHomeList';
+import { RemoteSessionStoreSubscriptionGate } from './remoteSessionStore';
import { MessageHistoryActive, MessageHistoryPositioning } from './messageHistoryActivity';
export { useMessageHistoryActive, useMessageHistoryPositioning } from './messageHistoryActivity';
@@ -80,11 +81,17 @@ export function RecentMessageHistoriesProvider({ children }: { children: ReactNo
{children}
{[...entries].filter(([key]) => allowed.has(key)).map(([key, entry]) => {
const active = onTaskRoute && entry.focused;
- if (NativeHistoryHost) return <NativeHistoryHost key={key} surfaceId={namespace + key}
- pointerEvents="none" style={{ position: 'absolute', width: entry.frame.width, height: entry.frame.height }}>
+ // Retained histories outlive their route, so no route-level gate covers
+ // them. Pause their store subscriptions while hidden; otherwise every
+ // task-list change re-renders all retained message trees.
+ const content = <RemoteSessionStoreSubscriptionGate enabled={active}>
<MessageHistoryPositioning.Provider value={active && entry.ready}>
<MessageHistoryActive.Provider value={active && entry.ready}>{entry.children}</MessageHistoryActive.Provider>
</MessageHistoryPositioning.Provider>
+ </RemoteSessionStoreSubscriptionGate>;
+ if (NativeHistoryHost) return <NativeHistoryHost key={key} surfaceId={namespace + key}
+ pointerEvents="none" style={{ position: 'absolute', width: entry.frame.width, height: entry.frame.height }}>
+ {content}
</NativeHistoryHost>;
// Keep the original list viewport/offset, but restrict this root layer's
// drawing and hit area to the message body. Native chrome/composer stay in
@@ -96,9 +103,7 @@ export function RecentMessageHistoriesProvider({ children }: { children: ReactNo
style={[styles.clip, { left: entry.frame.left, top: entry.frame.top + top,
width: entry.frame.width, height: entry.frame.height - top - bottom, opacity: active ? 1 : 0 }]}>
<View style={{ position: 'absolute', top: -top, width: entry.frame.width, height: entry.frame.height }}>
- <MessageHistoryPositioning.Provider value={active && entry.ready}>
- <MessageHistoryActive.Provider value={active && entry.ready}>{entry.children}</MessageHistoryActive.Provider>
- </MessageHistoryPositioning.Provider>
+ {content}
</View>
</View>;
})}
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 86450bac41..37f8f05ca5 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -75,6 +75,7 @@ import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession
import { clampLiveRowCreatedAt, compareMessageOrder, MESSAGE_PAGE_SIZE } from '@/session/messagePaging';
import { normalizeRemoteMoney } from '@/session/remoteMoney';
import { projectLargeSettledToolInputs } from '@/session/messageToolPayloadProjection';
+import { setRemoteSessionStoreSizeSource } from '@/debug/jankMetrics';
interface DeviceShard {
deviceId: string;
@@ -713,6 +714,15 @@ const sessionListRefreshListeners = new Set<(deviceId: string) => void>();
const sessionListRefreshArmed = new Set<string>();
const sessionListRefreshSeen = new Set<string>();
const subs = new Set<() => void>();
+setRemoteSessionStoreSizeSource(() => {
+ let total = 0;
+ let max = 0;
+ for (const list of messages.values()) {
+ total += list.length;
+ max = Math.max(max, list.length);
+ }
+ return { sessions: messages.size, messages: total, maxSessionMessages: max, storeSubscribers: subs.size };
+});
const homeStatusSubs = new Set<() => void>();
const sessionMessagePreviewSubs = new Map<string, Set<() => void>>();
const pendingMessagePreviewSessionIds = new Set<string>();
@@ -1297,10 +1307,27 @@ function enforceRegularMessageBudget(): boolean {
return changed;
}
+/**
+ * A regular task nobody is looking at still receives list pushes while it runs,
+ * and running tasks are exempt from the global LRU budget. Without a per-task
+ * cap that window grows for as long as the app stays alive, and every push
+ * copies and re-sorts all of it. Keep only the latest page; reopening the task
+ * re-syncs from the host like any other trimmed window.
+ */
+function hiddenRegularWindowOverCap(sessionId: string, list: readonly RemoteMessage[]): boolean {
+ return list.length > MESSAGE_PAGE_SIZE
+ && retentionForSession(sessionId) === 'regular'
+ && !sessionMessageLifecycle.isVisible(sessionId)
+ && !sessionMessageLifecycle.hasLocalWork(sessionId);
+}
+
function applyMessageWriteRetention(sessionId: string): void {
touchSessionAccess(sessionId);
const current = messages.get(sessionId);
- if (current && retentionForSession(sessionId) === 'schedule') {
+ if (current && (
+ retentionForSession(sessionId) === 'schedule'
+ || hiddenRegularWindowOverCap(sessionId, current)
+ )) {
const trimmed = trimMessageWindow(sessionId, current);
if (!remoteMessageListsEqual(current, trimmed)) {
forgetWindowCoverage(sessionId);