Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 修复伙伴 1:1 聊天空闲时 JS 线程持续满载 (#5258)
Chris Zhang8503ece6d81c
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 8a5fd2724e..1c77bac896 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -999,6 +999,9 @@ export default function SessionScreen() {> | null>(null);const messageScreenFocusedRef = useRef(false);const messageAppActiveRef = useRef(AppState.currentState === 'active');+ // Stable: MessageRenderer re-runs its companion read acknowledgement when this changes.+ const isReadingPositionActive = useCallback(+ () => messageScreenFocusedRef.current && messageAppActiveRef.current, []);const handledMessageReloadRevisionRef = useRef(0);const [messageReloadRevision, setMessageReloadRevision] = useState(0);useFocusEffect(@@ -9550,7 +9553,7 @@ export default function SessionScreen() {</>)}scrollResetKey={sessionId}- isReadingPositionActive={() => messageScreenFocusedRef.current && messageAppActiveRef.current}+ isReadingPositionActive={isReadingPositionActive}syncingWhileEmpty={syncingWhileEmpty || chasingHiddenHistory}testID="session.messageList"/>diff --git a/apps/mobile/src/__tests__/remoteResourceCache.test.ts b/apps/mobile/src/__tests__/remoteResourceCache.test.tsindex 67340cf137..feea0e6565 100644--- a/apps/mobile/src/__tests__/remoteResourceCache.test.ts+++ b/apps/mobile/src/__tests__/remoteResourceCache.test.ts@@ -7,7 +7,7 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: {getAllKeys: vi.fn(async () => [...disk.keys()]),multiRemove: vi.fn(async (keys: string[]) => { keys.forEach((key) => disk.delete(key)); }),} }));-import { cacheRemoteResourceHome, cacheRemoteResourceItems, clearRemoteResourceCache, isRemoteResourceUnread, markRemoteResourceRead, readRemoteResourceSnapshot } from '@/device-link/remoteResourceCache';+import { cacheRemoteResourceHome, cacheRemoteResourceItems, clearRemoteResourceCache, isRemoteResourceUnread, markRemoteResourceRead, readRemoteResourceSnapshot, remoteResourceCacheRevision, subscribeRemoteResourceCache } from '@/device-link/remoteResourceCache';const rows = (deviceId: string, lastReplyAt: number) => [{key: `${deviceId}:bot:writer`, host: { deviceId, deviceName: deviceId },item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' }, display: { title: 'Writer', lastReplyAt }, revision: '1', links: [] },@@ -44,6 +44,56 @@ it('keeps device-qualified read positions and treats only later host replies asexpect(isRemoteResourceUnread('alice', 'home', 'writer', 200)).toBe(false);expect((await readRemoteResourceSnapshot('bob')).items).toEqual({});});+it('stays silent when a read mark or roster refresh leaves the cache unchanged', async () => {+ const { default: storage } = await import('@react-native-async-storage/async-storage');+ await cacheRemoteResourceItems('alice', 'teammates', rows('home', 100));+ const listener = vi.fn();+ const unsubscribe = subscribeRemoteResourceCache(listener);+ const revision = remoteResourceCacheRevision();+ vi.mocked(storage.setItem).mockClear();+ try {+ // An open companion chat re-acknowledges the same reply on every render; these+ // must not notify subscribers, or the re-render acknowledges again (idle CPU loop).+ await markRemoteResourceRead('alice', 'home', 'writer', 100);+ await markRemoteResourceRead('alice', 'home', 'writer', 50);+ await cacheRemoteResourceItems('alice', 'teammates', rows('home', 100));+ expect(listener).not.toHaveBeenCalled();+ expect(remoteResourceCacheRevision()).toBe(revision);+ expect(storage.setItem).not.toHaveBeenCalled();++ await cacheRemoteResourceItems('alice', 'teammates', rows('home', 200));+ expect(isRemoteResourceUnread('alice', 'home', 'writer', 200)).toBe(true);+ await markRemoteResourceRead('alice', 'home', 'writer', 200);+ expect(isRemoteResourceUnread('alice', 'home', 'writer', 200)).toBe(false);+ expect(listener).toHaveBeenCalledTimes(2);+ expect(storage.setItem).toHaveBeenCalledTimes(2);+ } finally {+ unsubscribe();+ }+});+it('retries a failed cache write on the next unchanged update without notifying', async () => {+ const { default: storage } = await import('@react-native-async-storage/async-storage');+ const persistedRead = () => JSON.parse(disk.get('cindy.remoteResources.v1.alice') ?? '{}').read?.['["home","writer"]'];+ await cacheRemoteResourceItems('alice', 'teammates', rows('home', 100));+ await cacheRemoteResourceItems('alice', 'teammates', rows('home', 200));+ vi.mocked(storage.setItem).mockRejectedValueOnce(new Error('disk full'));+ await markRemoteResourceRead('alice', 'home', 'writer', 200);+ expect(isRemoteResourceUnread('alice', 'home', 'writer', 200)).toBe(false);+ expect(persistedRead()).toBe(100);+ const listener = vi.fn();+ const unsubscribe = subscribeRemoteResourceCache(listener);+ try {+ // A later unchanged update (roster refresh or the same read mark) repairs the disk copy.+ await markRemoteResourceRead('alice', 'home', 'writer', 200);+ expect(persistedRead()).toBe(200);+ expect(listener).not.toHaveBeenCalled();+ vi.mocked(storage.setItem).mockClear();+ await cacheRemoteResourceItems('alice', 'teammates', rows('home', 200));+ expect(storage.setItem).not.toHaveBeenCalled();+ } finally {+ unsubscribe();+ }+});it('restores portable roster data after process restart and never persists runtime facts', async () => {await cacheRemoteResourceHome('alice', [{ id: 'teammates', title: 'Companions', resourceKind: 'bot', targets: [{ deviceId: 'home', deviceName: 'Home' }] }]);const items = rows('home', 100);diff --git a/apps/mobile/src/device-link/remoteResourceCache.ts b/apps/mobile/src/device-link/remoteResourceCache.tsindex 22c8dc9eaa..cfaabc906f 100644--- a/apps/mobile/src/device-link/remoteResourceCache.ts+++ b/apps/mobile/src/device-link/remoteResourceCache.ts@@ -8,6 +8,8 @@ const empty = (): Snapshot => ({ home: [], items: {}, read: {} });let epoch = 0;const writes = new Map<string, Promise<void>>();const snapshots = new Map<string, Snapshot>();+// Users whose last disk write failed; the next update retries it even when unchanged.+const unsaved = new Set<string>();const listeners = new Set<() => void>();let revision = 0;export const subscribeRemoteResourceCache = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };@@ -59,13 +61,19 @@ async function update(userId: string, change: (snapshot: Snapshot) => void): Proconst next = previous.then(async () => {const snapshot = await readRemoteResourceSnapshot(userId);if (expected !== epoch) return;+ const before = JSON.stringify(snapshot);change(snapshot);const cleaned = normalize(snapshot);- snapshots.set(userId, cleaned); emit();const raw = JSON.stringify(cleaned);+ snapshots.set(userId, cleaned);+ // An unchanged cache must stay silent: subscribers re-render on every emit, and an+ // open companion chat re-acknowledges its read position on render (a JS render loop).+ if (raw === before && !unsaved.has(userId)) return;+ if (raw !== before) emit();if (raw.length > MAX_CHARS) return;- await AsyncStorage.setItem(PREFIX + userId, raw).catch(() => undefined);- if (expected !== epoch) await AsyncStorage.removeItem(PREFIX + userId).catch(() => undefined);+ const saved = await AsyncStorage.setItem(PREFIX + userId, raw).then(() => true, () => false);+ if (expected !== epoch) { await AsyncStorage.removeItem(PREFIX + userId).catch(() => undefined); return; }+ if (saved) unsaved.delete(userId); else unsaved.add(userId);});writes.set(userId, next);await next.finally(() => { if (writes.get(userId) === next) writes.delete(userId); });@@ -100,7 +108,7 @@ export function cachedBotItem(userId: string, collectionId: string, deviceId: st&& item.ref.kind === 'bot' && item.ref.id === botId)?.item ?? null;}export async function clearRemoteResourceCache(): Promise<void> {- epoch += 1; snapshots.clear(); emit();+ epoch += 1; snapshots.clear(); unsaved.clear(); emit();await Promise.allSettled([...writes.values()]);const keys = await AsyncStorage.getAllKeys().catch(() => []);await AsyncStorage.multiRemove(keys.filter((key) => key.startsWith(PREFIX))).catch(() => undefined);