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。

feat(mobile): 为历史视图增加 1 GiB 磁盘缓存

Dash4e3df24fb8cf
diff --git a/apps/mobile/src/__tests__/historyDiskStore.test.ts b/apps/mobile/src/__tests__/historyDiskStore.test.ts
new file mode 100644
index 0000000000..fc1c88db42
--- /dev/null
+++ b/apps/mobile/src/__tests__/historyDiskStore.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi } from 'vitest';
+import { HistoryDiskStore, HISTORY_DISK_BUDGET_BYTES, type HistoryDiskIO } from '../session/historyDiskStore';
+
+function fixture(budget = 100) {
+ const files = new Map<string, string>();
+ const io: HistoryDiskIO = {
+ read: vi.fn(async name => files.get(name) ?? null),
+ write: vi.fn(async (name, text) => { files.set(name, text); }),
+ remove: vi.fn(async name => { files.delete(name); }),
+ files: vi.fn(async () => [...files.keys()]),
+ };
+ return { files, io, cache: new HistoryDiskStore(io, budget) };
+}
+const current = () => true;
+describe('history disk cache', () => {
+ it('uses a GiB budget and survives a new store without reading every body', async () => {
+ expect(HISTORY_DISK_BUDGET_BYTES).toBe(1073741824);
+ const h = fixture();
+ await h.cache.write('first', 'hello', current);
+ await h.cache.write('second', 'world', current);
+ vi.mocked(h.io.read).mockClear();
+ const restarted = new HistoryDiskStore(h.io);
+ expect(await restarted.read('first', current)).toBe('hello');
+ expect(h.io.read).toHaveBeenCalledTimes(2); // index and requested body only
+ });
+ it('retains more than eight views and evicts by actual UTF-8 bytes', async () => {
+ const h = fixture(30);
+ for (let i = 0; i < 10; i++) await h.cache.write(String(i), '中', current);
+ expect(await h.cache.read('0', current)).toBe('中');
+ await h.cache.write('big', '中'.repeat(10), current);
+ expect(await h.cache.read('0', current)).toBeNull();
+ expect(await h.cache.read('big', current)).toBe('中'.repeat(10));
+ });
+ it('does not replace a good snapshot with an oversized write', async () => {
+ const h = fixture(5);
+ await h.cache.write('s', 'good', current);
+ await h.cache.write('s', 'oversized', current);
+ expect(await h.cache.read('s', current)).toBe('good');
+ });
+ it('clears only the selected scope and survives restart', async () => {
+ const h = fixture();
+ await h.cache.write('a', 'one', current);
+ await h.cache.write('b', 'two', current);
+ await h.cache.clear(key => key === 'a');
+ const restarted = new HistoryDiskStore(h.io);
+ expect(await restarted.read('a', current)).toBeNull();
+ expect(await restarted.read('b', current)).toBe('two');
+ });
+ it('revokes an in-flight body write before clear can run', async () => {
+ const h = fixture();
+ let release!: () => void;
+ const original = h.io.write;
+ h.io.write = vi.fn(async (name, text) => {
+ if (name.startsWith('view-')) await new Promise<void>(done => { release = done; });
+ await original(name, text);
+ });
+ const write = h.cache.write('s', 'secret', current);
+ await vi.waitFor(() => expect(release).toBeDefined());
+ const clear = h.cache.clear();
+ release();
+ await Promise.all([write, clear]);
+ expect(await h.cache.read('s', current)).toBeNull();
+ expect([...h.files.keys()]).toEqual(['index.json']);
+ });
+ it('does not deliver a late read after its owner changes', async () => {
+ const h = fixture();
+ await h.cache.write('s', 'old owner', current);
+ let active = true;
+ const original = h.io.read;
+ h.io.read = async name => { const value = await original(name); active = false; return value; };
+ expect(await h.cache.read('s', () => active)).toBeNull();
+ });
+ it('recovers from a corrupt index and removes orphaned bodies', async () => {
+ const h = fixture();
+ h.files.set('index.json', '{'); h.files.set('view-orphan.json', 'discard');
+ expect(await h.cache.read('s', current)).toBeNull();
+ expect(h.files.has('view-orphan.json')).toBe(false);
+ await h.cache.write('s', 'new', current);
+ expect(await h.cache.read('s', current)).toBe('new');
+ });
+ it('keeps the previous body if committing the new index fails', async () => {
+ const h = fixture();
+ await h.cache.write('s', 'old', current);
+ const original = h.io.write;
+ h.io.write = async (name, text) => { if (name === 'index.json') throw Error('disk full'); await original(name, text); };
+ await h.cache.write('s', 'new', current);
+ h.io.write = original;
+ expect(await h.cache.read('s', current)).toBe('old');
+ });
+ it('retries a failed body deletion without losing its index entry', async () => {
+ const h = fixture();
+ await h.cache.write('s', 'private', current);
+ vi.mocked(h.io.remove).mockRejectedValueOnce(Error('temporarily busy'));
+ await expect(h.cache.clear()).rejects.toThrow('temporarily busy');
+ await h.cache.clear();
+ expect(await new HistoryDiskStore(h.io).read('s', current)).toBeNull();
+ expect([...h.files.keys()]).toEqual(['index.json']);
+ });
+});
diff --git a/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts b/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts
new file mode 100644
index 0000000000..47d7b32b83
--- /dev/null
+++ b/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { HistoryViewController, projectHistoryView, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { clearHistoryDisk, historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from '@/session/remoteHistoryDiskCache';
+import type { RemoteMessage } from '@/session/types';
+
+const files = vi.hoisted(() => new Map<string, string>());
+vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => ({
+ read: async (name: string) => files.get(name) ?? null,
+ write: async (name: string, value: string) => { files.set(name, value); },
+ remove: async (name: string) => { files.delete(name); },
+ files: async () => [...files.keys()],
+}) }));
+vi.mock('@/config/env', () => ({ getActiveMobileSessionRealm: () => 'global' }));
+const snapshot = (text: string): HistoryViewSnapshot<RemoteMessage> => ({
+ items: projectHistoryView([{ id: 'a', clientId: 'a', role: 'assistant', content: text,
+ createdAt: '2026-09-08T00:00:00Z', sessionId: 's', toolUseId: null, agentMeta: null }], false),
+ details: new Map(), expanded: new Set(), hasMore: true, nextCursor: 'older', ready: true,
+ loading: false, error: null,
+});
+afterEach(async () => { await clearHistoryDisk(); setMobileAuthOwner(null); });
+describe('persistent history integration', () => {
+ it('restores items, pagination and expansion while separating account ownership', async () => {
+ setMobileAuthOwner('a');
+ const auth = historyDiskAuthority('d', 's');
+ await writeHistoryDisk(auth, snapshot('cached'));
+ expect(await readHistoryDisk(auth)).toMatchObject({ ready: true, nextCursor: 'older', hasMore: true });
+ setMobileAuthOwner('b');
+ expect(await readHistoryDisk(historyDiskAuthority('d', 's'))).toBeNull();
+ expect(await readHistoryDisk(auth)).toBeNull();
+ setMobileAuthOwner('a');
+ expect(await readHistoryDisk(historyDiskAuthority('d', 's'))).not.toBeNull();
+ });
+ it('invalidates old writes on deletion without disabling another task cache', async () => {
+ setMobileAuthOwner('a');
+ const old = historyDiskAuthority('d', 's');
+ const other = historyDiskAuthority('d', 'other');
+ await writeHistoryDisk(old, snapshot('old'));
+ await clearHistoryDisk('d', 's');
+ await writeHistoryDisk(old, snapshot('late'));
+ await writeHistoryDisk(other, snapshot('other'));
+ expect(await readHistoryDisk(historyDiskAuthority('d', 's'))).toBeNull();
+ expect(await readHistoryDisk(other)).not.toBeNull();
+ await writeHistoryDisk(historyDiskAuthority('d', 's'), snapshot('fresh after rewind'));
+ expect(await readHistoryDisk(historyDiskAuthority('d', 's'))).not.toBeNull();
+ });
+ it('does not cache an unfinished network page or restore a live streaming flag', async () => {
+ setMobileAuthOwner('a');
+ const auth = historyDiskAuthority('d', 's');
+ await writeHistoryDisk(auth, { ...snapshot('in flight'), loading: true });
+ expect(await readHistoryDisk(auth)).toBeNull();
+ const value = snapshot('saved');
+ if (value.items[0].type === 'messages') value.items[0].messages[0].agentMeta = { isStreaming: true };
+ await writeHistoryDisk(auth, value);
+ expect(JSON.stringify(await readHistoryDisk(auth))).not.toContain('"isStreaming":true');
+ });
+ function controller() {
+ return new HistoryViewController<RemoteMessage>({
+ page: async () => ({ version: 1, items: [...snapshot('network').items], hasMore: false, nextCursor: null }),
+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),
+ expanded: async () => {},
+ });
+ }
+ it('rejects structurally corrupt work summaries instead of rendering them', async () => {
+ setMobileAuthOwner('a');
+ const auth = historyDiskAuthority('d', 's');
+ await writeHistoryDisk(auth, snapshot('good'));
+ const body = [...files.keys()].find(name => name.startsWith('view-'))!;
+ const value = JSON.parse(files.get(body)!);
+ value.items = [{ type: 'work', key: 'w', summary: { key: 'w' } }];
+ files.set(body, JSON.stringify(value));
+ expect(await readHistoryDisk(auth)).toBeNull();
+ });
+ it('shows disk before network and then accepts the authoritative page', async () => {
+ const view = controller();
+ await view.restoreCachedView(async () => snapshot('disk'));
+ expect(JSON.stringify(view.getSnapshot())).toContain('disk');
+ await view.refresh();
+ expect(JSON.stringify(view.getSnapshot())).toContain('network');
+ });
+ it.each(['fresh', 'reset', 'deactivate'])('ignores late disk after %s', async (action) => {
+ const view = controller();
+ let resolve!: (value: HistoryViewSnapshot<RemoteMessage>) => void;
+ const reading = view.restoreCachedView(() => new Promise(done => { resolve = done; }));
+ if (action === 'fresh') await view.refresh();
+ else if (action === 'reset') view.reset();
+ else view.setActive(false);
+ resolve(snapshot('stale disk')); await reading;
+ expect(JSON.stringify(view.getSnapshot())).not.toContain('stale disk');
+ });
+});
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 4e597b9c26..bc4d1b4ee9 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -120,6 +120,7 @@ import { clearRemoteResourceCache } from '@/device-link/remoteResourceCache';
import { clearCachedHomeListSnapshot } from '@/session/mobileHomeListCache';
import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { clearCachedSessionMessages } from '@/session/mobileSessionMessageCache';
+import { clearHistoryDisk } from '@/session/remoteHistoryDiskCache';
import { clearAllMobileVoiceCredentials } from '@/session/mobileVoiceCredentialStore';
import {
clearAllMobileVoiceDictionaryCaches,
@@ -850,6 +851,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
clearAllMobileVoiceInputHistories().catch(() => undefined),
clearAllMobileVoiceDictionaryCaches().catch(() => undefined),
clearCachedSessionMessages().catch(() => undefined),
+ clearHistoryDisk(),
clearRemoteResourceCache().catch(() => undefined),
clearCachedHomeListSnapshot().catch(() => undefined),
]);
@@ -2580,6 +2582,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// deviceId,不清就会让下一个账号读到上一个账号的词条并发给润色模型。
await clearAllMobileVoiceDictionaryCaches().catch(() => undefined);
await clearCachedSessionMessages().catch(() => undefined);
+ await clearHistoryDisk();
// 首页设备+会话快照与消息缓存一样属于账号数据,登出必须清掉。
await clearRemoteResourceCache().catch(() => undefined);
await clearCachedHomeListSnapshot().catch(() => undefined);
diff --git a/apps/mobile/src/session/historyDiskStore.ts b/apps/mobile/src/session/historyDiskStore.ts
new file mode 100644
index 0000000000..b33515c0ba
--- /dev/null
+++ b/apps/mobile/src/session/historyDiskStore.ts
@@ -0,0 +1,95 @@
+/** Disk-only LRU. The index contains metadata, never message bodies. */
+export const HISTORY_DISK_BUDGET_BYTES = 1024 * 1024 * 1024;
+export interface HistoryDiskIO {
+ read(name: string): Promise<string | null>;
+ write(name: string, text: string): Promise<void>;
+ remove(name: string): Promise<void>;
+ files(): Promise<string[]>;
+}
+type Entry = { file: string; bytes: number; accessed: number };
+export class HistoryDiskStore {
+ private entries: Record<string, Entry> | null = null;
+ private tail: Promise<unknown> = Promise.resolve();
+ private epoch = 0;
+ constructor(private io: HistoryDiskIO, private budget = HISTORY_DISK_BUDGET_BYTES) {}
+ private run<T>(operation: () => Promise<T>): Promise<T> {
+ const result = this.tail.then(operation);
+ // A failed remove/index write may leave orphaned files. Reconcile against disk before
+ // the next operation instead of letting repeated IO failures escape quota accounting.
+ this.tail = result.catch(() => { this.entries = null; });
+ return result;
+ }
+ private async init(): Promise<void> {
+ if (this.entries) return;
+ let parsed: unknown;
+ try { parsed = JSON.parse(await this.io.read('index.json') ?? '{}'); } catch { parsed = {}; }
+ const files = new Set(await this.io.files());
+ this.entries = Object.create(null) as Record<string, Entry>;
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ for (const [key, value] of Object.entries(parsed)) {
+ const e = value as Entry;
+ if (e && /^view-[a-z0-9-]+\.json$/.test(e.file) && files.has(e.file)
+ && Number.isFinite(e.bytes) && e.bytes > 0 && Number.isFinite(e.accessed)) this.entries[key] = e;
+ }
+ }
+ const owned = new Set(Object.values(this.entries).map(e => e.file));
+ for (const file of files) {
+ if (file !== 'index.json' && !owned.has(file)) await this.io.remove(file);
+ }
+ }
+ private persist(): Promise<void> { return this.io.write('index.json', JSON.stringify(this.entries)); }
+ read(key: string, current: () => boolean): Promise<string | null> {
+ const epoch = this.epoch;
+ return this.run(async () => {
+ await this.init();
+ if (epoch !== this.epoch || !current()) return null;
+ const entry = this.entries![key];
+ if (!entry) return null;
+ const text = await this.io.read(entry.file);
+ if (epoch !== this.epoch || !current()) return null;
+ if (text === null) delete this.entries![key];
+ else entry.accessed = Date.now();
+ await this.persist();
+ return text;
+ }).catch(() => null);
+ }
+ write(key: string, text: string, current: () => boolean): Promise<void> {
+ const epoch = this.epoch;
+ // UTF-8 bytes, rather than JS UTF-16 code units, own the disk budget.
+ const bytes = new TextEncoder().encode(text).byteLength;
+ return this.run(async () => {
+ await this.init();
+ if (epoch !== this.epoch || !current() || bytes > this.budget) return;
+ const file = `view-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}.json`;
+ await this.io.write(file, text);
+ if (epoch !== this.epoch || !current()) { await this.io.remove(file); return; }
+ const previous = { ...this.entries! };
+ const old = this.entries![key];
+ this.entries![key] = { file, bytes, accessed: Date.now() };
+ const discarded = old ? [old.file] : [];
+ let total = Object.values(this.entries!).reduce((sum, entry) => sum + entry.bytes, 0);
+ for (const [candidate, entry] of Object.entries(this.entries!).sort((a, b) => a[1].accessed - b[1].accessed)) {
+ if (total <= this.budget) break;
+ if (candidate === key) continue;
+ delete this.entries![candidate]; total -= entry.bytes; discarded.push(entry.file);
+ }
+ try { await this.persist(); }
+ catch (error) { this.entries = previous; await this.io.remove(file); throw error; }
+ for (const name of discarded) await this.io.remove(name);
+ }).catch(() => undefined);
+ }
+ clear(matches: (key: string) => boolean = () => true): Promise<void> {
+ // Revoke queued work immediately, including reads already waiting on native IO.
+ this.epoch++;
+ return this.run(async () => {
+ await this.init();
+ for (const [key, entry] of Object.entries(this.entries!)) {
+ if (!matches(key)) continue;
+ // Keep failed deletions indexed so a subsequent clear retries them.
+ await this.io.remove(entry.file);
+ delete this.entries![key];
+ }
+ await this.persist();
+ });
+ }
+}
diff --git a/apps/mobile/src/session/historyDiskStoreExpo.ts b/apps/mobile/src/session/historyDiskStoreExpo.ts
new file mode 100644
index 0000000000..aefeb96189
--- /dev/null
+++ b/apps/mobile/src/session/historyDiskStoreExpo.ts
@@ -0,0 +1,28 @@
+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');
+ return {
+ async files() {
+ directory.create({ intermediates: true, idempotent: true });
+ return directory.list().filter(item => item instanceof File).map(item => item.name);
+ },
+ async read(name) {
+ const file = new File(directory, name);
+ return file.exists ? file.text() : null;
+ },
+ async write(name, text) {
+ directory.create({ intermediates: true, idempotent: true });
+ const temporary = new File(directory, `${name}.tmp`);
+ try {
+ // Native asynchronous write avoids a synchronous filesystem write on the UI thread.
+ const fs = await import('expo-file-system/legacy');
+ await fs.writeAsStringAsync(temporary.uri, text);
+ temporary.moveSync(new File(directory, name), { overwrite: true });
+ } finally { if (temporary.exists) temporary.delete(); }
+ },
+ async remove(name) { const file = new File(directory, name); if (file.exists) file.delete(); },
+ };
+}
diff --git a/apps/mobile/src/session/remoteHistoryDiskCache.ts b/apps/mobile/src/session/remoteHistoryDiskCache.ts
new file mode 100644
index 0000000000..952e7a5ef5
--- /dev/null
+++ b/apps/mobile/src/session/remoteHistoryDiskCache.ts
@@ -0,0 +1,89 @@
+import type { HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { getActiveMobileSessionRealm } from '@/config/env';
+import { HistoryDiskStore } from './historyDiskStore';
+import type { RemoteMessage } from './types';
+
+let store: Promise<HistoryDiskStore> | null = null;
+let epoch = 0;
+const keyEpochs = new Map<string, number>();
+const disk = () => store ??= import('./historyDiskStoreExpo')
+ .then(({ createHistoryDiskIO }) => new HistoryDiskStore(createHistoryDiskIO()));
+export function historyDiskAuthority(deviceId: string, sessionId: string) {
+ const owner = getMobileAuthOwner();
+ const realm = getActiveMobileSessionRealm();
+ const generation = epoch;
+ const key = JSON.stringify([realm, owner.accountId, deviceId, sessionId]);
+ const keyEpoch = keyEpochs.get(key) ?? 0;
+ keyEpochs.set(key, keyEpoch);
+ const ownerCurrent = () => !!owner.accountId && isMobileAuthOwnerCurrent(owner) && realm === getActiveMobileSessionRealm();
+ return {
+ key,
+ ownerCurrent,
+ current: () => !!owner.accountId && !!deviceId && !!sessionId
+ && generation === epoch && keyEpoch === (keyEpochs.get(key) ?? 0)
+ && ownerCurrent(),
+ };
+}
+type Authority = ReturnType<typeof historyDiskAuthority>;
+
+function validSummary(value: unknown, depth = 0): boolean {
+ if (!value || typeof value !== 'object' || depth > 32) return false;
+ const s = value as Record<string, unknown>;
+ return ['key', 'firstMessageId', 'lastMessageId', 'revision'].every(key => typeof s[key] === 'string')
+ && ['startedAtMs', 'endedAtMs', 'messageCount', 'toolCount'].every(key => typeof s[key] === 'number' && Number.isFinite(s[key]))
+ && typeof s.isStreaming === 'boolean' && (!s.preview || validSummary(s.preview, depth + 1));
+}
+function validItems(value: unknown, depth = 0): boolean {
+ if (!Array.isArray(value) || depth > 32) return false;
+ return value.every(item => item && typeof item.key === 'string' && (
+ item.type === 'messages' ? Array.isArray(item.messages) && item.messages.every((m: RemoteMessage) =>
+ m && typeof m.id === 'string' && typeof m.clientId === 'string' && typeof m.role === 'string'
+ && typeof m.createdAt === 'string')
+ : item.type === 'work' && validSummary(item.summary)
+ && (!item.children || validItems(item.children, depth + 1))
+ ));
+}
+export async function readHistoryDisk(authority: Authority): Promise<HistoryViewSnapshot<RemoteMessage> | null> {
+ if (!authority.current()) return null;
+ try {
+ const text = await (await disk()).read(authority.key, authority.current);
+ if (!text || !authority.current()) return null;
+ const value = JSON.parse(text);
+ if (value.version !== 1 || !validItems(value.items) || typeof value.hasMore !== 'boolean'
+ || (value.nextCursor !== null && typeof value.nextCursor !== 'string')
+ || !Array.isArray(value.expanded) || !value.expanded.every((key: unknown) => typeof key === 'string')
+ || !Array.isArray(value.details) || !value.details.every((entry: unknown[]) => Array.isArray(entry)
+ && typeof entry[0] === 'string' && entry[1] && typeof entry[1] === 'object'
+ && (entry[1] as { complete: unknown }).complete === true
+ && (entry[1] as { loading: unknown }).loading === false
+ && typeof (entry[1] as { revision: unknown }).revision === 'string'
+ && typeof (entry[1] as { lastMessageId: unknown }).lastMessageId === 'string'
+ && validItems([{ type: 'messages', key: '', messages: (entry[1] as { messages: unknown }).messages }]))) return null;
+ return { ...value, details: new Map(value.details), expanded: new Set(value.expanded),
+ ready: true, loading: false, error: null };
+ } catch { return null; }
+}
+export async function writeHistoryDisk(authority: Authority, snapshot: HistoryViewSnapshot<RemoteMessage>): Promise<void> {
+ if (!authority.current() || !snapshot.ready || snapshot.loading || snapshot.error) return;
+ try {
+ const text = JSON.stringify({ version: 1, items: snapshot.items,
+ details: [...snapshot.details].filter(([, detail]) => detail.complete && !detail.loading && !detail.error),
+ expanded: [...snapshot.expanded], nextCursor: snapshot.nextCursor, hasMore: snapshot.hasMore,
+ }, (key, value) => key === 'isStreaming' ? false : value);
+ await (await disk()).write(authority.key, text, authority.current);
+ } catch { /* Cache failure must not affect reading or synchronizing. */ }
+}
+
+export function clearHistoryDisk(deviceId?: string, sessionId?: string): Promise<void> {
+ // Fence late reads, pending debounce callbacks and unmount writes synchronously.
+ const matches = (key: string) => {
+ try {
+ const [, , device, session] = JSON.parse(key);
+ return (deviceId === undefined || device === deviceId) && (sessionId === undefined || session === sessionId);
+ } catch { return true; }
+ };
+ if (deviceId === undefined && sessionId === undefined) { epoch++; keyEpochs.clear(); }
+ else for (const [key, value] of keyEpochs) if (matches(key)) keyEpochs.set(key, value + 1);
+ return disk().then(cache => cache.clear(matches)).catch(() => undefined);
+}
diff --git a/apps/mobile/src/session/remoteHistoryViews.ts b/apps/mobile/src/session/remoteHistoryViews.ts
index b1ca600bd2..afbe356e18 100644
--- a/apps/mobile/src/session/remoteHistoryViews.ts
+++ b/apps/mobile/src/session/remoteHistoryViews.ts
@@ -1,9 +1,10 @@
import { HistoryViewController } from '@cindy/maker-shared/message-window';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import type { RemoteMessage } from './types';
+import { historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from './remoteHistoryDiskCache';
// Retain only recently visited views in memory. The existing account/device and
-// session reclamation boundaries own invalidation; no second disk cache.
+// session reclamation boundaries own invalidation. Older views remain in the disk LRU.
export const MAX_INACTIVE_HISTORY_VIEWS = 8;
const MAX_INACTIVE_HISTORY_BYTES = 4 * 1024 * 1024;
type Reader = Pick<MobileMakerTransport, 'readHistoryView' | 'readWorkDetails' | 'setHistoryExpanded'>;
@@ -36,7 +37,31 @@ export function mountRemoteHistoryView(entry: Entry, reader: Reader, active: boo
entry.reader = reader;
entry.consumers++;
entry.view.setActive(active);
+ const authority = historyDiskAuthority(entry.deviceId, entry.sessionId);
+ void entry.view.restoreCachedView(() => readHistoryDisk(authority));
+ let writeAuthority = authority;
+ let pendingSnapshot = entry.view.getSnapshot();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const persist = () => {
+ if (timer) clearTimeout(timer);
+ timer = undefined;
+ void writeHistoryDisk(writeAuthority, pendingSnapshot);
+ };
+ const unsubscribe = entry.view.subscribe(() => {
+ if (timer) clearTimeout(timer);
+ const snapshot = entry.view.getSnapshot();
+ if (!snapshot.ready) pendingSnapshot = snapshot;
+ if (!authority.ownerCurrent() || !snapshot.ready || snapshot.loading || snapshot.error) return;
+ pendingSnapshot = snapshot;
+ // A new authoritative snapshot after rewind gets new write authority. Old timers/unmounts
+ // keep their old authority and cannot repopulate a cleared snapshot.
+ writeAuthority = historyDiskAuthority(entry.deviceId, entry.sessionId);
+ if (!entry.view.isActive()) { persist(); return; }
+ timer = setTimeout(persist, 1200);
+ });
return () => {
+ unsubscribe();
+ persist();
if (--entry.consumers > 0) return;
entry.view.setActive(false);
const key = keyFor(entry.deviceId, entry.sessionId);
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 81d265e7f1..4b797a13fc 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -60,6 +60,7 @@ import {
} from '@/session/sessionMessageLifecycle';
import { classifySessionRetention, type SessionRetentionKind } from '@/session/sessionRetention';
import { clearRemoteHistoryViews, resetRemoteHistoryViews } from '@/session/remoteHistoryViews';
+import { clearHistoryDisk } from '@/session/remoteHistoryDiskCache';
import { contentToPreview } from '@/utils/contentPreview';
import type { MobileSystemCardType } from '@/session/systemCard';
import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';
@@ -1028,6 +1029,7 @@ function invalidateSessionMessageWindowState(
}
function removeSessionRuntimeState(sessionId: string): void {
+ void clearHistoryDisk(undefined, sessionId);
clearRemoteHistoryViews(undefined, sessionId);
invalidateSessionMessageWindowState(sessionId, false);
emptySessionMessageStructureTokens.delete(sessionId);
@@ -3019,6 +3021,7 @@ export const remoteSessionStore = {
* 清内存与磁盘预览并登记一次刷新;页面可见时立即 load,隐藏时下次打开再拉。
*/
invalidateSessionMessageWindow(sessionId: string, deviceId?: string): void {
+ void clearHistoryDisk(deviceId, sessionId);
resetRemoteHistoryViews(deviceId, sessionId);
const changed = invalidateSessionMessageWindowState(sessionId, true);
clearSessionMessageCache(sessionId, deviceId);
@@ -3235,6 +3238,7 @@ export const remoteSessionStore = {
}
let shouldReseedAfterPatch = false;
if (patch.status === 'deleted' || patch.status === 'archived') {
+ void clearHistoryDisk(deviceId, sessionId);
clearRemoteHistoryViews(deviceId, sessionId);
shard.sessions = shard.sessions.filter((s) => s.id !== sessionId);
deleteSessionLiveActivity(sessionId);
@@ -3698,6 +3702,7 @@ export const remoteSessionStore = {
removeMessages(sessionId: string, clientIds: readonly string[], deviceId?: string): void {
const deletedClientIds = new Set(clientIds.filter(Boolean));
if (!sessionId || deletedClientIds.size === 0) return;
+ void clearHistoryDisk(deviceId, sessionId);
const tracked = new Set(inputProjections.get(sessionId)?.pendingQueue.map((item) => item.clientId) ?? []);
for (const [clientId, epoch] of inputProjectionRemoteQueuedEvidence.get(sessionId) ?? []) if (epoch > 0) tracked.add(clientId);
const settled = new Set([...deletedClientIds].filter((clientId) => tracked.has(clientId)));
@@ -4816,6 +4821,7 @@ export const remoteSessionStore = {
},
removeDevice(deviceId: string): void {
+ void clearHistoryDisk(deviceId);
clearRemoteHistoryViews(deviceId);
bumpDeviceSessionListMutationEpoch(deviceId);
const hadShard = shards.delete(deviceId);
diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.ts
index c50793fb19..219e798e09 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -65,6 +65,15 @@ export class HistoryViewController<T extends HistoryMessageSource> {
for (const listener of this.listeners) listener();
}
+ /** Optimistic local display only. A fresh response or reset always wins over disk IO. */
+ async restoreCachedView(read: () => Promise<HistoryViewSnapshot<T> | null>): Promise<void> {
+ if (this.state.ready) return;
+ const generation = this.generation;
+ const cached = await read().catch(() => null);
+ if (!cached || this.state.ready || generation !== this.generation) return;
+ this.publish({ ...cached, loading: this.state.loading, error: this.state.error });
+ }
+
refresh(older = false): Promise<void> {
// Keep the existing raw fallback until an explicit reset; a later latest
// page must not re-enable projection after an oversized older-page read.