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): 安卓本地库写满时清理旧消息缓存并重试发送 (#5404)

Dashd460df8c17e6
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 1949ceb90c..6cf047a82d 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -51,6 +51,7 @@ import {
useStartupSplash,
} from '@/components/StartupSplashOverlay';
import { registerDevCacheMenu } from '@/debug/devCacheMenu';
+import { migrateLegacySessionMessageCache } from '@/session/mobileSessionMessageCache';
import { startJsStallWatchdog } from '@/debug/jsStallWatchdog';
import { initMobileTapdb } from '@/analytics/mobileTapdb';
import {
@@ -404,6 +405,11 @@ function RootLayout() {
useEffect(() => {
registerDevCacheMenu();
}, []);
+ // 旧版写在 AsyncStorage 的消息缓存会把安卓 6 MiB 库占满、导致发送失败(#5403);
+ // 消息缓存已改存文件,启动时把剩余旧副本迁过去、腾出库空间。
+ useEffect(() => {
+ void migrateLegacySessionMessageCache().catch(() => undefined);
+ }, []);
// Dev-only:JS 停摆探测器,把 JS 线程忙死的时间边界钉进 Metro 日志流(内部 __DEV__ gate)。
useEffect(() => startJsStallWatchdog(), []);
// 使用统计(TapDB):这里只是"尝试"初始化——用户没同意过《隐私政策》时同意闸会
diff --git a/apps/mobile/src/__tests__/asyncStorageFull.test.ts b/apps/mobile/src/__tests__/asyncStorageFull.test.ts
new file mode 100644
index 0000000000..c0e517cb55
--- /dev/null
+++ b/apps/mobile/src/__tests__/asyncStorageFull.test.ts
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
+import { isAsyncStorageFullError, withAsyncStorageFullRecovery } from '@/session/asyncStorageFull';
+
+const FULL = new Error('database or disk is full (code 13 SQLITE_FULL)');
+const data = new Map<string, string>();
+const base = {
+ getAllKeys: vi.fn(async () => [...data.keys()]),
+ getItem: vi.fn(async (key: string) => data.get(key) ?? null),
+ setItem: vi.fn(async (key: string, value: string) => { data.set(key, value); }),
+ removeItem: vi.fn(async (key: string) => { data.delete(key); }),
+};
+const reclaim = vi.fn(async () => {});
+const storage = withAsyncStorageFullRecovery(base, reclaim);
+
+beforeEach(() => { data.clear(); vi.clearAllMocks(); });
+describe('AsyncStorage full recovery', () => {
+ it('recognizes Android SQLITE_FULL messages only', () => {
+ expect(isAsyncStorageFullError(FULL)).toBe(true);
+ expect(isAsyncStorageFullError(new Error('database is locked'))).toBe(false);
+ expect(isAsyncStorageFullError(null)).toBe(false);
+ });
+ it('reclaims rebuildable caches and retries the write once', async () => {
+ base.setItem.mockRejectedValueOnce(FULL);
+ await storage.setItem('outbox', 'record');
+ expect(reclaim).toHaveBeenCalledOnce();
+ expect(data.get('outbox')).toBe('record');
+ });
+ it('reports a readable error when the retry is still full', async () => {
+ base.setItem.mockRejectedValueOnce(FULL).mockRejectedValueOnce(FULL);
+ await expect(storage.setItem('outbox', 'record')).rejects.toMatchObject({
+ message: 'session.screen.localStorageFull', cause: FULL,
+ });
+ expect(data.has('outbox')).toBe(false);
+ });
+ it('still retries when reclaiming fails', async () => {
+ base.setItem.mockRejectedValueOnce(FULL);
+ reclaim.mockRejectedValueOnce(new Error('enumerate failed'));
+ await storage.setItem('outbox', 'record');
+ expect(data.get('outbox')).toBe('record');
+ });
+ it('passes other write failures through without reclaiming', async () => {
+ const locked = new Error('database is locked');
+ base.setItem.mockRejectedValueOnce(locked);
+ await expect(storage.setItem('outbox', 'record')).rejects.toBe(locked);
+ expect(reclaim).not.toHaveBeenCalled();
+ expect(base.setItem).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/mobile/src/__tests__/messageCacheStorage.test.ts b/apps/mobile/src/__tests__/messageCacheStorage.test.ts
index da1eb4203d..efd91f9051 100644
--- a/apps/mobile/src/__tests__/messageCacheStorage.test.ts
+++ b/apps/mobile/src/__tests__/messageCacheStorage.test.ts
@@ -119,6 +119,30 @@ describe('message cache file migration', () => {
expect(state.files.size).toBe(0);
expect([...state.legacy]).toEqual([['preferences', 'keep']]);
});
+ it('lists only legacy AsyncStorage keys, and migrateLegacy moves each into a file', async () => {
+ state.legacy.set('cache.a', '["mobile-system-pwd"]'); state.legacy.set('preferences', 'keep');
+ await storage.setItem('cache.c', 'new');
+ const keys = await storage.legacyKeys('cache');
+ expect(keys).toEqual(['cache.a']);
+ for (const key of keys) await storage.migrateLegacy(key);
+ expect([...state.legacy]).toEqual([['preferences', 'keep']]);
+ expect(state.files.get('cache.a.json')).toBe('["mobile-system-pwd"]');
+ expect(await storage.getItem('cache.c')).toBe('new');
+ });
+ it('deletes a leftover legacy copy when its file already exists', async () => {
+ state.files.set('cache.a.json', 'file');
+ state.legacy.set('cache.a', 'stale');
+ await storage.migrateLegacy('cache.a');
+ expect(state.legacy.size).toBe(0);
+ expect(state.files.get('cache.a.json')).toBe('file');
+ expect(io.write).not.toHaveBeenCalled();
+ });
+ it('keeps the legacy copy when migrating it into a file fails', async () => {
+ state.legacy.set('cache.a', 'old');
+ io.write.mockRejectedValueOnce(new Error('disk full'));
+ await storage.migrateLegacy('cache.a');
+ expect(state.legacy.get('cache.a')).toBe('old');
+ });
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);
diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
index 5165bd8e03..201f31bf88 100644
--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
@@ -18,6 +18,8 @@ vi.mock('@/session/messageCacheStorage', () => ({
clear: vi.fn(async (prefix: string) => {
for (const key of store.keys()) if (key.startsWith(`${prefix}.`)) store.delete(key);
}),
+ migrateLegacy: vi.fn(async () => {}),
+ legacyKeys: vi.fn(async (prefix: string) => [...store.keys()].filter((key) => key.startsWith(`${prefix}.`))),
multiRemove: vi.fn(async (keys: readonly string[]) => {
for (const key of keys) store.delete(key);
}),
@@ -64,6 +66,39 @@ function makeSession(id: string, patch: Partial<RemoteSession> = {}): RemoteSess
}
describe('mobileSessionMessageCache', () => {
+ it('migrates every legacy cache entry through the per-key queue, even before login', async () => {
+ const storage = (await import('@/session/messageCacheStorage')).messageCacheStorage;
+ const { migrateLegacySessionMessageCache } = await import('@/session/mobileSessionMessageCache');
+ store.set('xdt.mobileSessionMessageCache.v1.a', '[]');
+ store.set('xdt.mobileSessionMessageCache.v1.b', '[]');
+ store.set('unrelated', 'keep');
+ vi.mocked(storage.migrateLegacy).mockClear();
+ await migrateLegacySessionMessageCache();
+ expect(vi.mocked(storage.migrateLegacy).mock.calls.map(([key]) => key)).toEqual([
+ 'xdt.mobileSessionMessageCache.v1.a', 'xdt.mobileSessionMessageCache.v1.b',
+ ]);
+ expect(storage.removeItem).not.toHaveBeenCalled();
+ });
+
+ it('a logout clear cancels legacy migrations still waiting in the queue', async () => {
+ const storage = (await import('@/session/messageCacheStorage')).messageCacheStorage;
+ const { migrateLegacySessionMessageCache, clearCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');
+ store.set('xdt.mobileSessionMessageCache.v1.a', '[]');
+ let release!: () => void;
+ vi.mocked(storage.legacyKeys).mockImplementationOnce(async (prefix: string) => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ return [...store.keys()].filter((key) => key.startsWith(`${prefix}.`));
+ });
+ vi.mocked(storage.migrateLegacy).mockClear();
+ const migration = migrateLegacySessionMessageCache();
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ const clearing = clearCachedSessionMessages();
+ release();
+ await Promise.all([migration, clearing]);
+ expect(storage.migrateLegacy).not.toHaveBeenCalled();
+ expect(store.has('xdt.mobileSessionMessageCache.v1.a')).toBe(false);
+ });
+
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');
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 1c3c59695c..a4f72703a2 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -200,6 +200,7 @@
"retry": "Retry",
"firstMessageNotSent": "The first message wasn't sent; its content has been restored to the input box.",
"attachmentsNotCarriedBack": "{{count}} attachment(s) couldn't be brought back — please add them again.",
+ "localStorageFull": "Cindy's local storage on this phone is full, so the message couldn't be saved. Please try again.",
"commandWaitsForSession": "The session is still being created — this command needs the session to be ready. Please try again shortly.",
"locateMessageNotFound": "Couldn't find the message to jump to.",
"shareNoLocalImage": "Couldn't get the local image file",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 9db654fb44..a28f64ba13 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -200,6 +200,7 @@
"retry": "再試行",
"firstMessageNotSent": "最初のメッセージは送信されませんでした。内容は入力欄に復元されました。",
"attachmentsNotCarriedBack": "{{count}} 件の添付は復元できませんでした。もう一度追加してください。",
+ "localStorageFull": "このスマートフォン上の Cindy のローカルストレージがいっぱいのため、メッセージを保存できませんでした。もう一度お試しください。",
"commandWaitsForSession": "セッションの作成中です。このコマンドはセッションの準備が必要なため、少し待ってから送信してください。",
"locateMessageNotFound": "移動先のメッセージが見つかりませんでした。",
"shareNoLocalImage": "ローカルの画像ファイルを取得できませんでした",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index cc033728cf..b0d255167e 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -196,6 +196,7 @@
"retry": "다시 시도",
"firstMessageNotSent": "첫 메시지가 전송되지 않았습니다. 내용이 입력창에 복원되었습니다.",
"attachmentsNotCarriedBack": "첨부 {{count}}개는 되돌리지 못했습니다. 다시 추가해 주세요.",
+ "localStorageFull": "이 휴대폰에서 Cindy 로컬 저장 공간이 가득 차 메시지를 저장하지 못했습니다. 다시 시도해 주세요.",
"commandWaitsForSession": "세션을 만들고 있습니다. 이 명령은 세션이 준비된 뒤에 사용할 수 있습니다. 잠시 후 다시 보내 주세요.",
"locateMessageNotFound": "이동할 메시지를 찾을 수 없습니다.",
"shareNoLocalImage": "로컬 이미지 파일을 가져올 수 없습니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 5554c5cf83..e90d277d28 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -196,6 +196,7 @@
"retry": "重试",
"firstMessageNotSent": "首条消息没有发出,内容已还原到输入框。",
"attachmentsNotCarriedBack": "有 {{count}} 个附件没能一起带回,需要重新添加。",
+ "localStorageFull": "Cindy 在手机上的本地存储已满,消息没能保存,请稍后重试。",
"commandWaitsForSession": "任务还在创建中,这个命令要等任务就绪后才能用,请稍后再发。",
"locateMessageNotFound": "未找到要定位的消息。",
"shareNoLocalImage": "无法获取本地图片文件",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index cbed3efa6b..e9f639069a 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -200,6 +200,7 @@
"retry": "重試",
"firstMessageNotSent": "首條訊息沒有發出,內容已還原到輸入框。",
"attachmentsNotCarriedBack": "有 {{count}} 個附件沒能一起帶回,需要重新新增。",
+ "localStorageFull": "Cindy 在手機上的本機儲存空間已滿,訊息沒能儲存,請稍後重試。",
"commandWaitsForSession": "任務還在建立中,這個命令要等任務就緒後才能用,請稍後再發。",
"locateMessageNotFound": "未找到要定位的訊息。",
"shareNoLocalImage": "無法獲取本地圖片檔案",
diff --git a/apps/mobile/src/session/asyncStorageFull.ts b/apps/mobile/src/session/asyncStorageFull.ts
new file mode 100644
index 0000000000..787e7515f0
--- /dev/null
+++ b/apps/mobile/src/session/asyncStorageFull.ts
@@ -0,0 +1,40 @@
+import { i18n } from '@/i18n';
+import type { OutboxStorage } from './durableOutbox';
+
+// 安卓 AsyncStorage 是带 6 MiB 上限的 SQLite 库:写满时报 SQLITE_FULL,与整机剩余空间无关。
+const FULL_PATTERN = /SQLITE_FULL|database or disk is full/i;
+
+export function isAsyncStorageFullError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
+ return FULL_PATTERN.test(message);
+}
+
+/**
+ * 写满时先把旧消息缓存迁出 AsyncStorage 腾出空间,再重试一次;仍然写不进就换成人话报错,
+ * 让用户知道是手机本地存储满了,而不是电脑或整机磁盘。
+ */
+export function withAsyncStorageFullRecovery(
+ storage: OutboxStorage,
+ reclaim: () => Promise<void>,
+): OutboxStorage {
+ return {
+ getAllKeys: () => storage.getAllKeys(),
+ getItem: (key) => storage.getItem(key),
+ removeItem: (key) => storage.removeItem(key),
+ async setItem(key, value) {
+ try {
+ await storage.setItem(key, value);
+ return;
+ } catch (error) {
+ if (!isAsyncStorageFullError(error)) throw error;
+ await reclaim().catch(() => undefined);
+ }
+ try {
+ await storage.setItem(key, value);
+ } catch (error) {
+ if (!isAsyncStorageFullError(error)) throw error;
+ throw new Error(i18n.t('session.screen.localStorageFull'), { cause: error });
+ }
+ },
+ };
+}
diff --git a/apps/mobile/src/session/messageCacheStorage.ts b/apps/mobile/src/session/messageCacheStorage.ts
index 30e4675e3c..80300603ab 100644
--- a/apps/mobile/src/session/messageCacheStorage.ts
+++ b/apps/mobile/src/session/messageCacheStorage.ts
@@ -55,6 +55,18 @@ export const messageCacheStorage = {
async () => { await (await disk()).remove(`${key}.json`); },
]));
},
+ /** Keys still held in the pre-file AsyncStorage backend; migrateLegacy moves each one. */
+ async legacyKeys(prefix: string): Promise<string[]> {
+ return (await AsyncStorage.getAllKeys()).filter(key => key.startsWith(`${prefix}.`));
+ },
+ /** An existing file already wins every read, so a leftover legacy copy is only deleted. */
+ async migrateLegacy(key: string): Promise<void> {
+ if (await (await disk()).read(`${key}.json`) !== null) {
+ await AsyncStorage.removeItem(key);
+ return;
+ }
+ await messageCacheStorage.getItem(key);
+ },
async clear(prefix: string): Promise<void> {
await persist(() => removeAll([
async () => {
diff --git a/apps/mobile/src/session/mobileDurableOutbox.ts b/apps/mobile/src/session/mobileDurableOutbox.ts
index 3e8553956d..a9726063b6 100644
--- a/apps/mobile/src/session/mobileDurableOutbox.ts
+++ b/apps/mobile/src/session/mobileDurableOutbox.ts
@@ -6,8 +6,11 @@ import { outboxItemAttachments, type MobileOutboxItem } from "./sessionOutbox";
import { discardMobileUploadedAttachment } from "./mobileAttachmentUpload";
import type { RemoteSerializedAttachment } from "./types";
import { reconcileCommittedComposerDraft } from './composerDraftStore';
+import { withAsyncStorageFullRecovery } from './asyncStorageFull';
+import { migrateLegacySessionMessageCache } from './mobileSessionMessageCache';
-export const mobileDurableOutbox = createDurableOutbox(AsyncStorage, async (record, guard) => {
+const outboxStorage = withAsyncStorageFullRecovery(AsyncStorage, migrateLegacySessionMessageCache);
+export const mobileDurableOutbox = createDurableOutbox(outboxStorage, async (record, guard) => {
if (!record.draftHandoff) return;
const owner = getMobileAuthOwner();
const check = () => {
diff --git a/apps/mobile/src/session/mobileSessionMessageCache.ts b/apps/mobile/src/session/mobileSessionMessageCache.ts
index 0e96611b5d..9fa74fa7b7 100644
--- a/apps/mobile/src/session/mobileSessionMessageCache.ts
+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts
@@ -171,6 +171,22 @@ export function clearCachedSessionMessages(): Promise<void> {
return activeGlobalClear;
}
+// 文件缓存之前的版本把消息缓存写在 AsyncStorage,按需迁移只覆盖打开过的会话;未打开会话的
+// 旧副本会一直占着安卓 6 MiB 的库,挤掉发件箱 / 草稿写入(#5403)。旧副本里的 mobile-system-*
+// 卡片没有服务端副本,不能直接删,所以逐条迁成文件(成功后才删旧值;已有文件时文件为准,只删旧值)。
+// 迁移只搬运已有内容,不依赖登录身份;与同 key 写删共用队列,登出全清会让排队中的迁移作废。
+export async function migrateLegacySessionMessageCache(): Promise<void> {
+ for (const key of await messageCacheStorage.legacyKeys(STORAGE_KEY_PREFIX)) {
+ if (globalClearInProgress) return;
+ const globalEpoch = globalWriteEpoch;
+ const keyEpoch = keyWriteEpochs.get(key) ?? 0;
+ await enqueueCacheOperation(key, async () => {
+ if (globalEpoch !== globalWriteEpoch || keyEpoch !== (keyWriteEpochs.get(key) ?? 0)) return;
+ await messageCacheStorage.migrateLegacy(key);
+ });
+ }
+}
+
// 排序(升序 createdAt)+ 按 messageKey 去重(对账:同 id 保留最后一次)+ 取最新 N 条。
// mobile-system-* 没有服务端副本,必须跨窗口保留;保护行可以让软上限略微超出。
function normalizeCachedMessages(input: readonly unknown[]): RemoteMessage[] {
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 70d0e01c9f..b9db6bfb7a 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -89,6 +89,12 @@ pnpm --filter mobile test:smoke
- 旧 AsyncStorage 消息按需迁移:仅在文件缺失时读取旧条目,成功原子写入后再删除旧值;
失败保留旧条目。回退到旧版不会读取新文件,会重新从主机获取消息。
迁移与同一任务的写入/删除共用队列,退出账号等待在途迁移后清理两种存储。
+- 每次启动把剩余旧 AsyncStorage 消息条目逐条迁成文件(走同一按需迁移与按 key 队列,
+ 成功后才删旧值;同 key 已有文件时以文件为准,只删旧值):未打开会话的旧副本会占满 Android AsyncStorage 的 6 MiB 库,使发件箱、
+ 草稿写入报 `SQLITE_FULL`(#5403)。旧副本含没有服务端副本的 `mobile-system-*` 卡片,
+ 不能直接丢弃。
+- 发件箱写入遇到 `SQLITE_FULL` 时先执行上述迁移再重试一次;仍失败提示「手机本地存储已满」,
+ 不把原始 SQLite 报错直接给用户,也不清理草稿、发件箱或其他非缓存数据。
- 删除逐项尝试旧条目和文件,不依赖新增文件写入;任一后端失败不阻止另一后端清理,
单个文件失败也不阻止后续文件删除,全部尝试结束后统一报告失败。清理报错时可能仍有
无法删除的残留,不能视为清理成功。新登录或切换账号必须在持久化
@@ -96,8 +102,7 @@ pnpm --filter mobile test:smoke
退出账号仍完成凭证清除;若缓存清理失败,下次登录会先重试。无有效账号期间禁止
读取或写入消息缓存,避免退出后的卸载回调重新落盘。
- 首页分组等偏好继续使用 AsyncStorage。合并保存时读失败不得当成空配置;写失败
- 必须向用户提示,不能把未落盘的选择当成已保存。旧消息只按需迁移,升级首次启动
- 不会立即释放所有旧数据库占用。
+ 必须向用户提示,不能把未落盘的选择当成已保存。
- 文件写入失败(含磁盘空间不足)会提示检查剩余空间,并说明离线内容可能不完整。
同一次启动最多提示一次,后台失败延后到前台提示;不把所有 I/O 错误都断言为磁盘已满。