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(device-link): 限制历史投影扫描并复用原读取降级

Dashbef61141255c
diff --git a/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts b/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts
new file mode 100644
index 0000000000..ddca37aa87
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts
@@ -0,0 +1,43 @@
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+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[]) {
+ const from = source.indexOf(start);
+ if (from < 0) throw new Error('callback start missing');
+ const to = source.indexOf(end, from);
+ if (to < 0) throw new Error('callback end missing');
+ const body = source.slice(from + start.length, to);
+ const js = ts.transpileModule(body, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ return new Function(...names, js)(...values);
+}
+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', () => {
+ 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;',
+ ['isCurrent', 'sessions', 'sessionId', 'view', 'isHistoryViewUnavailable', 'reconcileRemoteMessages'],
+ [() => current, new Set(['s']), 's', view, isHistoryViewUnavailable, reconcile]);
+ expect(reconcile).toHaveBeenCalledTimes(active && current ? 1 : 0);
+ if (active && current) expect(reconcile).toHaveBeenCalledWith('s', { force: true });
+ }
+ });
+ 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]);',
+ ['historyView', 'isHistoryViewUnavailable', 'requestSync'],
+ [{ view: { isActive: () => active }, snapshot: { error } }, isHistoryViewUnavailable, requestSync]);
+ expect(requestSync).toHaveBeenCalledTimes(active && /UNSUPPORTED_CAPABILITY/.test(String(error)) ? 1 : 0);
+ if (active && /UNSUPPORTED_CAPABILITY/.test(String(error))) expect(requestSync).toHaveBeenCalledWith({ reason: 'manual', replaceMessages: true });
+ }
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts b/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts
index 069995ad1c..f938dbaa88 100644
--- a/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts
@@ -82,3 +82,20 @@ describe('per-controller deferred history', () => {
expect(JSON.stringify(start).length).toBeGreaterThan(100000);
});
});
+
+it('restores raw pushes only for the disabled view and rejects its late reads/intents', () => {
+ for (const peer of ['a', 'b']) {
+ subscriptions.subscribe(peer, ['session:s']);
+ subscriptions.prepareHistoryView(peer, 's')!.update(['work']);
+ }
+ const old = subscriptions.prepareHistoryView('a', 's')!;
+ old.disable();
+ old.update(['work']);
+ old.setExpanded(['work']);
+ expect(subscriptions.hasHistoryView('a', 's')).toBe(false);
+ expect(subscriptions.projectsHistoryDetails('a', 's')).toBe(false);
+ expect(subscriptions.projectsHistoryDetails('b', 's')).toBe(true);
+ subscriptions.prepareHistoryView('a', 's')!.update(['new']);
+ old.disable();
+ expect(subscriptions.projectsHistoryDetails('a', 's')).toBe(true);
+});
diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.ts
index d4890e3a7c..d5a82e4b34 100644
--- a/apps/desktop/src/main/device-link/subscriptions.ts
+++ b/apps/desktop/src/main/device-link/subscriptions.ts
@@ -59,6 +59,9 @@ export function prepareHistoryView(deviceId: string, sessionId: string) {
historyViewsByController.set(deviceId, views);
const isCurrent = () => historyViewsByController.get(deviceId)?.get(sessionId) === view;
return {
+ disable(): void {
+ if (isCurrent()) views.delete(sessionId);
+ },
update(liveKeys: readonly string[]): void {
if (!isCurrent()) return;
view.liveKeys = [...liveKeys];
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
index 916172c9dc..e8cda055ef 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
@@ -116,3 +116,23 @@ describe('host history view', () => {
});
});
+
+describe('history scan budget', () => {
+ it('stops a boundary-free history before a twenty-first query without returning partial groups', async () => {
+ const { api, list } = reader(Array.from({ length: 2500 }, (_, i) => row(i)));
+ await expect(api.page('s')).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });
+ expect(list).toHaveBeenCalledTimes(20);
+ });
+ it('stops retained bytes before projecting a large result batch', async () => {
+ const { api, list } = reader(Array.from({ length: 150 }, (_, i) => ({ ...row(i), content: 'x'.repeat(100000) })));
+ await expect(api.page('s')).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });
+ expect(list).toHaveBeenCalledTimes(1);
+ });
+ it('applies the same budget to in-flight content', async () => {
+ const base = reader([row(0, 'user')]);
+ const api = createHistoryViewReader({ list: base.list, running: () => true,
+ live: () => [{ ...row(1), content: 'x'.repeat(8 * 1024 * 1024) }], anchor: async () => row(0, 'user') });
+ await expect(api.page('s')).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });
+ expect(base.list).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
index eda0ad1c2f..bb794b6d35 100644
--- a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
+++ b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
@@ -5,6 +5,9 @@ import {
type HistoryViewPage, type HistoryDetailPage, type HistoryWorkReference,
} from '@cindy/maker-shared/message-window';
+const MAX_HISTORY_SCAN_ROWS = 2000;
+const MAX_HISTORY_SCAN_BYTES = 8 * 1024 * 1024;
+
interface ReadOptions { limit: number; before?: string; after?: string }
export interface HistoryViewReaderDependencies<T extends HistoryMessageSource> {
list(sessionId: string, opts: ReadOptions, skipImport: boolean): Promise<T[]>;
@@ -31,10 +34,33 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
let raw: T[] = [];
let exhausted = false;
let items: HistoryViewItem<T>[] = [];
+ let scannedRows = 0;
+ let scannedBytes = 0;
+ const unavailable = () => throwIpcError('UNSUPPORTED_CAPABILITY', 'History view scan budget exceeded');
+ const liveRows = (stored: readonly T[]) => {
+ const ids = new Set(stored.map((row) => row.clientId));
+ const live: T[] = [];
+ let bytes = scannedBytes;
+ for (const row of !before ? (deps.live?.(sessionId) ?? []) : []) {
+ if (ids.has(row.clientId)) continue;
+ bytes += Buffer.byteLength(JSON.stringify(row), 'utf8');
+ if (scannedRows + live.length + 1 > MAX_HISTORY_SCAN_ROWS || bytes > MAX_HISTORY_SCAN_BYTES) unavailable();
+ live.push(row);
+ }
+ return live;
+ };
// Scan locally until the *visible* page fills. The oldest open group is
// withheld until a boundary is known, so a long run is not split per DB batch.
for (let scan = 0; ; scan++) {
+ // Never split a work group to satisfy this budget. Oversized history
+ // uses the existing raw window path; one DB batch may transiently exceed it.
+ if (scannedRows >= MAX_HISTORY_SCAN_ROWS) unavailable();
const rows = await deps.list(sessionId, { limit: 100, ...(cursor ? { before: cursor } : {}) }, scan > 0);
+ for (const row of rows) {
+ scannedRows++;
+ scannedBytes += Buffer.byteLength(JSON.stringify(row), 'utf8');
+ if (scannedRows > MAX_HISTORY_SCAN_ROWS || scannedBytes > MAX_HISTORY_SCAN_BYTES) unavailable();
+ }
if (rows.length === 0) { exhausted = true; break; }
const next = rows[rows.length - 1].id;
if (next === cursor) throwIpcError('INTERNAL', 'History cursor did not advance');
@@ -43,13 +69,13 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
exhausted = rows.length < 100;
if (!exhausted && !rows.some((row) => row.role === 'user' || row.role === 'system')) continue;
raw = chunks.slice().reverse().flat();
- const live = !before ? (deps.live?.(sessionId) ?? []).filter((row) => !raw.some((stored) => stored.clientId === row.clientId)) : [];
+ const live = liveRows(raw);
const boundary = exhausted ? 0 : raw.findIndex((row) => row.role === 'user' || row.role === 'system');
items = boundary < 0 ? [] : projectHistoryView([...raw.slice(boundary), ...live], !before && deps.running(sessionId));
if (exhausted || items.length > HISTORY_VIEW_PAGE_ITEMS) break;
}
raw = chunks.slice().reverse().flat();
- const live = !before ? (deps.live?.(sessionId) ?? []).filter((row) => !raw.some((stored) => stored.clientId === row.clientId)) : [];
+ const live = liveRows(raw);
const boundary = exhausted ? 0 : raw.findIndex((row) => row.role === 'user' || row.role === 'system');
items = boundary < 0 ? [] : projectHistoryView([...raw.slice(boundary), ...live], !before && deps.running(sessionId));
const selected: HistoryViewItem<T>[] = [];
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index c387329789..e2bd614bdf 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -23,7 +23,7 @@ import {
type SQL,
} from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
-import { historyViewLeaves } from '@cindy/maker-shared/message-window';
+import { historyViewLeaves, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
import { getDbClient } from '../client/current';
import type { ContextRebuildArgs } from '../client/tx/types';
@@ -380,7 +380,10 @@ export function registerMessageIpc(
if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
const sid = requireString(sessionId, 'sessionId');
const before = (opts as { before?: unknown } | null)?.before;
- const page = await historyView.page(sid, before == null ? undefined : requireString(before, 'before'));
+ const page = await historyView.page(sid, before == null ? undefined : requireString(before, 'before')).catch((error) => {
+ if (isHistoryViewUnavailable(error)) getDeviceLinkInvokeContext()?.historyView?.disable();
+ throw error;
+ });
if (before == null) {
const liveKeys = historyViewLeaves(page.items)
.filter((item) => item.type === 'work' && item.summary.isStreaming).map((item) => item.key);
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 67da8b3fea..a593024502 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -10723,7 +10723,12 @@ function createRemoteHistoryView(sessionId: string) {
view.subscribe(() => {
if (!isCurrent() || !sessions.has(sessionId)) return;
const snapshot = view.getSnapshot();
- if (!snapshot.ready) return;
+ if (!snapshot.ready) {
+ if (view.isActive() && isHistoryViewUnavailable(snapshot.error)) {
+ void reconcileRemoteMessages(sessionId, { force: true }).catch(() => undefined);
+ }
+ return;
+ }
const available = historyViewLeaves(snapshot.items).flatMap((item) => item.type === 'messages' ? item.messages : []);
for (const detail of snapshot.details.values()) available.push(...detail.messages);
setState(sessionId, (state) => ({ ...state, historyLoaded: true,
@@ -12458,7 +12463,14 @@ async function loadAroundMessage(
const rows = await aroundMessagesFor(sessionId, messageId, view?.getSnapshot().ready ? { radius: 0 } : opts);
if (view?.getSnapshot().ready) {
const target = rows.find((row) => row.id === messageId);
- return target ? view.locate(target.clientId, target.createdAt) : null;
+ try {
+ return target ? await view.locate(target.clientId, target.createdAt) : null;
+ } catch (error) {
+ if (!isHistoryViewUnavailable(error)) throw error;
+ if (getRemoteHistoryView(sessionId) !== view || (_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return null;
+ releaseRemoteHistoryView(sessionId, view);
+ return loadAroundMessage(sessionId, messageId, opts);
+ }
}
if (rows.length === 0) return null;
@@ -12528,7 +12540,14 @@ async function loadAroundMessageClientId(
const rows = await aroundMessagesByClientIdFor(sessionId, clientId, view?.getSnapshot().ready ? { radius: 0 } : opts);
if (view?.getSnapshot().ready) {
const target = rows.find((row) => row.clientId === clientId);
- return target ? view.locate(clientId, target.createdAt) : null;
+ try {
+ return target ? await view.locate(clientId, target.createdAt) : null;
+ } catch (error) {
+ if (!isHistoryViewUnavailable(error)) throw error;
+ if (getRemoteHistoryView(sessionId) !== view || (_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return null;
+ releaseRemoteHistoryView(sessionId, view);
+ return loadAroundMessageClientId(sessionId, clientId, opts);
+ }
}
if (rows.length === 0) return null;
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 82089d34fd..28d8a06449 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -3470,6 +3470,12 @@ export default function SessionScreen() {
(run) => syncSession(run),
remoteSyncContextKey,
);
+ // A growing turn may exceed the projection budget during an automatic refresh.
+ // Refill the raw mirror through the same coordinator used by initial/recovery reads.
+ useEffect(() => {
+ if (!historyView.view.isActive() || !/UNSUPPORTED_CAPABILITY/.test(String(historyView.snapshot.error))) return;
+ void requestSync({ reason: 'manual', replaceMessages: true });
+ }, [historyView.snapshot.error, historyView.view, requestSync]);
// A snapshot fetched before the subscription ACK can miss the gap between
// the two. Reuse the existing coordinator to reconcile after this exact ACK.
useEffect(() => {
@@ -4325,12 +4331,17 @@ export default function SessionScreen() {
appliedRouteFocusKeyRef.current = routeFocusKey;
setRouteFocusedClientId(routeFocusClientId);
})
- .catch((err) => {
+ .catch(async (err) => {
if (cancelled) return;
if (!remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) {
releasePendingRouteFocusLookup();
return;
}
+ if (isHistoryViewUnavailable(err)) {
+ releasePendingRouteFocusLookup();
+ await requestSync({ reason: 'manual', replaceMessages: true });
+ return;
+ }
setError(formatRemoteError(err));
});
@@ -4338,7 +4349,7 @@ export default function SessionScreen() {
cancelled = true;
releasePendingRouteFocusLookup();
};
- }, [deviceId, maker, messageReloadRevision, renderItems, routeFocusClientId, routeFocusKey, sessionId]);
+ }, [deviceId, maker, messageReloadRevision, renderItems, requestSync, routeFocusClientId, routeFocusKey, sessionId]);
useEffect(() => {
if (!routeFocusedItemKey || !routeFocusKey) return;
@@ -4488,6 +4499,11 @@ export default function SessionScreen() {
await historyView.view.refresh(true);
if (!historyView.view.isActive() || findRemoteHistoryView(deviceId, sessionId) !== historyView.view) return;
const error = historyView.view.getSnapshot().error;
+ if (isHistoryViewUnavailable(error)) {
+ setHistoryError(null);
+ await requestSync({ reason: 'manual', replaceMessages: true });
+ return;
+ }
setHistoryError(error ? formatRemoteError(error) : null);
return;
}
@@ -4533,7 +4549,7 @@ export default function SessionScreen() {
setLoadingEarlier(false);
}
}
- }, [historyView.snapshot.ready, historyView.view, abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);
+ }, [historyView.snapshot.ready, historyView.view, requestSync, abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);
const loadToolInput = useCallback(async (
ref: MobileToolInputProjection,
diff --git a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts
index 27e09ba1a6..b8699cba5d 100644
--- a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts
+++ b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts
@@ -22,7 +22,7 @@ describe('任务消息内存治理页面接线', () => {
expect(screen).toContain('handledMessageReloadRevisionRef.current = messageReloadRevision;');
expect(screen).toContain('const releasePendingRouteFocusLookup = () => {');
expect(screen).toContain('releasePendingRouteFocusLookup();');
- expect(screen).toContain('[deviceId, maker, messageReloadRevision, renderItems, routeFocusClientId, routeFocusKey, sessionId]');
+ expect(screen).toContain('[deviceId, maker, messageReloadRevision, renderItems, requestSync, routeFocusClientId, routeFocusKey, sessionId]');
});
it('首次进入详情在取得 authority 后触发同步,不依赖更早的 mount load', () => {
diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.ts
index 157e810299..75f8434216 100644
--- a/packages/maker-shared/src/__tests__/historyView.test.ts
+++ b/packages/maker-shared/src/__tests__/historyView.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import { projectHistoryView } from '../historyViewProjection.js';
-import { readHistoryWorkDetails, type HistoryMessageSource } from '../historyView.js';
+import { isHistoryViewUnavailable, readHistoryWorkDetails, type HistoryMessageSource } from '../historyView.js';
function row(id: number, role: string, content: unknown): HistoryMessageSource {
return { id: String(id), clientId: `c${id}`, role, content,
@@ -416,3 +416,27 @@ describe('locating folded history preserves display expansion', () => {
});
});
+
+it.each(['initial', 'older', 'refresh'])('uses existing raw fallback after a budget failure on %s', async (stage) => {
+ let fail = stage === 'initial';
+ const page = vi.fn(async () => {
+ if (fail) throw new Error('[UNSUPPORTED_CAPABILITY] History view scan budget exceeded');
+ return { version: 1 as const, items: projectHistoryView([row(1, 'user', 'hello')], false), hasMore: true, nextCursor: '1' };
+ });
+ const view = new HistoryViewController<HistoryMessageSource>({ page,
+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }), expanded: async () => undefined });
+ await view.refresh();
+ if (!fail) { fail = true; await view.refresh(stage === 'older'); }
+ expect(view.getSnapshot().ready).toBe(false);
+ expect(isHistoryViewUnavailable(view.getSnapshot().error)).toBe(true);
+ expect(view.getSnapshot().items).toEqual([]);
+ const calls = page.mock.calls.length;
+ fail = false;
+ await view.refresh();
+ view.setActive(false); view.setActive(true);
+ await view.refresh(true);
+ expect(page).toHaveBeenCalledTimes(calls);
+ view.reset(); await view.refresh();
+ expect(view.getSnapshot().ready).toBe(true);
+ view.setActive(false);
+});
diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.ts
index de66b34b5a..7b73a17386 100644
--- a/packages/maker-shared/src/historyView.ts
+++ b/packages/maker-shared/src/historyView.ts
@@ -5,7 +5,7 @@ export const HISTORY_VIEW_PAGE_BYTES = 256 * 1024;
export const HISTORY_DETAIL_PAGE_BYTES = 256 * 1024;
export function isHistoryViewUnavailable(error: unknown): boolean {
- return /CHANNEL_NOT_ALLOWED|not registered|No handler/i.test(String(error));
+ return /CHANNEL_NOT_ALLOWED|UNSUPPORTED_CAPABILITY|not registered|No handler/i.test(String(error));
}
export interface HistoryMessageSource {
diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.ts
index 4d8a51f055..c50793fb19 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -66,6 +66,9 @@ export class HistoryViewController<T extends HistoryMessageSource> {
}
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.
+ if (/UNSUPPORTED_CAPABILITY/.test(String(this.state.error))) return Promise.resolve();
if (this.pagePromise) {
// A caller after reset/reactivation must await its own generation's read,
// even when the invalidated request happened to have the same direction.