Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 统一消息文件缓存并提示存储失败
Dash2022be6b9cf7
diff --git a/apps/mobile/src/__tests__/cacheWriteNotice.test.ts b/apps/mobile/src/__tests__/cacheWriteNotice.test.tsnew file mode 100644index 0000000000..ace25819fd--- /dev/null+++ b/apps/mobile/src/__tests__/cacheWriteNotice.test.ts@@ -0,0 +1,31 @@+import { beforeEach, expect, it, vi } from 'vitest';+const state = vi.hoisted(() => ({ currentState: 'active', alert: vi.fn(), remove: vi.fn(), listener: undefined as undefined | ((state: string) => void) }));+vi.mock('react-native', () => ({+ Alert: { alert: state.alert },+ AppState: {+ get currentState() { return state.currentState; },+ addEventListener: (_: string, listener: (value: string) => void) => {+ state.listener = listener;+ return { remove: state.remove };+ },+ },+}));+vi.mock('@/i18n', () => ({ default: { t: (key: string) => key } }));+beforeEach(() => { vi.resetModules(); vi.clearAllMocks(); state.currentState = 'active'; state.listener = undefined; });+it('shows a save failure notice only once despite repeated streaming writes', async () => {+ const { notifyCacheWriteFailure } = await import('@/session/cacheWriteNotice');+ notifyCacheWriteFailure(); notifyCacheWriteFailure();+ expect(state.alert).toHaveBeenCalledTimes(1);+ expect(state.alert).toHaveBeenCalledWith('devices.list.alert.cacheSaveFailed', 'devices.list.alert.cacheSaveFailedDetail');+});+it('defers a background write failure until the user returns', async () => {+ state.currentState = 'background';+ const { notifyCacheWriteFailure } = await import('@/session/cacheWriteNotice');+ notifyCacheWriteFailure(); notifyCacheWriteFailure();+ expect(state.alert).not.toHaveBeenCalled();+ state.listener?.('inactive');+ expect(state.alert).not.toHaveBeenCalled();+ state.listener?.('active');+ expect(state.alert).toHaveBeenCalledTimes(1);+ expect(state.remove).toHaveBeenCalledTimes(1);+});diff --git a/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts b/apps/mobile/src/__tests__/homeViewPreferenceStore.test.tsindex 8488755955..ce526f4619 100644--- a/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts+++ b/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import AsyncStorage from '@react-native-async-storage/async-storage';const store = vi.hoisted(() => new Map<string, string>());@@ -25,6 +26,30 @@ const defaultPrefs = {} as const;describe('homeViewPreferenceStore', () => {+ it('does not overwrite saved grouping when the merge read fails', async () => {+ const { saveHomeViewPreferences, readHomeViewPreferences } = await import('@/session/homeViewPreferenceStore');+ await saveHomeViewPreferences({ groupByProject: false, groupDialogue: true });+ vi.mocked(AsyncStorage.getItem).mockRejectedValueOnce(new Error('read failed'));+ await expect(saveHomeViewPreferences({ selectedDevice: null })).rejects.toThrow('read failed');+ expect(await readHomeViewPreferences()).toMatchObject({ groupByProject: false, groupDialogue: true });+ });++ it('reports a failed write and lets a subsequent save succeed', async () => {+ const { saveHomeViewPreferences, readHomeViewPreferences } = await import('@/session/homeViewPreferenceStore');+ await saveHomeViewPreferences({ groupDialogue: false });+ vi.mocked(AsyncStorage.setItem).mockRejectedValueOnce(new Error('disk full'));+ await expect(saveHomeViewPreferences({ groupDialogue: true })).rejects.toThrow('disk full');+ expect((await readHomeViewPreferences()).groupDialogue).toBe(false);+ await saveHomeViewPreferences({ groupDialogue: true });+ expect((await readHomeViewPreferences()).groupDialogue).toBe(true);+ });++ it('preserves corrupt stored JSON instead of replacing it with defaults on save', async () => {+ const { __testing, saveHomeViewPreferences } = await import('@/session/homeViewPreferenceStore');+ store.set(__testing.storageKey, 'broken');+ await expect(saveHomeViewPreferences({ sortBy: 'priority' })).rejects.toThrow();+ expect(store.get(__testing.storageKey)).toBe('broken');+ });beforeEach(async () => {vi.clearAllMocks();store.clear();diff --git a/apps/mobile/src/__tests__/messageCacheStorage.test.ts b/apps/mobile/src/__tests__/messageCacheStorage.test.tsnew file mode 100644index 0000000000..1544cede98--- /dev/null+++ b/apps/mobile/src/__tests__/messageCacheStorage.test.ts@@ -0,0 +1,84 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+const notify = vi.hoisted(() => vi.fn());+vi.mock('@/session/cacheWriteNotice', () => ({ notifyCacheWriteFailure: notify }));++const state = vi.hoisted(() => ({ legacy: new Map<string, string>(), files: new Map<string, string>() }));+const io = vi.hoisted(() => ({+ read: vi.fn(async (name: string) => state.files.get(name) ?? null),+ write: vi.fn(async (name: string, value: string) => { state.files.set(name, value); }),+ remove: vi.fn(async (name: string) => { state.files.delete(name); }),+ files: vi.fn(async () => [...state.files.keys()]),+}));+vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => io }));+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {+ getItem: vi.fn(async (key: string) => state.legacy.get(key) ?? null),+ removeItem: vi.fn(async (key: string) => { state.legacy.delete(key); }),+ getAllKeys: vi.fn(async () => [...state.legacy.keys()]),+ multiRemove: vi.fn(async (keys: readonly string[]) => { keys.forEach(key => state.legacy.delete(key)); }),+} }));+import AsyncStorage from '@react-native-async-storage/async-storage';+import { messageCacheStorage as storage } from '@/session/messageCacheStorage';++beforeEach(() => { state.legacy.clear(); state.files.clear(); vi.clearAllMocks(); });+describe('message cache file migration', () => {+ it('migrates only the requested legacy entry and reads it after module restart', async () => {+ state.legacy.set('cache.a', '[1]'); state.legacy.set('cache.b', '[2]');+ expect(await storage.getItem('cache.a')).toBe('[1]');+ expect(state.files.get('cache.a.json')).toBe('[1]');+ expect(state.legacy.has('cache.a')).toBe(false);+ expect(state.legacy.get('cache.b')).toBe('[2]');+ vi.resetModules();+ const restarted = (await import('@/session/messageCacheStorage')).messageCacheStorage;+ expect(await restarted.getItem('cache.a')).toBe('[1]');+ });+ it('keeps legacy content readable if migration cannot write', async () => {+ state.legacy.set('cache.a', '[1]');+ io.write.mockRejectedValueOnce(new Error('disk full'));+ expect(await storage.getItem('cache.a')).toBe('[1]');+ expect(state.legacy.get('cache.a')).toBe('[1]');+ expect(state.files.size).toBe(0);+ expect(await storage.getItem('cache.a')).toBe('[1]');+ expect(state.legacy.size).toBe(0);+ });+ it('preserves the committed file when replacement fails', async () => {+ await storage.setItem('cache.a', 'old');+ io.write.mockRejectedValueOnce(new Error('disk full'));+ await expect(storage.setItem('cache.a', 'new')).rejects.toThrow();+ await vi.waitFor(() => expect(notify).toHaveBeenCalled());+ expect(await storage.getItem('cache.a')).toBe('old');+ });+ it('never falls back to stale legacy content after a successful replacement', async () => {+ state.legacy.set('cache.a', 'old');+ vi.mocked(AsyncStorage.removeItem).mockRejectedValueOnce(new Error('busy'));+ await storage.setItem('cache.a', 'new');+ expect(await storage.getItem('cache.a')).toBe('new');+ });+ it('keeps a deletion tombstone when legacy deletion fails', async () => {+ state.legacy.set('cache.a', 'old');+ vi.mocked(AsyncStorage.removeItem).mockRejectedValueOnce(new Error('busy'));+ await expect(storage.removeItem('cache.a')).rejects.toThrow();+ expect(await storage.getItem('cache.a')).toBe('[]');+ await storage.removeItem('cache.a');+ expect(await storage.getItem('cache.a')).toBeNull();+ });+ it('does not hide an IO failure by falling back to older data', async () => {+ state.legacy.set('cache.a', 'old');+ io.read.mockRejectedValueOnce(new Error('read failed'));+ await expect(storage.getItem('cache.a')).rejects.toThrow();+ expect(AsyncStorage.getItem).not.toHaveBeenCalled();+ });+ it('clears both backends while leaving preferences alone', async () => {+ state.legacy.set('cache.a', 'old'); state.legacy.set('preferences', 'keep');+ await storage.setItem('cache.b', 'new');+ await storage.clear('cache');+ expect(state.files.size).toBe(0);+ expect([...state.legacy]).toEqual([['preferences', 'keep']]);+ });+ it('retains files beyond 6 MB total without evicting earlier entries', async () => {+ const body = 'x'.repeat(1024 * 1024);+ for (let i = 0; i < 8; i++) await storage.setItem(`cache.${i}`, body);+ expect(state.files.size).toBe(8);+ expect(await storage.getItem('cache.0')).toBe(body);+ expect(state.legacy.size).toBe(0);+ });+});diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.tsindex 99a2bb5262..93632c532e 100644--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts@@ -6,8 +6,8 @@ import type { RemoteMessage, RemoteSession } from '@/session/types';// 内存版 AsyncStorage:覆盖 getItem/setItem/removeItem/getAllKeys/multiRemove,贴近真实 RN API。const store = vi.hoisted(() => new Map<string, string>());-vi.mock('@react-native-async-storage/async-storage', () => ({- default: {+vi.mock('@/session/messageCacheStorage', () => ({+ messageCacheStorage: {getItem: vi.fn(async (key: string) => store.get(key) ?? null),setItem: vi.fn(async (key: string, value: string) => {store.set(key, value);@@ -15,7 +15,9 @@ vi.mock('@react-native-async-storage/async-storage', () => ({removeItem: vi.fn(async (key: string) => {store.delete(key);}),- getAllKeys: vi.fn(async () => [...store.keys()]),+ clear: vi.fn(async (prefix: string) => {+ for (const key of store.keys()) if (key.startsWith(`${prefix}.`)) store.delete(key);+ }),multiRemove: vi.fn(async (keys: readonly string[]) => {for (const key of keys) store.delete(key);}),@@ -62,6 +64,44 @@ function makeSession(id: string, patch: Partial<RemoteSession> = {}): RemoteSess}describe('mobileSessionMessageCache', () => {+ it('logout waits for a migrating read and removes its late write', async () => {+ const storage = (await import('@/session/messageCacheStorage')).messageCacheStorage;+ const { getCachedSessionMessages, clearCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');+ let finish!: () => void;+ vi.mocked(storage.getItem).mockImplementationOnce(key => new Promise(resolve => {+ finish = () => {+ const text = JSON.stringify([makeMessage({ id: 'old', createdAt: isoAt(1) })]);+ store.set(key, text);+ resolve(text);+ };+ }));+ const read = getCachedSessionMessages('host-a', 'session-1');+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));+ const clear = clearCachedSessionMessages();+ finish();+ expect(await read).toEqual([]);+ await clear;+ expect(store.size).toBe(0);+ });++ it('does not deliver an old account read after switching owners', async () => {+ const storage = (await import('@/session/messageCacheStorage')).messageCacheStorage;+ const { getCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');+ const { setMobileAuthOwner } = await import('@/auth/authOwnerGeneration');+ setMobileAuthOwner('account-a');+ let finish!: () => void;+ vi.mocked(storage.getItem).mockImplementationOnce(() => new Promise(resolve => {+ finish = () => resolve(JSON.stringify([makeMessage({ id: 'old', createdAt: isoAt(1) })]));+ }));+ try {+ const read = getCachedSessionMessages('host-a', 'session-1');+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));+ setMobileAuthOwner('account-b');+ finish();+ expect(await read).toEqual([]);+ } finally { setMobileAuthOwner(null); }+ });+beforeEach(() => {store.clear();});@@ -311,7 +351,7 @@ describe('mobileSessionMessageCache', () => {});it('serializes a schedule cache clear after an already-started regular write', async () => {- const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;+ const AsyncStorage = (await import('@/session/messageCacheStorage')).messageCacheStorage;const { cacheSessionMessages, getCachedSessionMessages } =await import('@/session/mobileSessionMessageCache');let finishSetItem!: () => void;@@ -399,7 +439,7 @@ describe('mobileSessionMessageCache', () => {});it('an authoritative clear rejects a cache read that started before the clear', async () => {- const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;+ const AsyncStorage = (await import('@/session/messageCacheStorage')).messageCacheStorage;const {cacheSessionMessages,captureSessionMessageCacheWriteAuthority,@@ -432,13 +472,13 @@ describe('mobileSessionMessageCache', () => {remoteSessionStore.hydrateMessagesIfEmpty('session-1', cached, { authority: pageAuthority });}- expect(cached.map((row) => row.id)).toEqual(['stale']);+ expect(cached).toEqual([]);expect(isSessionMessageCacheWriteAuthorityCurrent(cacheAuthority)).toBe(false);expect(remoteSessionStore.getMessages('session-1')).toEqual([]);});it('logout waits for an in-flight cache write before deleting owned keys', async () => {- const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;+ const AsyncStorage = (await import('@/session/messageCacheStorage')).messageCacheStorage;const {cacheSessionMessages,clearCachedSessionMessages,@@ -466,7 +506,7 @@ describe('mobileSessionMessageCache', () => {});it('logout rejects a cache write authority captured after global clear starts', async () => {- const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;+ const AsyncStorage = (await import('@/session/messageCacheStorage')).messageCacheStorage;const {cacheSessionMessagesIfCurrent,captureSessionMessageCacheWriteAuthority,@@ -474,10 +514,9 @@ describe('mobileSessionMessageCache', () => {getCachedSessionMessages,} = await import('@/session/mobileSessionMessageCache');let finishGetAllKeys!: () => void;- vi.mocked(AsyncStorage.getAllKeys).mockImplementationOnce(() => {- const snapshot = [...store.keys()];- return new Promise<string[]>((resolve) => {- finishGetAllKeys = () => resolve(snapshot);+ vi.mocked(AsyncStorage.clear).mockImplementationOnce(() => {+ return new Promise<void>((resolve) => {+ finishGetAllKeys = () => resolve();});});diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.jsonindex cc4cc145b3..e8a93336d5 100644--- a/apps/mobile/src/i18n/locales/en/devices.json+++ b/apps/mobile/src/i18n/locales/en/devices.json@@ -296,6 +296,8 @@"noDevice": "No device available. Turn on remote control on the desktop, then sync again."},"alert": {+ "cacheSaveFailed": "Could not save offline cache",+ "cacheSaveFailedDetail": "Check the available storage on your phone. You can continue online, but some content may be unavailable offline.","actionFailed": "Action failed","renameFailed": "Rename failed","deleteTitle": "Delete session?",diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.jsonindex 07c3f05b2c..d758efc50b 100644--- a/apps/mobile/src/i18n/locales/ja/devices.json+++ b/apps/mobile/src/i18n/locales/ja/devices.json@@ -296,6 +296,8 @@"noDevice": "利用できるデバイスがありません。デスクトップでリモート操作をオンにしてから、再同期してください。"},"alert": {+ "cacheSaveFailed": "オフラインキャッシュを保存できませんでした",+ "cacheSaveFailedDetail": "端末の空き容量を確認してください。オンラインでは引き続き利用できますが、一部の内容はオフラインで表示できない場合があります。","actionFailed": "操作に失敗しました","renameFailed": "名前の変更に失敗しました","deleteTitle": "セッションを削除しますか?",diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.jsonindex 57114f1dfa..20c0e858b3 100644--- a/apps/mobile/src/i18n/locales/ko/devices.json+++ b/apps/mobile/src/i18n/locales/ko/devices.json@@ -296,6 +296,8 @@"noDevice": "사용할 수 있는 기기가 없습니다. 데스크톱에서 원격 제어를 켠 후 다시 동기화하세요."},"alert": {+ "cacheSaveFailed": "오프라인 캐시를 저장하지 못했습니다",+ "cacheSaveFailedDetail": "휴대전화의 남은 저장 공간을 확인해 주세요. 온라인에서는 계속 사용할 수 있지만 일부 콘텐츠는 오프라인에서 볼 수 없을 수 있습니다.","actionFailed": "작업 실패","renameFailed": "이름 변경 실패","deleteTitle": "세션을 삭제할까요?",diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.jsonindex 8d39e1a14b..8c59a03d43 100644--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json@@ -296,6 +296,8 @@"noDevice": "没有可用设备。请先打开桌面端远程控制,然后重新同步。"},"alert": {+ "cacheSaveFailed": "离线缓存未能保存",+ "cacheSaveFailedDetail": "请检查手机剩余存储空间。你仍可联网使用,但部分内容可能无法离线查看。","actionFailed": "操作失败","renameFailed": "重命名失败","deleteTitle": "删除任务?",diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.jsonindex ef9297589a..ba03c98e2e 100644--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json@@ -296,6 +296,8 @@"noDevice": "沒有可用裝置。請先開啟桌面端遠端控制,然後重新同步。"},"alert": {+ "cacheSaveFailed": "離線快取未能儲存",+ "cacheSaveFailedDetail": "請檢查手機剩餘儲存空間。你仍可連線使用,但部分內容可能無法離線查看。","actionFailed": "操作失敗","renameFailed": "重新命名失敗","deleteTitle": "刪除任務?",diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex 89857ba375..f90368faaf 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -1,3 +1,4 @@+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';import type { HomeMode } from './homeViewPreferenceStore';import { TaskTagDots } from '@/session/TaskTags';import { ResidentHomeList, useResidentHomeList } from './ResidentHomeList';@@ -203,7 +204,7 @@ import {} from '@/session/homeSections';import {readHomeViewPreferences,- saveHomeViewPreferences,+ saveHomeViewPreferences as persistHomeViewPreferences,type HomeViewPreferences,} from '@/session/homeViewPreferenceStore';import {@@ -403,6 +404,14 @@ function HomeScreenContent({ active = true, onModeChange, width, onDismiss, newSconst styles = useThemedStyles(makeStyles);const { colors, mode } = useTheme();const { t, i18n: i18nInstance } = useTranslation();+ const saveHomeViewPreferences = useCallback((patch: Parameters<typeof persistHomeViewPreferences>[0]) => {+ const owner = getMobileAuthOwner();+ return persistHomeViewPreferences(patch).catch(() => {+ if (isMobileAuthOwnerCurrent(owner)) {+ Alert.alert(t('devices.list.alert.actionFailed'), t('models.unified.saveFailed'));+ }+ });+ }, [t]);// 所有前进导航(进会话 / 新建 / 设置 / 组页面)统一走守卫 push:列表卡顿时的// 连点会各自触发一次裸 push,把同一页压进栈 N 层(返回也要 N 次)。const push = useGuardedPush();diff --git a/apps/mobile/src/session/cacheWriteNotice.ts b/apps/mobile/src/session/cacheWriteNotice.tsnew file mode 100644index 0000000000..237ad361f5--- /dev/null+++ b/apps/mobile/src/session/cacheWriteNotice.ts@@ -0,0 +1,20 @@+import { Alert, AppState } from 'react-native';+import i18n from '@/i18n';++let scheduled = false;++/** One notice per app run, deferred until foreground; streaming must not spam alerts. */+export function notifyCacheWriteFailure(): void {+ if (scheduled) return;+ scheduled = true;+ const show = () => Alert.alert(+ i18n.t('devices.list.alert.cacheSaveFailed'),+ i18n.t('devices.list.alert.cacheSaveFailedDetail'),+ );+ if (AppState.currentState === 'active') { show(); return; }+ const subscription = AppState.addEventListener('change', state => {+ if (state !== 'active') return;+ subscription.remove();+ show();+ });+}diff --git a/apps/mobile/src/session/historyDiskStoreExpo.ts b/apps/mobile/src/session/historyDiskStoreExpo.tsindex 1a75c2031f..982001d5bb 100644--- a/apps/mobile/src/session/historyDiskStoreExpo.ts+++ b/apps/mobile/src/session/historyDiskStoreExpo.ts@@ -2,8 +2,8 @@ import { Directory, File, Paths } from 'expo-file-system';import type { HistoryDiskIO } from './historyDiskStore';/** Discardable private app cache: survives restarts, but the OS may reclaim low-storage caches. */-export function createHistoryDiskIO(): HistoryDiskIO {- const directory = new Directory(Paths.cache, 'history-views-v1');+export function createHistoryDiskIO(directoryName = 'history-views-v1'): HistoryDiskIO {+ const directory = new Directory(Paths.cache, directoryName);return {async files() {directory.create({ intermediates: true, idempotent: true });diff --git a/apps/mobile/src/session/homeViewPreferenceStore.ts b/apps/mobile/src/session/homeViewPreferenceStore.tsindex 33d9053f4a..6dbb404e20 100644--- a/apps/mobile/src/session/homeViewPreferenceStore.ts+++ b/apps/mobile/src/session/homeViewPreferenceStore.ts@@ -30,7 +30,7 @@ export interface HomeViewPreferencePatch {}export async function readHomeViewPreferences(): Promise<HomeViewPreferences> {- const raw = await AsyncStorage.getItem(STORAGE_KEY).catch(() => null);+ const raw = await AsyncStorage.getItem(STORAGE_KEY);if (!raw) return emptyPreferences();try {return normalizeStoredPreferences(JSON.parse(raw));@@ -51,7 +51,10 @@ export function saveHomeViewPreferences(patch: HomeViewPreferencePatch): Promise}async function writeHomeViewPreferences(patch: HomeViewPreferencePatch): Promise<void> {- const current = await readHomeViewPreferences();+ // A failed read (including corrupt JSON) is not an empty preference record.+ // Preserve it rather than replacing unrelated choices with defaults.+ const raw = await AsyncStorage.getItem(STORAGE_KEY);+ const current = raw === null ? emptyPreferences() : normalizeStoredPreferences(JSON.parse(raw));const next: HomeViewPreferences = {groupByProject: patch.groupByProject ?? current.groupByProject,groupDialogue: patch.groupDialogue ?? current.groupDialogue,@@ -64,7 +67,7 @@ async function writeHomeViewPreferences(patch: HomeViewPreferencePatch): Promise? normalizeDevice(patch.selectedDevice): current.selectedDevice,};- await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(serializePreferences(next))).catch(() => undefined);+ await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(serializePreferences(next)));}export async function clearHomeViewPreferences(): Promise<void> {diff --git a/apps/mobile/src/session/messageCacheStorage.ts b/apps/mobile/src/session/messageCacheStorage.tsnew file mode 100644index 0000000000..1e1904ce1f--- /dev/null+++ b/apps/mobile/src/session/messageCacheStorage.ts@@ -0,0 +1,52 @@+import AsyncStorage from '@react-native-async-storage/async-storage';+import type { HistoryDiskIO } from './historyDiskStore';++let io: Promise<HistoryDiskIO> | undefined;+const disk = () => io ??= import('./historyDiskStoreExpo')+ .then(({ createHistoryDiskIO }) => createHistoryDiskIO('session-messages-v1'))+ .catch(error => { io = undefined; throw error; });++async function write(key: string, value: string): Promise<void> {+ try { await (await disk()).write(`${key}.json`, value); }+ catch (error) {+ void import('./cacheWriteNotice').then(module => module.notifyCacheWriteFailure()).catch(() => undefined);+ throw error;+ }+}++// Callers serialize operations per key and fence reads/writes against logout.+// Both mobile platforms use the same private cache files, with no total quota/TTL.+export const messageCacheStorage = {+ async getItem(key: string): Promise<string | null> {+ const files = await disk();+ const current = await files.read(`${key}.json`);+ if (current !== null) return current;+ const legacy = await AsyncStorage.getItem(key);+ if (legacy === null) return null;+ try {+ await write(key, legacy);+ await AsyncStorage.removeItem(key);+ } catch { /* Migration failure must leave the old cache readable. */ }+ return legacy;+ },+ async setItem(key: string, value: string): Promise<void> {+ await write(key, value);+ // Disk is authoritative even if cleanup fails; retry on the next write.+ await AsyncStorage.removeItem(key).catch(() => undefined);+ },+ async removeItem(key: string): Promise<void> {+ const files = await disk();+ // Keep a tombstone if legacy deletion fails, so fallback cannot revive it.+ await write(key, '[]');+ await AsyncStorage.removeItem(key);+ await files.remove(`${key}.json`);+ },+ async clear(prefix: string): Promise<void> {+ const files = await disk();+ const keys = (await AsyncStorage.getAllKeys()).filter(key => key.startsWith(`${prefix}.`));+ // If legacy cleanup fails, retain tombstones before propagating the error.+ for (const key of keys) await write(key, '[]');+ if (keys.length) await AsyncStorage.multiRemove(keys);+ for (const name of await files.files()) await files.remove(name);+ },+};diff --git a/apps/mobile/src/session/mobileSessionMessageCache.ts b/apps/mobile/src/session/mobileSessionMessageCache.tsindex e18fe3ad92..e65f2f5a56 100644--- a/apps/mobile/src/session/mobileSessionMessageCache.ts+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts@@ -1,9 +1,10 @@-import AsyncStorage from '@react-native-async-storage/async-storage';+import { messageCacheStorage } from './messageCacheStorage';+import { getMobileAuthOwner, isMobileAuthOwnerCurrent, type MobileAuthOwnerGeneration } from '@/auth/authOwnerGeneration';import { MESSAGE_PAGE_SIZE } from '@/session/messagePaging';import type { RemoteMessage } from '@/session/types';// 「每会话最近消息」本地缓存:冷开会话时先用上次看到的消息乐观渲染,fresh listMessages 回来后-// 对账替换。后端用 AsyncStorage(消息体放得下);key 按 (hostDeviceId, sessionId) 多设备隔离。+// 对账替换。两端统一使用独立文件缓存(不设总量或过期淘汰);key 按 (hostDeviceId, sessionId) 多设备隔离。// 关键保真度目标:缓存的消息要和 fresh 尽量逐字段一致,让 store 的 remoteMessageListsEqual 能短路、// 不触发可见的 cached→fresh 重渲染(开会话不再"闪一下")。因此:// - 保留消息的全部原始字段(不只 typed 子集),否则 store 的逐 key 比较永远不等;@@ -37,6 +38,7 @@ let activeGlobalClear: Promise<void> | null = null;export interface SessionMessageCacheWriteAuthority {readonly key: string;+ readonly owner: MobileAuthOwnerGeneration;readonly globalEpoch: number;readonly keyEpoch: number;}@@ -55,7 +57,8 @@ export function isSessionMessageCacheWriteAuthorityCurrent(authority: SessionMessageCacheWriteAuthority | null | undefined,): authority is SessionMessageCacheWriteAuthority {if (!authority) return false;- return authority.globalEpoch === globalWriteEpoch+ return isMobileAuthOwnerCurrent(authority.owner)+ && authority.globalEpoch === globalWriteEpoch&& authority.keyEpoch === (keyWriteEpochs.get(authority.key) ?? 0);}@@ -70,6 +73,7 @@ export function captureSessionMessageCacheWriteAuthority(if (!key) return null;return {key,+ owner: getMobileAuthOwner(),globalEpoch: globalWriteEpoch,keyEpoch: keyWriteEpochs.get(key) ?? 0,};@@ -88,7 +92,7 @@ export async function cacheSessionMessagesIfCurrent(await enqueueCacheOperation(authority.key, async () => {if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;if (normalized.length === 0) {- await AsyncStorage.removeItem(authority.key);+ await messageCacheStorage.removeItem(authority.key);return;}const payload: StoredSessionMessageCache = {@@ -96,7 +100,7 @@ export async function cacheSessionMessagesIfCurrent(updatedAt: Date.now(),messages: normalized,};- await AsyncStorage.setItem(authority.key, JSON.stringify(payload));+ await messageCacheStorage.setItem(authority.key, JSON.stringify(payload));});}@@ -118,22 +122,20 @@ export async function getCachedSessionMessages(deviceId: string,sessionId: string,): Promise<RemoteMessage[]> {- const key = safeStorageKey(deviceId, sessionId);- if (!key) return [];- await pendingOperations.get(key)?.catch(() => undefined);- const raw = await AsyncStorage.getItem(key).catch(() => null);- if (!raw) return [];- try {- const parsed = JSON.parse(raw) as unknown;- const list = isRecord(parsed) && Array.isArray((parsed as StoredSessionMessageCache).messages)- ? (parsed as StoredSessionMessageCache).messages- : Array.isArray(parsed)- ? parsed- : [];- return normalizeCachedMessages(list);- } catch {- return [];- }+ const authority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);+ if (!authority) return [];+ let messages: RemoteMessage[] = [];+ // Migration is a write too: include reads in the same queue as replacement/clear.+ await enqueueCacheOperation(authority.key, async () => {+ if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;+ const raw = await messageCacheStorage.getItem(authority.key);+ if (!raw || !isSessionMessageCacheWriteAuthorityCurrent(authority)) return;+ const parsed: unknown = JSON.parse(raw);+ const list = isRecord(parsed) && Array.isArray(parsed.messages)+ ? parsed.messages : Array.isArray(parsed) ? parsed : [];+ messages = normalizeCachedMessages(list);+ });+ return isSessionMessageCacheWriteAuthorityCurrent(authority) ? messages : [];}// 写入某 (host, session) 的缓存消息;保留最新 MAX 条、剥除 content 二进制大块。@@ -158,9 +160,7 @@ export function clearCachedSessionMessages(): Promise<void> {activeGlobalClear = (async () => {await Promise.all([...pendingOperations.values()].map((operation) =>operation.catch(() => undefined)));- const keys = await AsyncStorage.getAllKeys().catch(() => [] as readonly string[]);- const owned = keys.filter((key) => key.startsWith(`${STORAGE_KEY_PREFIX}.`));- if (owned.length > 0) await AsyncStorage.multiRemove(owned).catch(() => undefined);+ await messageCacheStorage.clear(STORAGE_KEY_PREFIX).catch(() => undefined);keyWriteEpochs.clear();})().finally(() => {globalClearInProgress = false;diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex 1426f10948..6ef5af1641 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -81,6 +81,23 @@ pnpm --filter mobile test:smoke## 专项入口+### 消息缓存与首页偏好++- iOS、Android 的最近消息窗口统一写入私有 `cache/session-messages-v1/` 文件,+ 不设总容量或按时间淘汰;分页、内存窗口、消息净化与显式删除语义不变。+ 该目录属于可再生缓存,系统低空间回收后会从主机重新获取,不作为消息权威副本。+- 旧 AsyncStorage 消息按需迁移:仅在文件缺失时读取旧条目,成功原子写入后再删除旧值;+ 失败保留旧条目。回退到旧版不会读取新文件,会重新从主机获取消息。+ 迁移与同一任务的写入/删除共用队列,退出账号等待在途迁移后清理两种存储。+- 首页分组等偏好继续使用 AsyncStorage。合并保存时读失败不得当成空配置;写失败+ 必须向用户提示,不能把未落盘的选择当成已保存。旧消息只按需迁移,升级首次启动+ 不会立即释放所有旧数据库占用。+- 文件写入失败(含磁盘空间不足)会提示检查剩余空间,并说明离线内容可能不完整。+ 同一次启动最多提示一次,后台失败延后到前台提示;不把所有 I/O 错误都断言为磁盘已满。++实现见 `src/session/messageCacheStorage.ts`、`mobileSessionMessageCache.ts`、+`homeViewPreferenceStore.ts`,回归见 `src/__tests__/` 下对应测试。+### 中国大陆版微信个人登录- 复用 `xdt-wechat-login`:iOS/Android 拉起微信取临时 code,再由 auth-server 交换。