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): 修复长任务历史扫描超限导致的上翻卡顿 (#5445)

Dashd1e7239a51d1
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 d2bd906bc8..1dfb65899e 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import { throwIpcError } from '../../../utils/ipcValidate';
import { createHistoryViewReader } from '../historyViewReader';
-import type { HistoryMessageSource } from '@cindy/maker-shared/message-window';
+import { projectHistoryView, type HistoryMessageSource, type HistoryViewItem } from '@cindy/maker-shared/message-window';
function row(n: number, role = 'thinking'): HistoryMessageSource {
return { id: String(n), clientId: `c${n}`, rowid: n, role, content: 'body '.repeat(200), createdAt: new Date(1700000000000 + n).toISOString() };
}
@@ -145,6 +145,32 @@ describe('host history view', () => {
list.mockImplementationOnce(async (...args) => { const result = await implementation(...args); source.length = 0; return result; });
await expect(api.page('s')).rejects.toMatchObject({ code: 'NOT_FOUND', message: '[NOT_FOUND] History range changed' });
});
+ it.each(['raw scan', 'outline scan', 'hydrate'])('rejects a cursor answer rewound during %s', async (phase) => {
+ const source = [row(0, 'user'), row(1),
+ { ...row(2, 'assistant'), content: 'Continuing', agentMeta: { turnCompleted: true } }, row(3),
+ { ...row(4, 'assistant'), content: '# Result\nDelivered', agentMeta: { turnCompleted: true } }];
+ const base = reader(source);
+ const read = vi.fn(async (sid: string, opts: { before?: string; limit: number }) => {
+ const rows = await base.list(sid, opts);
+ if (phase !== 'hydrate') source.pop();
+ return rows;
+ });
+ const api = createHistoryViewReader({ list: read, outline: read,
+ hydrate: async (_sid, ids) => {
+ const rows = source.filter((message) => ids.includes(message.id));
+ if (phase === 'hydrate') source.pop();
+ return rows;
+ },
+ anchor: async (_sid, id) => {
+ const found = source.find((message) => message.id === id);
+ if (!found) throwIpcError('NOT_FOUND', 'History range changed');
+ return found;
+ }, running: () => false });
+ // Only the right-hand context disappears; both scanned endpoints survive.
+ await expect(api.page('s', '4', phase !== 'raw scan'))
+ .rejects.toMatchObject({ code: 'NOT_FOUND', message: '[NOT_FOUND] History range changed' });
+ expect(source.map((message) => message.id)).toEqual(['0', '1', '2', '3']);
+ });
it.each([1000, 200000])('rejects details cleared or rewound during a batch before returning (%i bytes)', async (size) => {
for (const keep of [0, 1]) {
const source = [row(1), row(2), row(3)].map((message) => ({ ...message, content: 'x'.repeat(size) }));
@@ -171,6 +197,74 @@ describe('host history view', () => {
});
describe('history scan budget', () => {
+ it.each([
+ { outlined: false, streaming: false },
+ { outlined: true, streaming: false },
+ { outlined: true, streaming: true },
+ ])('pages completed deliveries without rescanning the entire automatic run ($outlined/$streaming)', async ({ outlined, streaming }) => {
+ let n = 0;
+ const source = [row(n++, 'user')];
+ for (let turn = 0; turn < 90; turn++) {
+ for (let step = 0; step < 50; step++) source.push({ ...row(n++), content: 'detail '.repeat(300) });
+ source.push({ ...row(n++, 'assistant'), content: 'Continuing', agentMeta: { turnCompleted: true } });
+ source.push(row(n++));
+ source.push({ ...row(n++, 'assistant'), content: '# Result\nDelivered', agentMeta: { turnCompleted: true } });
+ }
+ // An odd number of visible items makes a page start on the sealed answer,
+ // rather than always on its preceding group. The older page needs its seal.
+ source.push(row(n++, 'user'));
+ if (streaming) source.push(row(n++));
+ expect(Buffer.byteLength(JSON.stringify(source))).toBeGreaterThan(8 * 1024 * 1024);
+ const base = reader(source);
+ const api = createHistoryViewReader({ list: base.list,
+ ...(outlined ? { outline: base.list, hydrate: async (_sid: string, ids: string[]) => source.filter((r) => ids.includes(r.id)) } : {}),
+ anchor: async (_sid, id) => source.find((r) => r.id === id)!, running: () => streaming });
+ const received: HistoryViewItem<HistoryMessageSource>[] = [];
+ let before: string | undefined;
+ let pages = 0;
+ do {
+ base.list.mockClear();
+ const page = await api.page('s', before, outlined);
+ expect(page.items.length).toBeGreaterThan(0);
+ expect(base.list.mock.calls.length).toBeLessThanOrEqual(outlined ? 2 : 10);
+ received.unshift(...page.items);
+ expect(page.nextCursor).not.toBe(before);
+ before = page.nextCursor ?? undefined;
+ expect(++pages).toBeLessThan(20);
+ } while (before);
+ const withoutRevision = (items: unknown) => JSON.parse(JSON.stringify(items, (key, value) => key === 'revision' ? undefined : value));
+ expect(withoutRevision(received)).toEqual(withoutRevision(projectHistoryView(source, streaming, outlined)));
+ expect(received.flatMap((item) => item.type === 'messages' ? item.messages : [])
+ .some((message) => message.content === 'Continuing')).toBe(false);
+ });
+
+ it('stops when delivered bytes fill a page even with fewer than twenty visible items', async () => {
+ let n = 0;
+ const source = [row(n++, 'user')];
+ for (let turn = 0; turn < 40; turn++) {
+ for (let step = 0; step < 99; step++) source.push(row(n++));
+ source.push({ ...row(n++, 'assistant'), content: '# Report\n' + 'x'.repeat(200000), agentMeta: { turnCompleted: true } });
+ }
+ const base = reader(source);
+ const api = createHistoryViewReader({ list: base.list, outline: base.list,
+ hydrate: async (_sid, ids) => source.filter((r) => ids.includes(r.id)),
+ anchor: async (_sid, id) => source.find((r) => r.id === id)!, running: () => false });
+ const page = await api.page('s', undefined, true);
+ expect(base.list).toHaveBeenCalledTimes(1);
+ expect(page.items.length).toBeGreaterThan(1);
+ expect(page.items.length).toBeLessThan(20);
+ expect(page.hasMore).toBe(true);
+ expect(Buffer.byteLength(JSON.stringify(page))).toBeLessThan(1024 * 1024);
+ });
+
+ it.each(['progress', 'subagent'])('does not split work at a %s completion seal', async (kind) => {
+ const source = Array.from({ length: 2500 }, (_, n) => n % 50 === 0
+ ? { ...row(n, 'assistant'), content: kind === 'progress' ? 'Continuing' : '# Child report',
+ agentMeta: { turnCompleted: true, ...(kind === 'subagent' ? { parentUuid: 'child' } : {}) } }
+ : row(n));
+ await expect(reader(source).api.page('s')).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });
+ });
+
it('returns a full visible page before scanning an older oversized work group', async () => {
const older = Array.from({ length: 2500 }, (_, i) => row(i));
const latest = Array.from({ length: 20 }, (_, i) => row(2500 + i, 'user'));
@@ -204,6 +298,64 @@ describe('history scan budget', () => {
describe('outline history reads', () => {
+ it('allows an ordinary main-task result to paginate separately from its call', async () => {
+ const source = [row(0, 'user'),
+ { ...row(1, 'tool_use'), toolUseId: 'main-call', content: { toolName: 'Bash', input: {} } },
+ ...Array.from({ length: 30 }, (_, i) => row(i + 2, 'user')),
+ { ...row(32, 'tool_result'), toolUseId: 'main-call' }];
+ const page = await reader(source).api.page('s', undefined, true);
+ expect(page.hasMore).toBe(true);
+ expect(page.items.at(-1)).toMatchObject({ type: 'work', summary: { lastMessageId: '32' } });
+ });
+
+ it.each([false, true])('keeps an Agent spanning deliveries intact (outlined=%s)', async (outlined) => {
+ let n = 0;
+ const source = [row(n++, 'user'),
+ { ...row(n++, 'tool_use'), toolUseId: 'a', content: { toolName: 'Agent', input: {} } },
+ { ...row(n++, 'tool_use'), toolUseId: 'b', content: { toolName: 'Agent', input: {} }, agentMeta: { parentUuid: 'a' } }];
+ for (let i = 0; i < 1200; i++) {
+ if (i % 300 === 0) source.push({ ...row(n++, 'assistant'), content: '# Result\nDelivered', agentMeta: { turnCompleted: true } });
+ source.push({ ...row(n++), agentMeta: { parentUuid: i % 2 ? 'a' : 'b' } });
+ }
+ const base = reader(source);
+ const api = createHistoryViewReader({ list: base.list,
+ ...(outlined ? { outline: base.list, hydrate: async (_sid: string, ids: string[]) => source.filter((r) => ids.includes(r.id)) } : {}),
+ anchor: async (_sid, id) => source.find((r) => r.id === id)!, running: () => false });
+ const page = await api.page('s', undefined, true);
+ const withoutRevision = (items: unknown) => JSON.parse(JSON.stringify(items, (key, value) => key === 'revision' ? undefined : value));
+ expect(withoutRevision(page.items)).toEqual(withoutRevision(projectHistoryView(source, false, true)));
+ expect(page.hasMore).toBe(false);
+ const card = page.items.find((item) => item.type === 'messages' && item.deferred?.parentToolUseId === 'a');
+ expect(card?.type === 'messages' && card.deferred?.messageCount).toBe(1201);
+ });
+
+ it.each([
+ { lazy: false, outlined: false, large: false },
+ { lazy: true, outlined: false, large: false },
+ { lazy: true, outlined: true, large: false },
+ { lazy: true, outlined: true, large: true },
+ { lazy: true, outlined: true, large: false, resultOnly: true },
+ { lazy: true, outlined: true, large: false, liveTail: true },
+ ])('falls back instead of cutting an Agent with the returned cursor ($lazy/$outlined/$large/$resultOnly/$liveTail)', async ({ lazy, outlined, large, resultOnly = false, liveTail = false }) => {
+ let n = 0;
+ const source = [row(n++, 'user'),
+ { ...row(n++, 'tool_use'), toolUseId: 'a', content: { toolName: 'Agent', input: {} } }];
+ if (resultOnly) source.push({ ...row(n++, 'tool_use'), toolUseId: 'child-call', content: { toolName: 'Bash', input: {} }, agentMeta: { parentUuid: 'a' } });
+ for (let i = 0; i < (large ? 6 : 30); i++) {
+ source.push(resultOnly || liveTail ? row(n++) : { ...row(n++), agentMeta: { parentUuid: 'a' } });
+ source.push({ ...row(n++, 'assistant'), content: '# Result\n' + 'x'.repeat(large ? 200000 : 10), agentMeta: { turnCompleted: true } });
+ }
+ const tail = resultOnly ? { ...row(n++, 'tool_result'), toolUseId: 'child-call' }
+ : { ...row(n++), agentMeta: { parentUuid: 'a' } };
+ const live = liveTail ? [{ ...tail, id: `history-live:${tail.clientId}` }] : [];
+ if (!liveTail) source.push(tail);
+ const base = reader(source);
+ const api = createHistoryViewReader({ list: base.list,
+ ...(outlined ? { outline: base.list, hydrate: async (_sid: string, ids: string[]) => source.filter((r) => ids.includes(r.id)) } : {}),
+ anchor: async (_sid, id) => [...source, ...live].find((r) => r.id === id)!, running: () => liveTail, live: () => live });
+ await expect(api.page('s', undefined, lazy)).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });
+ });
+
it('reads visible bodies first across thousands of interleaved subagent rows, then pages only the expanded agent', async () => {
const source = [row(0, 'user'),
{ ...row(1, 'tool_use'), toolUseId: 'a', content: { toolName: 'Agent', input: { description: 'A' } } },
diff --git a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
index 33b1e892c5..fe08be34bd 100644
--- a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
+++ b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
@@ -1,5 +1,7 @@
import { randomUUID } from 'node:crypto';
import { throwIpcError } from '../../utils/ipcValidate';
+import { isDeliveryProseText } from '@cindy/maker-shared/message-render';
+import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
import {
HISTORY_VIEW_PAGE_BYTES, HISTORY_VIEW_PAGE_ITEMS, HISTORY_DETAIL_PAGE_BYTES,
projectHistoryView, historySubagentScopes, mapHistoryViewMessages, historyWorkSummaries, type HistoryMessageSource, type HistoryViewItem,
@@ -31,6 +33,34 @@ function firstId<T extends HistoryMessageSource>(item: HistoryViewItem<T>): stri
return item.type === 'work' ? item.summary.firstMessageId : item.messages[0].id;
}
+/** A progress seal can fold into later work; only a delivered answer is a stable cut. */
+function isHistoryPageBoundary(row: HistoryMessageSource): boolean {
+ if (row.role === 'user' || row.role === 'system') return true;
+ const meta = row.agentMeta as { parentUuid?: unknown; turnCompleted?: unknown } | null;
+ return row.role === 'assistant' && !meta?.parentUuid && meta?.turnCompleted === true
+ && typeof row.content === 'string' && isDeliveryProseText(row.content);
+}
+
+/** A suffix must retain the tool headers that establish its parent/result scope. */
+function cutsHistoryToolContext(rows: readonly HistoryMessageSource[], start: number, knownScopes?: ReadonlyMap<string, string>): boolean {
+ const tools = new Set<string>();
+ for (let i = start; i < rows.length; i++) {
+ if (rows[i].role !== 'tool_use') continue;
+ const id = parseMessageToolUse(rows[i]).toolUseId;
+ if (id) tools.add(id);
+ }
+ for (let i = start; i < rows.length; i++) {
+ const row = rows[i];
+ const parent = knownScopes ? knownScopes.get(row.id)
+ : (row.agentMeta as { parentUuid?: unknown } | null)?.parentUuid;
+ if (typeof parent === 'string' && parent && !tools.has(parent)) return true;
+ // Before reading the owning call, an orphan result could be a child row.
+ // Once scopes are known, ordinary main-task results may paginate normally.
+ if (!knownScopes && row.role === 'tool_result' && row.toolUseId && !tools.has(row.toolUseId)) return true;
+ }
+ return false;
+}
+
export function createHistoryViewReader<T extends HistoryMessageSource>(deps: HistoryViewReaderDependencies<T>) {
let readRevision = 0;
const readerEpoch = randomUUID();
@@ -54,6 +84,25 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
let items: HistoryViewItem<T>[] = [];
let scannedRows = 0;
let scannedBytes = 0;
+ const project = (live: T[]) => {
+ const boundary = exhausted ? 0 : raw.findIndex(isHistoryPageBoundary);
+ if (boundary < 0) return [];
+ // Continue back to the owning headers instead of promoting orphan child
+ // rows to the main timeline at a newly introduced delivery boundary.
+ if (!exhausted && raw[boundary].role === 'assistant'
+ && cutsHistoryToolContext([...raw, ...live], boundary)) return [];
+ // A page may start at a sealed answer. Keep that answer as right-hand
+ // context when reading the preceding page, or an older progress seal
+ // would become the "last answer" and escape its completed work group.
+ const context = beforeAnchor?.role === 'assistant'
+ && (beforeAnchor.agentMeta as { turnCompleted?: unknown } | null)?.turnCompleted === true
+ ? beforeAnchor : undefined;
+ const projected = projectHistoryView(
+ [...raw.slice(boundary), ...live, ...(context ? [context] : [])],
+ !before && deps.running(sessionId), lazyDetails,
+ );
+ return context ? projected.filter((item) => firstId(item) !== context.id) : projected;
+ };
const unavailable = () => throwIpcError('UNSUPPORTED_CAPABILITY', 'History view scan budget exceeded');
const liveRows = (stored: readonly T[]) => {
const ids = new Set(stored.map((row) => row.clientId));
@@ -85,17 +134,18 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
cursor = next;
chunks.push(rows.slice().reverse());
exhausted = rows.length < batchSize;
- if (!exhausted && !rows.some((row) => row.role === 'user' || row.role === 'system')) continue;
+ if (!exhausted && !rows.some(isHistoryPageBoundary)) continue;
raw = chunks.slice().reverse().flat();
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), lazyDetails);
- if (exhausted || items.length >= HISTORY_VIEW_PAGE_ITEMS) break;
+ items = project(live);
+ // Large completed groups can fill the byte-limited page well before
+ // twenty items. Continuing to scan then only spends the scan budget.
+ if (exhausted || items.length >= HISTORY_VIEW_PAGE_ITEMS
+ || Buffer.byteLength(JSON.stringify(items), 'utf8') + 1024 >= HISTORY_VIEW_PAGE_BYTES) break;
}
raw = chunks.slice().reverse().flat();
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), lazyDetails);
+ items = project(live);
if (outlined) {
// Select by visible objects before reading any hidden payloads. Every
// hydrated row is rechecked against the current session/rewind epoch.
@@ -121,10 +171,22 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
selected.unshift(items[index]);
bytes += size;
}
+ const hasMore = !exhausted || selected.length < items.length;
+ if (hasMore && selected.length) {
+ const rows = [...raw, ...live];
+ const start = rows.findIndex((row) => row.id === firstId(selected[0]));
+ // A deferred card can own rows newer than its own header. A cursor inside
+ // that span would lose them on the older page; use the existing raw path.
+ if (start >= 0 && cutsHistoryToolContext(rows, start, historySubagentScopes(rows))) {
+ throwIpcError('UNSUPPORTED_CAPABILITY', 'History page would split tool context');
+ }
+ }
// A clear/rewind during the scan invalidates the whole snapshot, including
// already-read rows. Never publish a prefix from the previous history epoch.
- if (raw.length) await Promise.all([deps.anchor(sessionId, raw[0].id, outlined), deps.anchor(sessionId, raw[raw.length - 1].id, outlined)]);
- const hasMore = !exhausted || selected.length < items.length;
+ // The cursor can also supply grouping context without appearing in raw.
+ const anchors = raw.length ? [raw[0].id, raw[raw.length - 1].id] : [];
+ if (beforeAnchor) anchors.push(beforeAnchor.id);
+ await Promise.all(anchors.map((id) => deps.anchor(sessionId, id, outlined)));
return { version: 1, items: selected, hasMore,
nextCursor: hasMore && selected.length ? firstId(selected[0]) : null };
},