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(history): 限制缓存序列化并阻止降级后恢复旧投影

Dash95c4db789197
diff --git a/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts b/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts
index ddca37aa87..606f468108 100644
--- a/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts
@@ -7,6 +7,7 @@ import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
// Execute the actual consumer callbacks: a controller-only test cannot prove
// that a timer-driven budget failure refills the raw mirror on both platforms.
function callback(source: string, start: string, end: string, names: string[], values: unknown[]) {
+ source = source.replace(/\r\n/g, '\n');
const from = source.indexOf(start);
if (from < 0) throw new Error('callback start missing');
const to = source.indexOf(end, from);
@@ -17,13 +18,15 @@ function callback(source: string, start: string, end: string, names: string[], v
}
const desktop = readFileSync(fileURLToPath(new URL('../../../renderer/lib/makerChatStore.ts', import.meta.url)), 'utf8');
const mobile = readFileSync(fileURLToPath(new URL('../../../../../mobile/app/sessions/[sessionId].tsx', import.meta.url)), 'utf8');
-describe('automatic scan budget fallback owners', () => {
+describe.each(['\n', '\r\n'])('automatic scan budget fallback owners (%j)', (newline) => {
+ const desktopSource = desktop.replace(/\r?\n/g, newline);
+ const mobileSource = mobile.replace(/\r?\n/g, newline);
it.each([true, false])('Desktop refills only the current active view (active=%s)', (active) => {
const reconcile = vi.fn(async () => true);
const view = { isActive: () => active, getSnapshot: () => ({ ready: false, error: new Error('[UNSUPPORTED_CAPABILITY] History view scan budget exceeded') }) };
for (const current of [true, false]) {
reconcile.mockClear();
- callback(desktop, ' view.subscribe(() => {', '\n });\n return view;',
+ callback(desktopSource, ' view.subscribe(() => {', '\n });\n return view;',
['isCurrent', 'sessions', 'sessionId', 'view', 'isHistoryViewUnavailable', 'reconcileRemoteMessages'],
[() => current, new Set(['s']), 's', view, isHistoryViewUnavailable, reconcile]);
expect(reconcile).toHaveBeenCalledTimes(active && current ? 1 : 0);
@@ -33,7 +36,7 @@ describe('automatic scan budget fallback owners', () => {
it.each([true, false])('Mobile refills only an active unavailable view (active=%s)', (active) => {
for (const error of [null, new Error('[CHANNEL_NOT_ALLOWED] Old Host'), new Error('[INTERNAL] transient'), new Error('[UNSUPPORTED_CAPABILITY] History view scan budget exceeded')]) {
const requestSync = vi.fn();
- callback(mobile, ' // Refill the raw mirror through the same coordinator used by initial/recovery reads.\n useEffect(() => {', '\n }, [historyView.snapshot.error, historyView.view, requestSync]);',
+ callback(mobileSource, ' // Refill the raw mirror through the same coordinator used by initial/recovery reads.\n useEffect(() => {', '\n }, [historyView.snapshot.error, historyView.view, requestSync]);',
['historyView', 'isHistoryViewUnavailable', 'requestSync'],
[{ view: { isActive: () => active }, snapshot: { error } }, isHistoryViewUnavailable, requestSync]);
expect(requestSync).toHaveBeenCalledTimes(active && /UNSUPPORTED_CAPABILITY/.test(String(error)) ? 1 : 0);
diff --git a/apps/mobile/src/__tests__/historyDiskStore.test.ts b/apps/mobile/src/__tests__/historyDiskStore.test.ts
index fc1c88db42..048b249711 100644
--- a/apps/mobile/src/__tests__/historyDiskStore.test.ts
+++ b/apps/mobile/src/__tests__/historyDiskStore.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
-import { HistoryDiskStore, HISTORY_DISK_BUDGET_BYTES, type HistoryDiskIO } from '../session/historyDiskStore';
+import { HistoryDiskStore, HISTORY_DISK_BUDGET_BYTES, HISTORY_DISK_ITEM_BYTES, historyValueBytes, type HistoryDiskIO } from '../session/historyDiskStore';
function fixture(budget = 100) {
const files = new Map<string, string>();
@@ -13,6 +13,23 @@ function fixture(budget = 100) {
}
const current = () => true;
describe('history disk cache', () => {
+ it('bounds nested accounting without copying or visiting the remaining details', () => {
+ const late = vi.fn(() => 'must not visit');
+ const value = ['x'.repeat(1000), { get content() { return late(); } }];
+ expect(historyValueBytes(value, 100)).toBe(Infinity);
+ expect(late).not.toHaveBeenCalled();
+ const small = { text: '\u0000中😀', values: [null, true, 1] };
+ expect(historyValueBytes(small, 10000)).toBeGreaterThan(new TextEncoder().encode(JSON.stringify(small)).length);
+ });
+ it('rejects a giant string before encoding and does not read oversized legacy bodies', async () => {
+ const h = fixture(HISTORY_DISK_BUDGET_BYTES);
+ await h.cache.write('big', 'x'.repeat(HISTORY_DISK_ITEM_BYTES + 1), current);
+ expect(h.io.write).not.toHaveBeenCalled();
+ h.files.set('index.json', JSON.stringify({ old: { file: 'view-old.json', bytes: HISTORY_DISK_ITEM_BYTES + 1, accessed: 1 } }));
+ h.files.set('view-old.json', 'large legacy body');
+ expect(await new HistoryDiskStore(h.io).read('old', current)).toBeNull();
+ expect(h.io.read).not.toHaveBeenCalledWith('view-old.json');
+ });
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();
diff --git a/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts b/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts
index 47d7b32b83..e54f294dc4 100644
--- a/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts
+++ b/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts
@@ -20,6 +20,17 @@ const snapshot = (text: string): HistoryViewSnapshot<RemoteMessage> => ({
});
afterEach(async () => { await clearHistoryDisk(); setMobileAuthOwner(null); });
describe('persistent history integration', () => {
+ it('skips oversized snapshots before serializing complete details', async () => {
+ setMobileAuthOwner('a');
+ const auth = historyDiskAuthority('d', 's');
+ const value = snapshot('small');
+ const toJSON = vi.fn(() => { throw new Error('must not serialize'); });
+ value.details = new Map([['huge', { messages: [{ content: 'x'.repeat(2 * 1024 * 1024), toJSON }],
+ complete: true, loading: false, error: null, revision: 'r', lastMessageId: 'a' }]]) as unknown as typeof value.details;
+ await writeHistoryDisk(auth, value);
+ expect(toJSON).not.toHaveBeenCalled();
+ expect(await readHistoryDisk(auth)).toBeNull();
+ });
it('restores items, pagination and expansion while separating account ownership', async () => {
setMobileAuthOwner('a');
const auth = historyDiskAuthority('d', 's');
@@ -78,6 +89,22 @@ describe('persistent history integration', () => {
await view.refresh();
expect(JSON.stringify(view.getSnapshot())).toContain('network');
});
+ it.each(['UNSUPPORTED_CAPABILITY', 'CHANNEL_NOT_ALLOWED'])('does not restore disk after %s fallback', async (code) => {
+ const view = new HistoryViewController<RemoteMessage>({
+ page: async () => { throw new Error(`[${code}] unavailable`); },
+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),
+ expanded: async () => {},
+ });
+ let resolve!: (value: HistoryViewSnapshot<RemoteMessage>) => void;
+ const reading = view.restoreCachedView(() => new Promise(done => { resolve = done; }));
+ await view.refresh();
+ resolve(snapshot('stale disk')); await reading;
+ const read = vi.fn(async () => snapshot('stale disk'));
+ await view.restoreCachedView(read);
+ expect(read).not.toHaveBeenCalled();
+ expect(view.getSnapshot().ready).toBe(false);
+ expect(view.getSnapshot().items).toEqual([]);
+ });
it.each(['fresh', 'reset', 'deactivate'])('ignores late disk after %s', async (action) => {
const view = controller();
let resolve!: (value: HistoryViewSnapshot<RemoteMessage>) => void;
diff --git a/apps/mobile/src/session/historyDiskStore.ts b/apps/mobile/src/session/historyDiskStore.ts
index b33515c0ba..ed8d3c7111 100644
--- a/apps/mobile/src/session/historyDiskStore.ts
+++ b/apps/mobile/src/session/historyDiskStore.ts
@@ -1,5 +1,27 @@
/** Disk-only LRU. The index contains metadata, never message bodies. */
export const HISTORY_DISK_BUDGET_BYTES = 1024 * 1024 * 1024;
+export const HISTORY_DISK_ITEM_BYTES = 8 * 1024 * 1024;
+
+/** Conservative JSON/UTF-8 bound with early exit; never copies message bodies. */
+export function historyValueBytes(value: unknown, limit: number, depth = 0): number {
+ if (limit <= 0 || depth > 64) return Infinity;
+ if (typeof value === 'string') return 2 + 6 * value.length;
+ if (!value || typeof value !== 'object') return 32;
+ let bytes = 16;
+ const add = (child: unknown) => { bytes += historyValueBytes(child, limit - bytes, depth + 1) + 16; };
+ if (value instanceof Map) {
+ for (const [key, child] of value) { add(key); add(child); if (bytes > limit) return Infinity; }
+ } else if (value instanceof Set || Array.isArray(value)) {
+ for (const child of value) { add(child); if (bytes > limit) return Infinity; }
+ } else {
+ for (const key in value) {
+ if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
+ add(key); add((value as Record<string, unknown>)[key]);
+ if (bytes > limit) return Infinity;
+ }
+ }
+ return bytes;
+}
export interface HistoryDiskIO {
read(name: string): Promise<string | null>;
write(name: string, text: string): Promise<void>;
@@ -44,7 +66,7 @@ export class HistoryDiskStore {
await this.init();
if (epoch !== this.epoch || !current()) return null;
const entry = this.entries![key];
- if (!entry) return null;
+ if (!entry || entry.bytes > HISTORY_DISK_ITEM_BYTES) return null;
const text = await this.io.read(entry.file);
if (epoch !== this.epoch || !current()) return null;
if (text === null) delete this.entries![key];
@@ -54,12 +76,13 @@ export class HistoryDiskStore {
}).catch(() => null);
}
write(key: string, text: string, current: () => boolean): Promise<void> {
+ if (text.length > HISTORY_DISK_ITEM_BYTES) return Promise.resolve();
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;
+ if (epoch !== this.epoch || !current() || bytes > Math.min(this.budget, HISTORY_DISK_ITEM_BYTES)) 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; }
diff --git a/apps/mobile/src/session/remoteHistoryDiskCache.ts b/apps/mobile/src/session/remoteHistoryDiskCache.ts
index 952e7a5ef5..21ee9b8676 100644
--- a/apps/mobile/src/session/remoteHistoryDiskCache.ts
+++ b/apps/mobile/src/session/remoteHistoryDiskCache.ts
@@ -1,7 +1,7 @@
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 { HistoryDiskStore, HISTORY_DISK_ITEM_BYTES, historyValueBytes } from './historyDiskStore';
import type { RemoteMessage } from './types';
let store: Promise<HistoryDiskStore> | null = null;
@@ -66,6 +66,7 @@ export async function readHistoryDisk(authority: Authority): Promise<HistoryView
}
export async function writeHistoryDisk(authority: Authority, snapshot: HistoryViewSnapshot<RemoteMessage>): Promise<void> {
if (!authority.current() || !snapshot.ready || snapshot.loading || snapshot.error) return;
+ if (historyValueBytes([snapshot.items, snapshot.details, snapshot.expanded, snapshot.nextCursor], HISTORY_DISK_ITEM_BYTES - 1024) > HISTORY_DISK_ITEM_BYTES - 1024) return;
try {
const text = JSON.stringify({ version: 1, items: snapshot.items,
details: [...snapshot.details].filter(([, detail]) => detail.complete && !detail.loading && !detail.error),
diff --git a/apps/mobile/src/session/remoteHistoryViews.ts b/apps/mobile/src/session/remoteHistoryViews.ts
index afbe356e18..822bf91aa2 100644
--- a/apps/mobile/src/session/remoteHistoryViews.ts
+++ b/apps/mobile/src/session/remoteHistoryViews.ts
@@ -2,6 +2,7 @@ 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';
+import { historyValueBytes } from './historyDiskStore';
// Retain only recently visited views in memory. The existing account/device and
// session reclamation boundaries own invalidation. Older views remain in the disk LRU.
@@ -67,8 +68,9 @@ export function mountRemoteHistoryView(entry: Entry, reader: Reader, active: boo
const key = keyFor(entry.deviceId, entry.sessionId);
if (views.get(key) !== entry) return;
const snapshot = entry.view.getSnapshot();
- // Wire data is JSON. Count UTF-16 conservatively without retaining another copy.
- entry.bytes = 2 * JSON.stringify([snapshot.items, [...snapshot.details], [...snapshot.expanded]]).length;
+ // Bound accounting work before allocating a serialization of large details.
+ entry.bytes = Math.min(MAX_INACTIVE_HISTORY_BYTES + 1,
+ 2 * historyValueBytes([snapshot.items, snapshot.details, snapshot.expanded], MAX_INACTIVE_HISTORY_BYTES));
views.delete(key);
views.set(key, entry);
let count = 0;
diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.ts
index 219e798e09..4064d1cb3d 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -67,10 +67,10 @@ export class HistoryViewController<T extends HistoryMessageSource> {
/** 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;
+ if (this.state.ready || isHistoryViewUnavailable(this.state.error)) return;
const generation = this.generation;
const cached = await read().catch(() => null);
- if (!cached || this.state.ready || generation !== this.generation) return;
+ if (!cached || this.state.ready || isHistoryViewUnavailable(this.state.error) || generation !== this.generation) return;
this.publish({ ...cached, loading: this.state.loading, error: this.state.error });
}