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): 清理缓存无需写入并阻止失败清理后的账号激活

Dash81c034534808
diff --git a/apps/mobile/src/__tests__/historyDiskStoreExpo.test.ts b/apps/mobile/src/__tests__/historyDiskStoreExpo.test.ts
index dce0c1a9fa..afd72ec8ce 100644
--- a/apps/mobile/src/__tests__/historyDiskStoreExpo.test.ts
+++ b/apps/mobile/src/__tests__/historyDiskStoreExpo.test.ts
@@ -1,11 +1,14 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const state = vi.hoisted(() => ({ files: new Map<string, string>(), failMove: false, failWrite: false }));
+const createDirectory = vi.hoisted(() => vi.fn());
vi.mock('expo-file-system', () => {
class Directory {
uri: string;
constructor(parent: string, name: string) { this.uri = `${parent}/${name}`; }
- create() {}
+ create() { createDirectory(); }
+ get exists() { return [...state.files.keys()].some(key => key.startsWith(`${this.uri}/`)); }
+ list() { return [...state.files.keys()].filter(key => key.startsWith(`${this.uri}/`)).map(key => new File(key)); }
}
class File {
uri: string;
@@ -13,6 +16,7 @@ vi.mock('expo-file-system', () => {
this.uri = name ? `${typeof parent === 'string' ? parent : parent.uri}/${name}` : String(parent);
}
get exists() { return state.files.has(this.uri); }
+ get name() { return this.uri.split('/').at(-1)!; }
text() { return Promise.resolve(state.files.get(this.uri)); }
delete() { state.files.delete(this.uri); }
moveSync(destination: File) {
@@ -33,8 +37,15 @@ vi.mock('expo-file-system/legacy', () => ({
}));
import { createHistoryDiskIO } from '../session/historyDiskStoreExpo';
-beforeEach(() => { state.files.clear(); state.failMove = false; state.failWrite = false; });
+beforeEach(() => { state.files.clear(); state.failMove = false; state.failWrite = false; createDirectory.mockClear(); });
describe('Expo history disk IO', () => {
+ it('enumerates missing and existing cache directories without creating anything', async () => {
+ const io = createHistoryDiskIO('session-messages-v1');
+ expect(await io.files()).toEqual([]);
+ state.files.set('file:///cache/session-messages-v1/a.json', 'old');
+ expect(await io.files()).toEqual(['a.json']);
+ expect(createDirectory).not.toHaveBeenCalled();
+ });
it('keeps committed snapshots and the index after moving the staging file', async () => {
const io = createHistoryDiskIO();
await io.write('view-a.json', 'first');
diff --git a/apps/mobile/src/__tests__/messageCacheStorage.test.ts b/apps/mobile/src/__tests__/messageCacheStorage.test.ts
index 1544cede98..ac31b99557 100644
--- a/apps/mobile/src/__tests__/messageCacheStorage.test.ts
+++ b/apps/mobile/src/__tests__/messageCacheStorage.test.ts
@@ -53,13 +53,34 @@ describe('message cache file migration', () => {
await storage.setItem('cache.a', 'new');
expect(await storage.getItem('cache.a')).toBe('new');
});
- it('keeps a deletion tombstone when legacy deletion fails', async () => {
+ it('propagates failed legacy deletion without removing the authoritative file', async () => {
state.legacy.set('cache.a', 'old');
+ state.files.set('cache.a.json', 'new');
vi.mocked(AsyncStorage.removeItem).mockRejectedValueOnce(new Error('busy'));
await expect(storage.removeItem('cache.a')).rejects.toThrow();
- expect(await storage.getItem('cache.a')).toBe('[]');
+ expect(await storage.getItem('cache.a')).toBe('new');
+ await storage.removeItem('cache.a');
+ expect(await storage.getItem('cache.a')).toBeNull();
+ });
+ it('deletes both backends without writing when the disk is full', async () => {
+ state.legacy.set('cache.a', 'old');
+ state.files.set('cache.a.json', 'new');
await storage.removeItem('cache.a');
+ expect(state.legacy.size).toBe(0);
+ expect(state.files.size).toBe(0);
+ expect(io.write).not.toHaveBeenCalled();
+ });
+ it.each(['enumerate', 'legacy', 'files'])('propagates %s cleanup failure and supports retry', async kind => {
+ state.legacy.set('cache.a', 'old');
+ state.files.set('cache.a.json', 'new');
+ const error = new Error('storage unavailable');
+ if (kind === 'enumerate') vi.mocked(AsyncStorage.getAllKeys).mockRejectedValueOnce(error);
+ if (kind === 'legacy') vi.mocked(AsyncStorage.multiRemove).mockRejectedValueOnce(error);
+ if (kind === 'files') io.remove.mockRejectedValueOnce(error);
+ await expect(storage.clear('cache')).rejects.toThrow(error);
+ await storage.clear('cache');
expect(await storage.getItem('cache.a')).toBeNull();
+ expect(io.write).not.toHaveBeenCalled();
});
it('does not hide an IO failure by falling back to older data', async () => {
state.legacy.set('cache.a', 'old');
diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
index 9bca752262..90e4d55d9d 100644
--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
@@ -511,7 +511,7 @@ describe('mobile auth-server login', () => {
);
const runtimeClear = switchBody.indexOf(
'await clearAccountScopedRuntimeForSwitch();',
- targetWrite,
+ latestRead,
);
const rollbackWrite = switchBody.indexOf(
'await restorePersistedAuthSessionRaw(previousSessionRaw);',
@@ -522,7 +522,8 @@ describe('mobile auth-server login', () => {
expect(latestRead).toBeGreaterThan(serialized);
expect(activeVaultCommit).toBeGreaterThan(latestRead);
expect(targetWrite).toBeGreaterThan(activeVaultCommit);
- expect(runtimeClear).toBeGreaterThan(targetWrite);
+ expect(runtimeClear).toBeGreaterThan(latestRead);
+ expect(runtimeClear).toBeLessThan(activeVaultCommit);
expect(rollbackWrite).toBeGreaterThan(runtimeClear);
expect(switchBody.slice(runtimeClear, rollbackWrite)).toContain(
'activateMobileSessionRealm(realm!);',
@@ -621,7 +622,7 @@ describe('mobile auth-server login', () => {
).toBeGreaterThanOrEqual(4);
});
- it('keeps the added-account vault transaction through runtime cleanup and owner commit', () => {
+ it('clears unscoped caches before persisting a new login identity', () => {
const authSource = readFileSync(
resolve(process.cwd(), 'src/auth/AuthContext.tsx'),
'utf8',
@@ -648,7 +649,7 @@ describe('mobile auth-server login', () => {
);
const runtimeClear = acceptBody.indexOf(
'await clearAccountScopedRuntimeForSwitch();',
- targetWrite,
+ previousSessionSnapshot,
);
const ownerCommit = acceptBody.indexOf(
'activateMobileSessionRealm(committedRealm);',
@@ -663,7 +664,9 @@ describe('mobile auth-server login', () => {
expect(previousSessionSnapshot).toBeGreaterThan(serialized);
expect(vaultTransaction).toBeGreaterThan(previousSessionSnapshot);
expect(targetWrite).toBeGreaterThan(vaultTransaction);
- expect(runtimeClear).toBeGreaterThan(targetWrite);
+ expect(runtimeClear).toBeGreaterThan(previousSessionSnapshot);
+ expect(runtimeClear).toBeLessThan(vaultTransaction);
+ expect(acceptBody).toContain('replacesActiveSession || userRef.current === null');
expect(ownerCommit).toBeGreaterThan(runtimeClear);
expect(rollback).toBeGreaterThan(ownerCommit);
expect(acceptBody.slice(rollback)).toContain(
diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
index 93632c532e..5165bd8e03 100644
--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
@@ -102,8 +102,32 @@ describe('mobileSessionMessageCache', () => {
} finally { setMobileAuthOwner(null); }
});
- beforeEach(() => {
+ beforeEach(async () => {
store.clear();
+ const { setMobileAuthOwner } = await import('@/auth/authOwnerGeneration');
+ setMobileAuthOwner('account-a');
+ });
+
+ it('rejects failed global cleanup and permits a later retry', async () => {
+ const storage = (await import('@/session/messageCacheStorage')).messageCacheStorage;
+ const { clearCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');
+ vi.mocked(storage.clear).mockRejectedValueOnce(new Error('delete failed'));
+ await expect(clearCachedSessionMessages()).rejects.toThrow('delete failed');
+ await expect(clearCachedSessionMessages()).resolves.toBeUndefined();
+ });
+
+ it('does not hydrate or persist while logged out or switching accounts', async () => {
+ const { setMobileAuthOwner, invalidateMobileAuthOwnerForSwitch } = await import('@/auth/authOwnerGeneration');
+ const { cacheSessionMessages, getCachedSessionMessages, captureSessionMessageCacheWriteAuthority } = await import('@/session/mobileSessionMessageCache');
+ const rows = [makeMessage({ id: 'old', createdAt: isoAt(1) })];
+ await cacheSessionMessages('host-a', 'session-1', rows);
+ for (const invalidate of [() => setMobileAuthOwner(null), invalidateMobileAuthOwnerForSwitch]) {
+ invalidate();
+ expect(captureSessionMessageCacheWriteAuthority('host-a', 'session-1')).toBeNull();
+ expect(await getCachedSessionMessages('host-a', 'session-1')).toEqual([]);
+ await cacheSessionMessages('host-a', 'new-session', rows);
+ expect(store.size).toBe(1);
+ }
});
it('round-trips cached messages for a (host, session) sorted oldest-first', async () => {
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index fd22aa3a46..e842a10f56 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -862,7 +862,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
clearAllMobileVoiceCredentials().catch(() => undefined),
clearAllMobileVoiceInputHistories().catch(() => undefined),
clearAllMobileVoiceDictionaryCaches().catch(() => undefined),
- clearCachedSessionMessages().catch(() => undefined),
+ clearCachedSessionMessages(),
clearHistoryDisk(),
clearRemoteResourceCache().catch(() => undefined),
clearCachedHomeListSnapshot().catch(() => undefined),
@@ -1074,6 +1074,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
const previousPersistedSessionRaw = await getSecureItem(AUTH_SESSION_KEY);
try {
+ // Clear unscoped caches before either durable store can name the new
+ // account. Fresh login must also retry a previously failed logout clear.
+ if (replacesActiveSession || userRef.current === null) {
+ runtimeCleanupStarted = true;
+ await clearAccountScopedRuntimeForSwitch();
+ if (authGenerationRef.current !== generation) {
+ throw authCodeError('AUTH_FLOW_SUPERSEDED');
+ }
+ assertLoginFlowCurrent(expectedLoginFlowEpoch);
+ }
await commitMobileLoginSessions(
{
pair: outcome,
@@ -1092,14 +1102,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
throw authCodeError('AUTH_FLOW_SUPERSEDED');
}
assertLoginFlowCurrent(expectedLoginFlowEpoch);
- if (replacesActiveSession) {
- runtimeCleanupStarted = true;
- await clearAccountScopedRuntimeForSwitch();
- if (authGenerationRef.current !== generation) {
- throw authCodeError('AUTH_FLOW_SUPERSEDED');
- }
- assertLoginFlowCurrent(expectedLoginFlowEpoch);
- }
await commitWithClearedAccountDeletionReceipt(() => {
if (authGenerationRef.current !== generation) {
@@ -2535,6 +2537,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// initial vault snapshot.
const previousSessionRaw = await getSecureItem(AUTH_SESSION_KEY);
try {
+ runtimeCleanupStarted = true;
+ await clearAccountScopedRuntimeForSwitch();
+ if (authGenerationRef.current !== generation) {
+ throw authCodeError('AUTH_FLOW_SUPERSEDED');
+ }
await commitMobileSavedAccountActivation(
accountKey,
async () => {
@@ -2542,11 +2549,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
if (authGenerationRef.current !== generation) {
throw authCodeError('AUTH_FLOW_SUPERSEDED');
}
- runtimeCleanupStarted = true;
- await clearAccountScopedRuntimeForSwitch();
- if (authGenerationRef.current !== generation) {
- throw authCodeError('AUTH_FLOW_SUPERSEDED');
- }
await commitWithClearedAccountDeletionReceipt(() => {
if (authGenerationRef.current !== generation) {
diff --git a/apps/mobile/src/session/historyDiskStoreExpo.ts b/apps/mobile/src/session/historyDiskStoreExpo.ts
index 982001d5bb..ec3d46e64c 100644
--- a/apps/mobile/src/session/historyDiskStoreExpo.ts
+++ b/apps/mobile/src/session/historyDiskStoreExpo.ts
@@ -6,7 +6,7 @@ export function createHistoryDiskIO(directoryName = 'history-views-v1'): History
const directory = new Directory(Paths.cache, directoryName);
return {
async files() {
- directory.create({ intermediates: true, idempotent: true });
+ if (!directory.exists) return [];
return directory.list().filter(item => item instanceof File).map(item => item.name);
},
async read(name) {
diff --git a/apps/mobile/src/session/messageCacheStorage.ts b/apps/mobile/src/session/messageCacheStorage.ts
index 1e1904ce1f..f136de7f37 100644
--- a/apps/mobile/src/session/messageCacheStorage.ts
+++ b/apps/mobile/src/session/messageCacheStorage.ts
@@ -6,14 +6,18 @@ 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); }
+async function persist(operation: () => Promise<void>): Promise<void> {
+ try { await operation(); }
catch (error) {
void import('./cacheWriteNotice').then(module => module.notifyCacheWriteFailure()).catch(() => undefined);
throw error;
}
}
+function write(key: string, value: string): Promise<void> {
+ return persist(async () => { await (await disk()).write(`${key}.json`, value); });
+}
+
// 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 = {
@@ -35,18 +39,19 @@ export const messageCacheStorage = {
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`);
+ await persist(async () => {
+ const files = await disk();
+ // Delete fallback first: deletion must not need free space for a new file.
+ 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);
+ await persist(async () => {
+ const files = await disk();
+ const keys = (await AsyncStorage.getAllKeys()).filter(key => key.startsWith(`${prefix}.`));
+ 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.ts
index e65f2f5a56..0e96611b5d 100644
--- a/apps/mobile/src/session/mobileSessionMessageCache.ts
+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts
@@ -69,11 +69,13 @@ export function captureSessionMessageCacheWriteAuthority(
// 登出全清从推进 global epoch 到 multiRemove 完成之间禁止铸造新写权。
// 否则卸载 flush 可在 getAllKeys 已取完快照后创建新 key,并晚于删除落盘。
if (globalClearInProgress) return null;
+ const owner = getMobileAuthOwner();
+ if (!owner.accountKey) return null;
const key = safeStorageKey(deviceId, sessionId);
if (!key) return null;
return {
key,
- owner: getMobileAuthOwner(),
+ owner,
globalEpoch: globalWriteEpoch,
keyEpoch: keyWriteEpochs.get(key) ?? 0,
};
@@ -160,7 +162,7 @@ export function clearCachedSessionMessages(): Promise<void> {
activeGlobalClear = (async () => {
await Promise.all([...pendingOperations.values()].map((operation) =>
operation.catch(() => undefined)));
- await messageCacheStorage.clear(STORAGE_KEY_PREFIX).catch(() => undefined);
+ await messageCacheStorage.clear(STORAGE_KEY_PREFIX);
keyWriteEpochs.clear();
})().finally(() => {
globalClearInProgress = false;
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 6ef5af1641..e8cdabe344 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -89,6 +89,10 @@ pnpm --filter mobile test:smoke
- 旧 AsyncStorage 消息按需迁移:仅在文件缺失时读取旧条目,成功原子写入后再删除旧值;
失败保留旧条目。回退到旧版不会读取新文件,会重新从主机获取消息。
迁移与同一任务的写入/删除共用队列,退出账号等待在途迁移后清理两种存储。
+- 删除先清理旧条目,再删除文件,不依赖新增文件写入。新登录或切换账号必须在持久化
+ 新身份前完成缓存清理;清理失败沿用登录错误与回滚路径,不能激活下一账号。
+ 退出账号仍完成凭证清除;若缓存清理失败,下次登录会先重试。无有效账号期间禁止
+ 读取或写入消息缓存,避免退出后的卸载回调重新落盘。
- 首页分组等偏好继续使用 AsyncStorage。合并保存时读失败不得当成空配置;写失败
必须向用户提示,不能把未落盘的选择当成已保存。旧消息只按需迁移,升级首次启动
不会立即释放所有旧数据库占用。