Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): bound Home startup cache reads (#1556)
天魔b9ac8332898b
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsxindex 0781d11177..0102a1d9ce 100644--- a/apps/mobile/app/devices/index.tsx+++ b/apps/mobile/app/devices/index.tsx@@ -97,6 +97,7 @@ import {getCachedHomeListSnapshot,scheduleHomeListSnapshotPersist,} from '@/session/mobileHomeListCache';+import { startBoundedStartupRead } from '@/session/mobileHomeStartup';import { serializeNewSessionDeviceOptions } from '@/session/newSession';import {buildRemoteSessionCardPreview,@@ -195,6 +196,10 @@ export default function HomeScreen() {const scheduleIndexDeferRegistryRef = useRef(createScheduleIndexDeferRegistry());const scheduleEventVersionsRef = useRef(new Map<string, number>());const deviceIdentityCacheRef = useRef(createEmptyDeviceIdentityCache());+ // A timed-out SecureStore read may still complete. Do not persist an empty/rebuilt+ // cache until that read settles and its stored identities have been reapplied.+ const deviceIdentityCachePersistReadyRef = useRef(false);+ const deviceIdentityCachePersistPendingRef = useRef(false);// presence 补丁新鲜度:loadHome 用它判断哪些设备在 REST 快照发起后又收到过 presence-changed,// 避免用过期快照把它们改回离线(否则出现「会话都同步出来了、新建对话按钮却灰着」的卡死态)。const presenceFreshnessRef = useRef(createPresenceFreshnessTracker());@@ -267,7 +272,10 @@ export default function HomeScreen() {const reconcileDeviceViews = useCallback((nextRawDevices: readonly DeviceView[]) => {const result = reconcileDeviceIdentities(nextRawDevices, deviceIdentityCacheRef.current);deviceIdentityCacheRef.current = result.cache;- if (result.cacheChanged) void saveDeviceIdentityCache(result.cache);+ if (result.cacheChanged) {+ if (deviceIdentityCachePersistReadyRef.current) void saveDeviceIdentityCache(result.cache);+ else deviceIdentityCachePersistPendingRef.current = true;+ }return result;}, []);@@ -506,13 +514,24 @@ export default function HomeScreen() {return;}let cancelled = false;- void getCachedHomeListSnapshot(homeCacheUserId)- .then((snapshot) => {- if (cancelled || lastSyncedAtRef.current !== null) return;- for (const device of snapshot) {- remoteSessionStore.hydrateDeviceSessionsIfEmpty(device.deviceId, device.deviceName, device.sessions);- updateDeviceConnectionState(device.deviceId, 'syncing');- }+ const read = startBoundedStartupRead(+ getCachedHomeListSnapshot(homeCacheUserId),+ [],+ );+ const applySnapshot = async (snapshot: Awaited<ReturnType<typeof getCachedHomeListSnapshot>>) => {+ await syncInFlightRef.current;+ if (cancelled || lastSyncedAtRef.current !== null) return;+ for (const device of snapshot) {+ remoteSessionStore.hydrateDeviceSessionsIfEmpty(device.deviceId, device.deviceName, device.sessions);+ updateDeviceConnectionState(device.deviceId, 'syncing');+ }+ };+ void read.initial+ .then((initial) => {+ void applySnapshot(initial.value);+ if (initial.timedOut) void read.completion.then((late) => {+ if (late.ok) void applySnapshot(late.value);+ });}).catch(() => undefined).finally(() => {@@ -525,18 +544,36 @@ export default function HomeScreen() {useEffect(() => {let cancelled = false;- void loadDeviceIdentityCache()- .then((cache) => {+ const read = startBoundedStartupRead(+ loadDeviceIdentityCache(),+ createEmptyDeviceIdentityCache(),+ );+ void read.initial+ .then(async (initial) => {if (cancelled) return;- deviceIdentityCacheRef.current = cache;- })- .finally(() => {- if (!cancelled) setDeviceIdentityCacheReady(true);+ deviceIdentityCacheRef.current = initial.value;+ deviceIdentityCachePersistReadyRef.current = !initial.timedOut;+ setDeviceIdentityCacheReady(true);+ if (!initial.timedOut) return;++ const late = await read.completion;+ if (cancelled) return;+ if (late.ok) {+ deviceIdentityCacheRef.current = late.value;+ deviceIdentityCachePersistReadyRef.current = true;+ const reconciled = reconcileDeviceViews(devicesRef.current);+ devicesRef.current = reconciled.devices;+ if (reconciled.viewsChanged) setDevices(reconciled.devices);+ return;+ }++ deviceIdentityCachePersistReadyRef.current = true;+ if (deviceIdentityCachePersistPendingRef.current) void saveDeviceIdentityCache(deviceIdentityCacheRef.current);});return () => {cancelled = true;};- }, []);+ }, [reconcileDeviceViews]);// 冷启动恢复上次的首页视图偏好(设备筛选 + 按项目分组);用户已手动操作过则不覆盖。useEffect(() => {diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.tsindex 329f23a0bd..34a089fc62 100644--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts@@ -1,12 +1,50 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { i18n } from '@/i18n';+import { startBoundedStartupRead } from '@/session/mobileHomeStartup';function readSource(relativePath: string): string {return readFileSync(resolve(process.cwd(), relativePath), 'utf8').replace(/\r\n/g, '\n');}+describe('mobile Home startup reads', () => {+ it('returns the local value when the read settles in time', async () => {+ const read = startBoundedStartupRead(Promise.resolve('cached'), 'fallback', 100);++ await expect(read.initial).resolves.toEqual({ timedOut: false, value: 'cached' });+ });++ it('falls back on read failure', async () => {+ const read = startBoundedStartupRead(Promise.reject(new Error('read failed')), 'fallback', 100);++ await expect(+ read.initial,+ ).resolves.toEqual({ timedOut: false, value: 'fallback' });+ await expect(read.completion).resolves.toEqual({ ok: false, value: 'fallback' });+ });++ it('falls back on timeout while preserving a late local value', async () => {+ vi.useFakeTimers();+ try {+ let finishRead: ((value: string) => void) | undefined;+ const pendingRead = new Promise<string>((resolveRead) => {+ finishRead = resolveRead;+ });+ const read = startBoundedStartupRead(pendingRead, 'fallback', 100);++ await vi.advanceTimersByTimeAsync(100);+ await expect(read.initial).resolves.toEqual({ timedOut: true, value: 'fallback' });++ finishRead?.('late-cache');+ await Promise.resolve();+ await expect(read.completion).resolves.toEqual({ ok: true, value: 'late-cache' });+ } finally {+ vi.useRealTimers();+ }+ });+});+describe('mobile home desktop-first surface', () => {it('uses the desktop-sidebar Home as the authenticated root instead of a device picker route', () => {const indexSource = readSource('app/index.tsx');@@ -343,6 +381,10 @@ describe('mobile home desktop-first surface', () => {const source = readSource('app/devices/index.tsx');expect(source).toContain('void loadHome({ visible: false });');+ expect(source).toMatch(/startBoundedStartupRead\(\s*getCachedHomeListSnapshot\(homeCacheUserId\)/);+ expect(source).toContain('await syncInFlightRef.current;');+ expect(source).toMatch(/startBoundedStartupRead\(\s*loadDeviceIdentityCache\(\)/);+ expect(source).toContain('const deviceIdentityCachePersistPendingRef = useRef(false);');// 重连(connectionEpoch 变化)必须无条件全量刷新:presence 只在变化时广播、无全量重放,// 后台漏掉的上/下线事件只能靠重连重拉 REST 快照兜底,不能再用 hydrated 标记门控挡掉。// homeListCacheHydrated 是一次性 gate(缓存种入完成后永久为 true,种入失败也置 true),diff --git a/apps/mobile/src/session/mobileHomeStartup.ts b/apps/mobile/src/session/mobileHomeStartup.tsnew file mode 100644index 0000000000..a1fffa2a75--- /dev/null+++ b/apps/mobile/src/session/mobileHomeStartup.ts@@ -0,0 +1,29 @@+export const HOME_STARTUP_LOCAL_READ_TIMEOUT_MS = 2_000;++/**+ * Bounds best-effort local reads that must not block the first remote Home sync.+ * The native operation is left alone after timeout and remains available through+ * completion so callers can safely reconcile a late value.+ */+export function startBoundedStartupRead<T>(+ operation: PromiseLike<T>,+ fallback: T,+ timeoutMs: number = HOME_STARTUP_LOCAL_READ_TIMEOUT_MS,+) {+ const completion = Promise.resolve(operation)+ .then((value) => ({ ok: true as const, value }))+ .catch(() => ({ ok: false as const, value: fallback }));+ const initial = new Promise<{ timedOut: boolean; value: T }>((resolve) => {+ let settled = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const finish = (result: { timedOut: boolean; value: T }) => {+ if (settled) return;+ settled = true;+ if (timer !== undefined) clearTimeout(timer);+ resolve(result);+ };+ timer = setTimeout(() => finish({ timedOut: true, value: fallback }), timeoutMs);+ void completion.then((result) => finish({ timedOut: false, value: result.value }));+ });+ return { completion, initial };+}