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。

perf(history): 优先加载可见消息,按需读取折叠工具详情 (#5073)

Chris Zhang96dcfad99559
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts
new file mode 100644
index 0000000000..94fecb15d1
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts
@@ -0,0 +1,69 @@
+import { DatabaseSync } from 'node:sqlite';
+import { SQLiteSyncDialect } from 'drizzle-orm/sqlite-core';
+import { describe, expect, it } from 'vitest';
+import { historyOutlineContent, withHistoryArtifacts } from '../historyViewOutline';
+
+function outline(role: string, content: unknown, agentMeta: unknown = null, raw = false) {
+ const db = new DatabaseSync(':memory:');
+ try {
+ db.exec('CREATE TABLE messages (role TEXT, content TEXT, agent_meta TEXT)');
+ db.prepare('INSERT INTO messages VALUES (?, ?, ?)').run(role, raw ? String(content) : JSON.stringify(content), JSON.stringify(agentMeta));
+ const query = new SQLiteSyncDialect().sqlToQuery(historyOutlineContent());
+ const row = db.prepare(`SELECT ${query.sql} AS content FROM messages`).get(...query.params as string[])!;
+ try { return JSON.parse(row.content as string); } catch { return row.content; }
+ } finally { db.close(); }
+}
+
+describe('SQLite history outline', () => {
+ it('does not return folded thinking, tool outputs or file bodies to the main thread', () => {
+ const body = 'private heavy body '.repeat(100000);
+ expect(JSON.stringify(outline('thinking', { text: body, durationMs: 1000 })).length).toBeLessThan(100);
+ expect(outline('thinking', { text: '', durationMs: 0 })).toEqual({ isRedacted: false, durationMs: 0 });
+ expect(outline('tool_result', body)).toBe('');
+ const content = outline('tool_use', { toolName: 'Write', input: { file_path: '/work/report.md', content: body } });
+ expect(JSON.stringify(content)).not.toContain(body);
+ const result = withHistoryArtifacts({ id: '1', clientId: '1', role: 'tool_use', content, createdAt: '2026-09-25T00:00:00Z' });
+ expect(result.historyArtifacts).toMatchObject([{ path: '/work/report.md', source: 'tool' }]);
+ });
+ it('keeps visible prose, artifacts and malformed legacy bodies intact', () => {
+ expect(outline('assistant', 'Final answer')).toBe('Final answer');
+ expect(outline('assistant', 'Internal prose', { parentUuid: 'agent' })).toBe('');
+ const media = JSON.stringify({ xdt_image_url: 'cindy-media://blobs/test.png' });
+ expect(outline('tool_result', media)).toBe(media);
+ expect(outline('tool_result', 'xdt-file://report.pdf')).toBe('xdt-file://report.pdf');
+ expect(outline('tool_use', '{broken', null, true)).toBe('{broken');
+ expect(() => outline('tool_use', { toolName: 'file_change', input: { changes: ['malformed'] } })).not.toThrow();
+ });
+ it('retains command file candidates without sending command bodies in the summary', () => {
+ const content = outline('tool_use', { toolName: 'Bash', input: { command: 'echo done > /work/report.txt' } });
+ const result = withHistoryArtifacts({ id: '1', clientId: '1', role: 'tool_use', content, createdAt: '2026-09-25T00:00:00Z' });
+ expect(result.historyArtifacts).toMatchObject([{ path: '/work/report.txt', source: 'command' }]);
+ expect(JSON.stringify(result.historyArtifacts)).not.toContain('echo');
+ });
+ it.each(['Bash', 'exec'])('bounds long %s command outlines after extracting trailing output paths', (toolName) => {
+ const command = `echo '${'x'.repeat(300000)}' > /work/trailing-report.txt`;
+ const content = outline('tool_use', { toolName, input: { command, displayCommand: command } });
+ const result = withHistoryArtifacts({ id: '1', clientId: '1', role: 'tool_use', content, createdAt: '2026-09-25T00:00:00Z' });
+ expect(JSON.stringify(result).length).toBeLessThan(1500);
+ expect(result.historyArtifacts).toMatchObject([{ path: '/work/trailing-report.txt', source: 'command' }]);
+ expect(content.input.command).toBe(command);
+ const empty = outline('tool_use', { toolName, input: null });
+ expect(() => withHistoryArtifacts({ id: '2', clientId: '2', role: 'tool_use', content: empty, createdAt: '' })).not.toThrow();
+ });
+ it('retains structured failures and rejects malformed file changes', () => {
+ for (const result of [{ ok: false }, { success: false }, { status: 'FAILED' }]) {
+ expect(outline('tool_result', JSON.stringify(result))).toBe('<tool_use_error>');
+ }
+ expect(outline('tool_result', JSON.stringify({ ok: true }))).toBe('');
+ const content = outline('tool_use', { toolName: 'file_change', input: { changes: [{ path: '/work/no.md', kind: { type: 'add' } }] } });
+ expect(withHistoryArtifacts({ id: '1', clientId: '1', role: 'tool_use', content, createdAt: '2026-09-25T00:00:00Z' }).historyArtifacts).toBeUndefined();
+ });
+ it('keeps document delivery metadata and file suppression without edit bodies', () => {
+ const delivery = { toolName: 'cindy_mcp_call_tool', input: { server: 'documents', tool: 'render_pdf', args: { outPath: '/work/report.pdf', htmlPath: '/work/source.html' } } };
+ expect(outline('tool_use', delivery)).toEqual(delivery);
+ const content = outline('tool_use', { toolName: 'Edit', input: { file_path: '/work/code.ts', old_string: 'heavy', new_string: 'heavy' } });
+ const projected = withHistoryArtifacts({ id: '1', clientId: '1', role: 'tool_use', content, createdAt: '2026-09-25T00:00:00Z' });
+ expect(projected.historyArtifacts).toMatchObject([{ path: '/work/code.ts', exclude: 'command' }]);
+ expect(JSON.stringify(content)).not.toContain('heavy');
+ });
+});
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 21c4f3acf4..d2bd906bc8 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
@@ -201,3 +201,80 @@ describe('history scan budget', () => {
expect(base.list).toHaveBeenCalledTimes(1);
});
});
+
+
+describe('outline history reads', () => {
+ 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' } } },
+ { ...row(2, 'tool_use'), toolUseId: 'b', content: { toolName: 'Agent', input: { description: 'B' } } },
+ ...Array.from({ length: 3000 }, (_, i) => ({ ...row(i + 3), agentMeta: { parentUuid: i % 2 ? 'b' : 'a' } })),
+ row(3003, 'assistant')];
+ const base = reader(source);
+ const outline = vi.fn(async (sid: string, opts: { before?: string; after?: string; limit: number }) =>
+ (await base.list(sid, opts)).map((item) => item.role === 'thinking' ? { ...item, content: { isRedacted: true } } : item));
+ const hydrate = vi.fn(async (_sid: string, ids: string[]) => source.filter((item) => ids.includes(item.id)));
+ const api = createHistoryViewReader({ list: base.list, outline, hydrate, running: () => true,
+ revision: async () => 'stable', anchor: async (_sid, id) => source.find((item) => item.id === id)! });
+ const page = await api.page('s', undefined, true);
+ expect(page.hasMore).toBe(false);
+ expect(page.items.filter((item) => item.type === 'messages').flatMap((item) => item.messages.map((message) => message.id)))
+ .toEqual(['0', '1', '2', '3003']);
+ expect(hydrate.mock.calls.flatMap(([, ids]) => ids)).toEqual(['0', '1', '2', '3003']);
+ expect(outline).toHaveBeenCalledTimes(4);
+ const card = page.items.find((item) => item.type === 'messages' && item.deferred?.parentToolUseId === 'a');
+ if (card?.type !== 'messages' || !card.deferred) throw new Error('Missing lazy subagent');
+ hydrate.mockClear(); outline.mockClear();
+ const received: string[] = [];
+ let after: string | undefined;
+ do {
+ const detail = await api.details('s', card.deferred, after);
+ received.push(...detail.messages.map((item) => item.id));
+ after = detail.nextCursor ?? undefined;
+ } while (after);
+ const expected = source.filter((item) => (item.agentMeta as { parentUuid?: string })?.parentUuid === 'a').map((item) => item.id);
+ expect(received).toEqual(expected);
+ // Payload pages reuse one three-batch scope scan, not a scan per page.
+ expect(outline).toHaveBeenCalledTimes(3);
+ expect(hydrate.mock.calls.flatMap(([, ids]) => ids).every((id) => expected.includes(id))).toBe(true);
+ });
+});
+
+it('uses database revisions for stable snapshots and invalidates same-size hidden edits', async () => {
+ const source = [row(0, 'user'), row(1), row(2, 'assistant')];
+ const base = reader(source);
+ let revision = 'first';
+ const api = createHistoryViewReader({ list: base.list, outline: base.list,
+ hydrate: async (_sid, ids) => source.filter((message) => ids.includes(message.id)),
+ anchor: async (_sid, id) => source.find((message) => message.id === id)!,
+ revision: async () => revision, running: () => false });
+ const initial = await api.page('s', undefined, true);
+ expect(await api.page('s', undefined, true)).toEqual(initial);
+ revision = 'edited';
+ source[1] = { ...source[1], content: 'changed' };
+ expect(await api.page('s', undefined, true)).not.toEqual(initial);
+});
+
+it('invalidates cached subagent membership on a database revision and still rejects cleared anchors', async () => {
+ const source = [1, 2, 3, 4].map((n) => ({ ...row(n), content: 'x'.repeat(200000), agentMeta: { parentUuid: 'a' } }));
+ const base = reader(source);
+ let revision = 'one';
+ const outline = vi.fn(async (sid: string, opts: { after?: string; limit: number }) =>
+ (await base.list(sid, opts)).map((item) => ({ ...item, content: { isRedacted: true } })));
+ const api = createHistoryViewReader({ list: base.list, outline,
+ hydrate: async (_sid, ids) => source.filter((message) => ids.includes(message.id)),
+ anchor: async (_sid, id) => {
+ const found = source.find((message) => message.id === id);
+ if (!found) throwIpcError('NOT_FOUND', 'History range changed');
+ return { ...found, content: { isRedacted: true } };
+ }, revision: async () => revision, running: () => false });
+ const ref = { key: 'a', firstMessageId: '1', lastMessageId: '4', parentToolUseId: 'a' };
+ expect((await api.details('s', ref)).nextCursor).toBe('1');
+ expect((await api.details('s', ref, '1')).messages.map((item) => item.id)).toEqual(['2']);
+ expect(outline).toHaveBeenCalledTimes(1);
+ source[1].agentMeta.parentUuid = 'b'; revision = 'two';
+ expect((await api.details('s', ref, '1')).messages.map((item) => item.id)).toEqual(['3']);
+ expect(outline).toHaveBeenCalledTimes(2);
+ source.length = 0;
+ await expect(api.details('s', ref, '3')).rejects.toMatchObject({ code: 'NOT_FOUND' });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
index ab253b7208..c75b7cd13f 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
@@ -79,6 +79,7 @@ vi.mock('../../../cindy-media/chatAttachments', () => ({
}));
vi.mock('../../client/current', () => ({
getDbClient: () => ({ drizzle: h.db, query: h.query, tx: h.tx }),
+ getCurrentDbClientSnapshot: () => ({ client: { drizzle: h.db, query: h.query, tx: h.tx }, clientEpoch: 1 }),
}));
import {
@@ -174,6 +175,56 @@ function insertCostMessage(
}
describe('local-db:messages:list cursor', () => {
+ it('serves a lightweight SQLite view, hydrates visible text, then reads only the expanded subagent', async () => {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');
+ const insert = sqlite.prepare('INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
+ const add = (id: string, role: string, content: unknown, parent?: string) => insert.run(id, id, 's1', role,
+ JSON.stringify(content), role === 'tool_use' ? 'agent' : null,
+ parent ? JSON.stringify({ parentUuid: parent, model: 'actual-child-model' }) : null, Number(id));
+ add('0', 'user', 'Visible question');
+ add('1', 'tool_use', { toolName: 'Agent', toolUseId: 'agent', input: { description: 'Inspect' } });
+ for (let n = 2; n < 103; n++) add(String(n), 'thinking', { text: 'hidden '.repeat(1000), durationMs: 10 }, 'agent');
+ add('103', 'assistant', 'Visible answer');
+ registerMessageIpc();
+ const invoke = (channel: string, ...args: unknown[]) => runDeviceLinkInvokeContext({ controllerDeviceId: 'd', channel }, () => h.handlers.get(channel)!({}, 's1', ...args));
+ const page = await invoke('local-db:messages:view', { lazyDetails: true }) as HistoryViewPage<HistoryMessageSource>;
+ expect(page.hasMore).toBe(false);
+ expect(JSON.stringify(page)).not.toContain('hidden ');
+ expect(JSON.stringify(page)).toContain('Visible answer');
+ const card = page.items.find((item) => item.type === 'messages' && item.deferred);
+ if (card?.type !== 'messages' || !card.deferred) throw new Error('Missing subagent');
+ expect(card.deferred).toMatchObject({ messageCount: 101, model: 'actual-child-model' });
+ const detail = await invoke('local-db:messages:work-details', card.deferred, {}) as HistoryDetailPage<HistoryMessageSource>;
+ expect(detail.messages.length).toBeGreaterThan(0);
+ expect(detail.messages.every((row) => (row.agentMeta as { parentUuid?: string })?.parentUuid === 'agent')).toBe(true);
+ expect(JSON.stringify(detail)).toContain('hidden ');
+ expect(await invoke('local-db:messages:view', { lazyDetails: true })).toEqual(page);
+ sqlite.prepare('UPDATE messages SET content = ? WHERE id = ?').run(JSON.stringify({ text: 'edited '.repeat(1000), durationMs: 10 }), '2');
+ expect(await invoke('local-db:messages:view', { lazyDetails: true })).not.toEqual(page);
+ });
+ it('keeps a command larger than the scan budget folded without losing its trailing artifact or full details', async () => {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');
+ const command = `echo '${'x'.repeat(9 * 1024 * 1024)}' > /work/trailing-report.txt`;
+ const insert = sqlite.prepare('INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)');
+ for (const [id, role, content] of [
+ ['0', 'user', 'Question'],
+ ['1', 'tool_use', { toolName: 'Bash', input: { command } }],
+ ['2', 'tool_result', 'done'],
+ ['3', 'assistant', 'Answer'],
+ ] as const) insert.run(id, id, 's1', role, JSON.stringify(content), ['1', '2'].includes(id) ? 'bash' : null, Number(id));
+ registerMessageIpc();
+ const invoke = (channel: string, ...args: unknown[]) => runDeviceLinkInvokeContext({ controllerDeviceId: 'd', channel }, () => h.handlers.get(channel)!({}, 's1', ...args));
+ const page = await invoke('local-db:messages:view', { lazyDetails: true }) as HistoryViewPage<HistoryMessageSource>;
+ expect(page.hasMore).toBe(false);
+ expect(JSON.stringify(page).length).toBeLessThan(5000);
+ const work = historyViewLeaves(page.items).find((item) => item.type === 'work');
+ if (work?.type !== 'work') throw new Error('Missing folded command');
+ expect(work.summary.artifacts).toMatchObject([{ path: '/work/trailing-report.txt' }]);
+ const detail = await invoke('local-db:messages:work-details', work.summary, {}) as HistoryDetailPage<HistoryMessageSource>;
+ expect((detail.messages[0].content as { input: { command: string } }).input.command).toBe(command);
+ });
it.each([101, MAX_HISTORY_SCAN_ROWS])('reads all %i live rows from a generated work reference', async (count) => {
const sqlite = createDb();
sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');
diff --git a/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts b/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts
new file mode 100644
index 0000000000..02793f7cc3
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts
@@ -0,0 +1,82 @@
+import { sql, type SQL } from 'drizzle-orm';
+import { describeToolUse, createdPathsFromDescriptor } from '@cindy/maker-shared/tool-use-descriptor';
+import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
+import type { HistoryMessageSource } from '@cindy/maker-shared/message-window';
+import { extractCommandOutputPathCandidates } from '../../../shared/commandOutputPaths';
+import { messages } from '../schema';
+
+/** Read-model headers only. Full content is read by ID after visible items are selected.
+ * Candidate artifact results are conservative: the shared parser remains authoritative.
+ * Invalid legacy JSON stays intact instead of disappearing from the history.
+ */
+export function historyOutlineContent(): SQL<string> {
+ const body = messages.content;
+ return sql<string>`CASE
+ WHEN NOT json_valid(${body}) THEN ${body}
+ WHEN ${messages.role} = 'thinking' THEN json_object('isRedacted', json(CASE
+ WHEN (json_type(${body}, '$') = 'text' AND length(json_extract(${body}, '$')) > 0)
+ OR length(json_extract(${body}, '$.text')) > 0 OR json_extract(${body}, '$.isRedacted') = 1
+ THEN 'true' ELSE 'false' END),
+ 'durationMs', json_extract(${body}, '$.durationMs'))
+ WHEN ${messages.role} = 'tool_use' AND (
+ COALESCE(json_extract(${body}, '$.input.outPath'), json_extract(${body}, '$.input.out_path'),
+ json_extract(${body}, '$.input.outputPath'), json_extract(${body}, '$.input.output_path'),
+ json_extract(${body}, '$.input.args.outPath'), json_extract(${body}, '$.input.args.out_path'),
+ json_extract(${body}, '$.input.args.outputPath'), json_extract(${body}, '$.input.args.output_path')) IS NOT NULL
+ ) THEN ${body}
+ WHEN ${messages.role} = 'tool_use' THEN json_object(
+ 'toolName', json_extract(${body}, '$.toolName'),
+ 'toolUseId', json_extract(${body}, '$.toolUseId'),
+ 'input', CASE WHEN json_extract(${body}, '$.toolName') = 'cindy_mcp_call_tool'
+ THEN json_object('server', json_extract(${body}, '$.input.server'), 'tool', json_extract(${body}, '$.input.tool'))
+ ELSE json_object('file_path', json_extract(${body}, '$.input.file_path'),
+ 'path', json_extract(${body}, '$.input.path'),
+ 'command', json_extract(${body}, '$.input.command'),
+ 'displayCommand', json_extract(${body}, '$.input.displayCommand'),
+ 'changes', json(COALESCE((SELECT json_group_array(json_object('path', json_extract(CASE WHEN json_valid(value) THEN value ELSE '{}' END, '$.path'),
+ 'kind', json_extract(CASE WHEN json_valid(value) THEN value ELSE '{}' END, '$.kind'),
+ 'move_path', json_extract(CASE WHEN json_valid(value) THEN value ELSE '{}' END, '$.move_path'),
+ 'movePath', json_extract(CASE WHEN json_valid(value) THEN value ELSE '{}' END, '$.movePath'),
+ 'diff', CASE WHEN json_type(CASE WHEN json_valid(value) THEN value ELSE '{}' END, '$.diff') = 'text' THEN '' END))
+ FROM json_each(${body}, '$.input.changes')), '[]')))
+ END)
+ WHEN ${messages.role} = 'tool_result'
+ AND instr(${body}, 'xdt_') = 0 AND instr(${body}, 'xdt-file:') = 0 AND instr(${body}, 'cindy-media:') = 0
+ THEN json_quote(CASE WHEN instr(${body}, '<tool_use_error>') > 0 OR CASE
+ WHEN json_valid(json_extract(${body}, '$')) THEN
+ json_extract(json_extract(${body}, '$'), '$.ok') IS 0
+ OR json_extract(json_extract(${body}, '$'), '$.success') IS 0
+ OR lower(json_extract(json_extract(${body}, '$'), '$.status')) IN ('error', 'failed', 'failure')
+ ELSE 0 END THEN '<tool_use_error>' ELSE '' END)
+ WHEN ${messages.role} = 'assistant'
+ AND length(CASE WHEN json_valid(${messages.agentMeta}) THEN json_extract(${messages.agentMeta}, '$.parentUuid') END) > 0 THEN json_quote('')
+ ELSE ${body} END`;
+}
+
+
+/** File content/patches never cross the outline query; commands yield only paths on the wire. */
+export function withHistoryArtifacts<T extends HistoryMessageSource>(row: T): T & Pick<HistoryMessageSource, 'historyArtifacts'> {
+ if (row.role !== 'tool_use') return row;
+ const tool = parseMessageToolUse(row);
+ const descriptor = describeToolUse(tool.toolName, tool.input);
+ const paths = descriptor.kind === 'command'
+ ? extractCommandOutputPathCandidates(descriptor.command) : createdPathsFromDescriptor(descriptor);
+ const exclusions = descriptor.kind === 'file' && descriptor.action === 'edit'
+ ? [{ path: descriptor.filePath, exclude: 'command' as const }]
+ : descriptor.kind === 'fileChange' ? descriptor.changes.filter((change) => change.action !== 'add')
+ .map((change) => ({ path: change.path, exclude: change.action === 'delete' || change.action === 'move' ? 'all' as const : 'command' as const })) : [];
+ // Extract from the complete command first: output paths may occur after a
+ // long script/heredoc. Only the bounded outline enters the scan budget/cache;
+ // visible messages and expanded details are hydrated from the original row.
+ const outlined = descriptor.kind === 'command' ? { ...row, content: {
+ ...row.content as object,
+ input: Object.fromEntries(Object.entries((tool.input ?? {}) as Record<string, unknown>).map(([key, value]) =>
+ [key, (key === 'command' || key === 'displayCommand') && typeof value === 'string'
+ ? value.slice(0, 256) : value])),
+ } } : row;
+ if (!paths.length && !exclusions.length) return outlined;
+ return { ...outlined, historyArtifacts: [...paths.map((path) => ({ path,
+ source: descriptor.kind === 'command' ? 'command' : 'tool',
+ createdAt: row.createdAt, toolUseId: tool.toolUseId,
+ } as const)), ...exclusions.map((file) => ({ ...file, source: 'tool' as const, createdAt: row.createdAt, toolUseId: tool.toolUseId }))] };
+}
diff --git a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
index 97d489152b..33b1e892c5 100644
--- a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
+++ b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
@@ -1,7 +1,8 @@
+import { randomUUID } from 'node:crypto';
import { throwIpcError } from '../../utils/ipcValidate';
import {
HISTORY_VIEW_PAGE_BYTES, HISTORY_VIEW_PAGE_ITEMS, HISTORY_DETAIL_PAGE_BYTES,
- projectHistoryView, type HistoryMessageSource, type HistoryViewItem,
+ projectHistoryView, historySubagentScopes, mapHistoryViewMessages, historyWorkSummaries, type HistoryMessageSource, type HistoryViewItem,
type HistoryViewPage, type HistoryDetailPage, type HistoryWorkReference,
} from '@cindy/maker-shared/message-window';
@@ -11,8 +12,13 @@ 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[]>;
+ /** Lightweight rows sufficient for grouping, never used as message bodies. */
+ outline?(sessionId: string, opts: ReadOptions, skipImport: boolean): Promise<T[]>;
+ hydrate?(sessionId: string, ids: string[]): Promise<T[]>;
+ revision?(): Promise<string>;
+ validate?(sessionId: string, ids: string[]): Promise<void>;
/** Must reject anchors outside this session, cleared history or rewound history. */
- anchor(sessionId: string, id: string): Promise<T>;
+ anchor(sessionId: string, id: string, outline?: boolean): Promise<T>;
running(sessionId: string): boolean;
live?(sessionId: string): T[];
}
@@ -26,9 +32,21 @@ function firstId<T extends HistoryMessageSource>(item: HistoryViewItem<T>): stri
}
export function createHistoryViewReader<T extends HistoryMessageSource>(deps: HistoryViewReaderDependencies<T>) {
+ let readRevision = 0;
+ const readerEpoch = randomUUID();
+ // Only retain scoped headers, never hydrated bodies. Revisions invalidate the
+ // cache on DB writes/account changes; live ranges remain uncached.
+ const detailRanges = new Map<string, { rows: T[]; bytes: number }>();
+ let detailRevision: string | undefined;
+ let detailCacheBytes = 0;
return {
- async page(sessionId: string, before?: string): Promise<HistoryViewPage<T>> {
- const beforeAnchor = before ? await deps.anchor(sessionId, before) : undefined;
+ async page(sessionId: string, before?: string, lazyDetails = false): Promise<HistoryViewPage<T>> {
+ const outlined = lazyDetails && !!deps.outline && !!deps.hydrate;
+ const batchSize = outlined ? 1000 : 100;
+ const rowBudget = outlined ? 100000 : MAX_HISTORY_SCAN_ROWS;
+ const read = outlined ? deps.outline! : deps.list;
+ const outlineRevision = outlined ? `${readerEpoch}:${await deps.revision?.() ?? ++readRevision}` : undefined;
+ const beforeAnchor = before ? await deps.anchor(sessionId, before, outlined) : undefined;
let cursor = beforeAnchor?.id.startsWith('history-live:') ? undefined : beforeAnchor?.id;
const chunks: T[][] = [];
let raw: T[] = [];
@@ -44,7 +62,7 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
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();
+ if (scannedRows + live.length + 1 > rowBudget || live.length >= MAX_HISTORY_SCAN_ROWS || bytes > MAX_HISTORY_SCAN_BYTES) unavailable();
live.push(row);
}
return live;
@@ -54,30 +72,47 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
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);
+ if (scannedRows >= rowBudget) unavailable();
+ const rows = await read(sessionId, { limit: batchSize, ...(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 (scannedRows > rowBudget || 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');
cursor = next;
chunks.push(rows.slice().reverse());
- exhausted = rows.length < 100;
+ exhausted = rows.length < batchSize;
if (!exhausted && !rows.some((row) => row.role === 'user' || row.role === 'system')) 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));
+ items = boundary < 0 ? [] : projectHistoryView([...raw.slice(boundary), ...live], !before && deps.running(sessionId), lazyDetails);
if (exhausted || items.length >= HISTORY_VIEW_PAGE_ITEMS) 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));
+ items = boundary < 0 ? [] : projectHistoryView([...raw.slice(boundary), ...live], !before && deps.running(sessionId), lazyDetails);
+ if (outlined) {
+ // Select by visible objects before reading any hidden payloads. Every
+ // hydrated row is rechecked against the current session/rewind epoch.
+ const candidate = items.slice(-HISTORY_VIEW_PAGE_ITEMS);
+ const ids: string[] = [];
+ mapHistoryViewMessages(candidate, (rows) => {
+ ids.push(...rows.filter((row) => !row.id.startsWith('history-live:')).map((row) => row.id));
+ return rows;
+ });
+ const hydrated = new Map((await deps.hydrate!(sessionId, [...new Set(ids)])).map((row) => [row.id, row]));
+ items.splice(items.length - candidate.length, candidate.length,
+ ...mapHistoryViewMessages(candidate, (rows) => rows.map((row) => hydrated.get(row.id) ?? row)));
+ // The outline deliberately omits bodies, so it cannot hash their bytes.
+ // SQLite change counters also cover edits to hidden bodies without
+ // reading them. Unchanged snapshots retain their rendering identities.
+ for (const summary of historyWorkSummaries(items)) summary.revision += `:${outlineRevision}`;
+ }
const selected: HistoryViewItem<T>[] = [];
let bytes = 1024;
for (let index = items.length - 1; index >= 0; index--) {
@@ -88,7 +123,7 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
}
// 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), deps.anchor(sessionId, raw[raw.length - 1].id)]);
+ 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;
return { version: 1, items: selected, hasMore,
nextCursor: hasMore && selected.length ? firstId(selected[0]) : null };
@@ -99,9 +134,84 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
// Like the summary scan, every detail exit must reject a clear/rewind
// that happened while an earlier DB batch was already collected.
const ids = new Set([ref.firstMessageId, ref.lastMessageId, ...page.messages.map((row) => row.id)]);
- for (const id of ids) await deps.anchor(sessionId, id);
+ if (deps.validate) await deps.validate(sessionId, [...ids]);
+ else for (const id of ids) await deps.anchor(sessionId, id, true);
return page;
};
+ if (ref.parentToolUseId && deps.outline && deps.hydrate) {
+ const first = await deps.anchor(sessionId, ref.firstMessageId, true);
+ const last = await deps.anchor(sessionId, ref.lastMessageId, true);
+ if (compareRows(first, last) > 0) throwIpcError('INVALID_PARAMS', 'Invalid history range');
+ const cursorAnchor = after ? await deps.anchor(sessionId, after, true) : undefined;
+ if (cursorAnchor && (compareRows(cursorAnchor, first) < 0 || compareRows(cursorAnchor, last) > 0)) {
+ throwIpcError('INVALID_PARAMS', 'Invalid detail cursor');
+ }
+ const revision = !ref.liveMessageIds?.length && deps.revision ? await deps.revision() : undefined;
+ if (revision !== detailRevision) {
+ detailRanges.clear(); detailCacheBytes = 0; detailRevision = revision;
+ }
+ const cacheKey = JSON.stringify([sessionId, ref.parentToolUseId, first.id, last.id, ref.lastStoredMessageId]);
+ const cached = revision === undefined ? undefined : detailRanges.get(cacheKey);
+ let scoped = cached?.rows;
+ if (cached) {
+ detailRanges.delete(cacheKey); detailRanges.set(cacheKey, cached);
+ }
+ if (!scoped) {
+ const headers: T[] = [];
+ if (!first.id.startsWith('history-live:')) {
+ headers.push(first);
+ let cursor = first.id;
+ while (cursor !== (ref.lastStoredMessageId ?? last.id)) {
+ const batch = (await deps.outline(sessionId, { limit: 1000, after: cursor }, true)).slice().reverse();
+ if (!batch.length) break;
+ const bounded = batch.filter((row) => compareRows(row, last) <= 0);
+ headers.push(...bounded);
+ if (headers.length > 100000) throwIpcError('INVALID_PARAMS', 'History detail range is too large');
+ const next = batch.at(-1)!.id;
+ if (next === cursor) throwIpcError('INTERNAL', 'History detail cursor did not advance');
+ cursor = next;
+ if (bounded.length < batch.length || batch.length < 1000) break;
+ }
+ }
+ for (const id of ref.liveMessageIds ?? []) {
+ const row = await deps.anchor(sessionId, id);
+ if (!headers.some((stored) => stored.clientId === row.clientId)) headers.push(row);
+ }
+ const scopes = historySubagentScopes(headers, ref.parentToolUseId);
+ scoped = headers.filter((row) => scopes.get(row.id) === ref.parentToolUseId);
+ // A write during the scan must not publish a cache for an older epoch.
+ if (revision !== undefined && revision === await deps.revision!() && revision === detailRevision) {
+ const bytes = Buffer.byteLength(JSON.stringify(scoped), 'utf8');
+ if (bytes <= MAX_HISTORY_SCAN_BYTES) {
+ while (detailRanges.size && (detailRanges.size >= 2 || detailCacheBytes + bytes > MAX_HISTORY_SCAN_BYTES)) {
+ const oldest = detailRanges.keys().next().value!;
+ detailCacheBytes -= detailRanges.get(oldest)!.bytes;
+ detailRanges.delete(oldest);
+ }
+ // Concurrent requests may have inserted the same range.
+ detailCacheBytes -= detailRanges.get(cacheKey)?.bytes ?? 0;
+ detailRanges.set(cacheKey, { rows: scoped, bytes }); detailCacheBytes += bytes;
+ }
+ }
+ }
+ const candidates = scoped.filter((row) => !cursorAnchor || compareRows(row, cursorAnchor) > 0);
+ const collected: T[] = [];
+ let bytes = 1024;
+ for (let offset = 0; offset < candidates.length; offset += 100) {
+ const batch = candidates.slice(offset, offset + 100);
+ const stored = batch.filter((row) => !row.id.startsWith('history-live:'));
+ const full = new Map((await deps.hydrate(sessionId, stored.map((row) => row.id))).map((row) => [row.id, row]));
+ for (const header of batch) {
+ const row = full.get(header.id) ?? header;
+ const size = Buffer.byteLength(JSON.stringify(row), 'utf8');
+ if (collected.length && bytes + size > HISTORY_DETAIL_PAGE_BYTES) {
+ return finalize({ version: 1, messages: collected, hasMore: true, nextCursor: collected.at(-1)!.id });
+ }
+ collected.push(row); bytes += size;
+ }
+ }
+ return finalize({ version: 1, messages: collected, hasMore: false, nextCursor: null });
+ }
if (ref.liveMessageIds?.length) {
const liveCursor = after ? ref.liveMessageIds.indexOf(after) : -1;
const stored = liveCursor >= 0 || !ref.firstStoredMessageId || !ref.lastStoredMessageId
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 7a25e9b427..d2421295ef 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -23,9 +23,10 @@ import {
type SQL,
} from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
+import { historyOutlineContent, withHistoryArtifacts } from './historyViewOutline';
import { historyViewLeaves, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
-import { getDbClient } from '../client/current';
+import { getDbClient, getCurrentDbClientSnapshot } from '../client/current';
import type { ContextRebuildArgs } from '../client/tx/types';
import { latestVisiblePreviewRow } from '../latestMessageText';
import { messages, sessions } from '../schema';
@@ -237,9 +238,9 @@ const VALID_ROLES: ReadonlySet<MessageRole> = new Set([
'thinking',
] as const);
-export async function readMessagesList(sessionId: unknown, opts: unknown, skipImport = false) {
+export async function readMessagesList(sessionId: unknown, opts: unknown, skipImport = false, outline = false) {
const sid = requireString(sessionId, 'sessionId');
- const limit = clampLimit((opts as { limit?: number } | undefined)?.limit);
+ const limit = outline ? 1000 : clampLimit((opts as { limit?: number } | undefined)?.limit);
const before = (opts as { before?: string } | undefined)?.before;
const beforeTs = (opts as { beforeTs?: number } | undefined)?.beforeTs;
const after = (opts as { after?: string } | undefined)?.after;
@@ -316,6 +317,7 @@ export async function readMessagesList(sessionId: unknown, opts: unknown, skipIm
const rows = await db
.select({
...getMessageSelectFields(),
+ ...(outline ? { content: historyOutlineContent() } : {}),
rowid: messageRowid,
})
.from(messages)
@@ -326,8 +328,8 @@ export async function readMessagesList(sessionId: unknown, opts: unknown, skipIm
)
.limit(limit);
const orderedRows = afterCursor ? rows.slice().reverse() : rows;
- const listed = hydrateLegacyUserTurnCosts(orderedRows.map(messageToCamelWithRowid));
- return listed;
+ const listed = await hydrateLegacyUserTurnCosts(orderedRows.map(messageToCamelWithRowid));
+ return outline ? listed.map(withHistoryArtifacts) : listed;
}
export function registerMessageIpc(
@@ -339,9 +341,55 @@ export function registerMessageIpc(
const historyView = createHistoryViewReader({
list: readMessagesList,
+ revision: async () => {
+ const current = getCurrentDbClientSnapshot();
+ if (!current) throw new Error('DbClient not ready');
+ // Own writes increment total_changes; writes through other connections
+ // increment data_version. Both run on the existing database worker.
+ const [version] = await current.client.query<{ changes: number; version: number }>(
+ 'SELECT total_changes() AS changes, data_version AS version FROM pragma_data_version');
+ return `${current.clientEpoch}:${version.version}:${version.changes}`;
+ },
+ outline: (sid, opts, skipImport) => readMessagesList(sid, opts, skipImport, true),
+ hydrate: async (sid, ids) => {
+ const db = getDbClient().drizzle;
+ const [session] = await db.select({ clearedAt: sessions.clearedAt }).from(sessions)
+ .where(eq(sessions.id, sid)).limit(1);
+ if (!session) throwIpcError('NOT_FOUND', 'History is unavailable');
+ const result: Message[] = [];
+ for (let offset = 0; offset < ids.length; offset += 100) {
+ const batch = ids.slice(offset, offset + 100);
+ const rows = await db.select({ ...getMessageSelectFields(), rowid: messageRowid }).from(messages)
+ .where(and(eq(messages.sessionId, sid), inArray(messages.id, batch), isNull(messages.rewindAt),
+ session.clearedAt !== null ? gt(messages.createdAt, session.clearedAt) : undefined));
+ if (rows.length !== batch.length) throwIpcError('NOT_FOUND', 'History range changed');
+ result.push(...rows.map(messageToCamelWithRowid));
+ }
+ return hydrateLegacyUserTurnCosts(result);
+ },
+ validate: async (sid, ids) => {
+ const db = getDbClient().drizzle;
+ const [session] = await db.select({ clearedAt: sessions.clearedAt }).from(sessions)
+ .where(eq(sessions.id, sid)).limit(1);
+ if (!session) throwIpcError('NOT_FOUND', 'History is unavailable');
+ const valid = new Set(readLive(sid).filter((row) => session.clearedAt === null || Date.parse(row.createdAt) > session.clearedAt)
+ .map((row) => row.id));
+ const pending = ids.filter((id) => !valid.has(id));
+ for (let offset = 0; offset < pending.length; offset += 100) {
+ const batch = pending.slice(offset, offset + 100);
+ const storedIds = batch.filter((id) => !id.startsWith('history-live:'));
+ const clientIds = batch.filter((id) => id.startsWith('history-live:')).map((id) => id.slice('history-live:'.length));
+ const rows = await db.select({ id: messages.id, clientId: messages.clientId }).from(messages)
+ .where(and(eq(messages.sessionId, sid), isNull(messages.rewindAt),
+ or(inArray(messages.id, storedIds), inArray(messages.clientId, clientIds)),
+ session.clearedAt !== null ? gt(messages.createdAt, session.clearedAt) : undefined));
+ for (const row of rows) { valid.add(row.id); valid.add(`history-live:${row.clientId}`); }
+ }
+ if (ids.some((id) => !valid.has(id))) throwIpcError('NOT_FOUND', 'History range changed');
+ },
running: readRunning,
live: readLive,
- anchor: async (sessionId, id) => {
+ anchor: async (sessionId, id, outline) => {
const db = getDbClient().drizzle;
const [session] = await db.select({ clearedAt: sessions.clearedAt }).from(sessions)
.where(eq(sessions.id, sessionId)).limit(1);
@@ -350,20 +398,22 @@ export function registerMessageIpc(
const live = readLive(sessionId).find((row) => row.id === id);
if (live && (session.clearedAt === null || Date.parse(live.createdAt) > session.clearedAt)) return live;
}
- const [row] = await db.select({ ...getMessageSelectFields(), rowid: messageRowid }).from(messages)
+ const [row] = await db.select({ ...getMessageSelectFields(), ...(outline ? { content: historyOutlineContent() } : {}), rowid: messageRowid }).from(messages)
.where(and(eq(messages.sessionId, sessionId),
id.startsWith('history-live:') ? eq(messages.clientId, id.slice('history-live:'.length)) : eq(messages.id, id),
isNull(messages.rewindAt),
session.clearedAt !== null ? gt(messages.createdAt, session.clearedAt) : undefined)).limit(1);
if (!row) throwIpcError('NOT_FOUND', 'History range changed');
- return messageToCamelWithRowid(row);
+ const message = messageToCamelWithRowid(row);
+ return outline ? withHistoryArtifacts(message) : message;
},
});
ipcMain.handle('local-db:messages:view', async (event, sessionId: unknown, opts: unknown) => {
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')).catch((error) => {
+ const page = await historyView.page(sid, before == null ? undefined : requireString(before, 'before'),
+ (opts as { lazyDetails?: unknown } | null)?.lazyDetails === true).catch((error) => {
if (isHistoryViewUnavailable(error)) getDeviceLinkInvokeContext()?.historyView?.disable();
throw error;
});
@@ -384,11 +434,12 @@ export function registerMessageIpc(
ipcMain.handle('local-db:messages:work-details', async (event, sessionId: unknown, ref: unknown, opts: unknown) => {
if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
const sid = requireString(sessionId, 'sessionId');
- const value = ref as { key?: unknown; firstMessageId?: unknown; lastMessageId?: unknown; firstStoredMessageId?: unknown; lastStoredMessageId?: unknown; liveMessageIds?: unknown } | null;
+ const value = ref as { key?: unknown; firstMessageId?: unknown; lastMessageId?: unknown; firstStoredMessageId?: unknown; lastStoredMessageId?: unknown; liveMessageIds?: unknown; parentToolUseId?: unknown } | null;
const after = (opts as { after?: unknown } | null)?.after;
if (value?.liveMessageIds != null && (!Array.isArray(value.liveMessageIds) || value.liveMessageIds.length > MAX_HISTORY_SCAN_ROWS)) throwIpcError('INVALID_PARAMS', 'Invalid live work range');
return historyView.details(sid, {
key: requireString(value?.key, 'key'),
+ ...(value?.parentToolUseId == null ? {} : { parentToolUseId: requireString(value.parentToolUseId, 'parentToolUseId') }),
firstMessageId: requireString(value?.firstMessageId, 'firstMessageId'),
lastMessageId: requireString(value?.lastMessageId, 'lastMessageId'),
...(value?.firstStoredMessageId == null ? {} : { firstStoredMessageId: requireString(value.firstStoredMessageId, 'firstStoredMessageId') }),
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index bd826f88dc..8bd8a5a6fa 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5583,6 +5583,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:collaboration-settings:reset'),
},
messages: {
+ historyView: (sessionId: string, opts?: { before?: string | null; lazyDetails?: boolean }): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:messages:view', sessionId, opts),
+ workDetails: (sessionId: string, ref: unknown, opts?: { after?: string | null }): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:messages:work-details', sessionId, ref, opts),
list: (
sessionId: string,
opts?: { limit?: number; before?: string; beforeTs?: number },
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
index e4b9714ac4..173b62342a 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
@@ -1355,7 +1355,38 @@ describe('device-link controller mirror — end-to-end scenarios', () => {
view.setActive(false);
});
- it('force reconciliation hydrates a terminal row from a collapsed work range', async () => {
+ it('seals a displayed live row without fetching an older collapsed work range', async () => {
+ const s = sid();
+ host.enableHistoryView();
+ const older = [dbMessage(s, 'old-u', 'old question', '2026-09-08T00:00:00Z', 'user'),
+ { ...dbMessage(s, 'old-thought', '', '2026-09-08T00:00:01Z', 'thinking'), content: { text: 'old hidden body', durationMs: 500 } },
+ dbMessage(s, 'old-answer', 'old answer', '2026-09-08T00:00:02Z'),
+ dbMessage(s, 'question', 'new question', '2026-09-08T00:00:03Z', 'user')];
+ host.seedSession(s, {}, older);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(); await flush();
+ const startedAt = Date.parse('2026-09-08T00:00:04Z');
+ host.push('maker:event', { sessionId: s, event: { type: 'thinking', data: { blockId: 'client-thought', stage: 'start', startedAt } } });
+ host.push('maker:event', { sessionId: s, event: { type: 'thinking', data: { blockId: 'client-thought', stage: 'delta', text: 'live prefix' } } });
+ const terminal = { ...dbMessage(s, 'thought', '', new Date(startedAt).toISOString(), 'thinking'),
+ content: { text: 'sealed thought', durationMs: 1000, finishedAt: startedAt + 1000 } };
+ host.seedSession(s, {}, [...older, terminal, dbMessage(s, 'answer', 'final answer', '2026-09-08T00:00:06Z')]);
+ host.invoke.mockClear();
+ await expect(makerChatStore.reconcileRemoteMessages(s, { force: true })).resolves.toBe(true);
+ const state = makerChatStore.getSnapshot(s);
+ expect(state.messages.find((row) => row.clientId === 'client-thought')).toMatchObject({ content: 'sealed thought', isStreaming: false });
+ expect(state.messages.some((row) => row.clientId === 'client-old-thought')).toBe(false);
+ const view = getRemoteHistoryView(s)!;
+ expect(view.getSnapshot().expanded.size).toBe(0);
+ expect([...view.getSnapshot().details.values()].flatMap((detail) => detail.messages.map((row) => row.clientId))).toEqual(['client-thought']);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:work-details')).toHaveLength(1);
+ expect(host.invoke).not.toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
+ makerChatStore.purgeSession(s);
+ });
+
+ it('force reconciliation leaves completed historical work folded until expansion', async () => {
const s = sid();
host.enableHistoryView();
const history = [dbMessage(s, 'u', 'question', '2026-06-15T00:00:00.000Z', 'user'),
@@ -1374,12 +1405,18 @@ describe('device-link controller mirror — end-to-end scenarios', () => {
'client-u', 'client-answer',
]);
+ host.invoke.mockClear();
await makerChatStore.reconcileRemoteMessages(s, { force: true });
expect(makerChatStore.getSnapshot(s).messages.map((row) => row.clientId)).toEqual([
- 'client-u', 'client-thought', 'client-answer',
+ 'client-u', 'client-answer',
]);
+ expect(host.invoke).not.toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:work-details', expect.anything());
expect(view.getSnapshot().expanded.has(group.key)).toBe(false);
+ view.setExpanded(group.key, true);
+ await flush();
+ expect(makerChatStore.getSnapshot(s).messages.find((row) => row.clientId === 'client-thought'))
+ .toMatchObject({ content: 'terminal body', isStreaming: false });
view.setActive(false);
});
@@ -1456,6 +1493,14 @@ describe('device-link controller mirror — end-to-end scenarios', () => {
if (args[1] === channelToHold) await new Promise<void>(resolve => { releases.push(resolve); });
return value;
});
+ if (path === 'raw-fallback') {
+ // A failed visible detail requires fallback; folded historical work does not.
+ const view = getRemoteHistoryView(s)!;
+ await view.refresh();
+ const group = view.getSnapshot().items.find((item) => item.type === 'work')!;
+ view.setExpanded(group.key, true);
+ await flush();
+ }
const first = makerChatStore.reconcileRemoteMessages(s, { force: true });
await vi.waitFor(() => expect(releases).toHaveLength(1));
const second = makerChatStore.reconcileRemoteMessages(s, { force: true });
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index cb14d098de..bbbe092ae3 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -1,6 +1,7 @@
import { simplifyBotRenderItems } from '@/features/bots/botConversationPresentation';
export { simplifyBotRenderItems } from '@/features/bots/botConversationPresentation';
import { placeBotTaskCardsAfterIntroduction } from '@cindy/maker-shared/botCollaboration';
+import { describeToolUse, sourcePathCandidatesFromDescriptor } from '@cindy/maker-shared/tool-use-descriptor';
/**
* MessageStream
* ---------------------------------------------------------------------------
@@ -36,6 +37,7 @@ import {
renderHistoryView,
historyPrefetchThreshold,
historyViewLeaves,
+ historyWorkSummaries,
} from '@cindy/maker-shared/message-window';
import {
getRemoteHistoryView,
@@ -1451,6 +1453,7 @@ export function buildRenderItems(
turnChangeSets?: readonly TurnChangeSetSummary[];
/** Session working directory for opaque generated-file fallback chips. */
workingDir?: string;
+ historyArtifacts?: readonly import('@cindy/maker-shared/message-window').HistoryFileArtifact[];
/** Bot-owned Session: show newly created files as deliverables, not an engineering diff card. */
botSessionId?: string;
/** Reuse image Markdown extraction for completed assistant messages across stream batches. */
@@ -1812,11 +1815,41 @@ export function buildRenderItems(
}
const workingDir = opts?.workingDir ?? '';
if (workingDir) {
+ const start = Date.parse(messages[lo]?.createdAt ?? '');
+ const end = Date.parse(messages[hi]?.createdAt ?? '');
+ const artifacts = (opts?.historyArtifacts ?? []).filter((artifact) => {
+ const time = Date.parse(artifact.createdAt);
+ return !(Number.isFinite(start) && time < start || Number.isFinite(end) && time >= end);
+ });
+ const editedPaths = new Set(artifacts.filter((file) => file.exclude && file.ready)
+ .map((file) => pathKey(resolveToolFilePath(file.path, workingDir))));
+ for (const artifact of artifacts) {
+ const path = resolveToolFilePath(artifact.path, workingDir);
+ const normalized = pathKey(path);
+ if (artifact.exclude) {
+ if (artifact.exclude === 'all' && artifact.ready) generatedByPath.delete(normalized);
+ continue;
+ }
+ if (artifact.source === 'command' && editedPaths.has(normalized)) continue;
+ if (exactPaths.has(normalized) && changeSets.length > 0) continue;
+ const previous = generatedByPath.get(normalized);
+ if (previous?.source === 'tool' && artifact.source === 'command') continue;
+ generatedByPath.set(normalized, { path, name: basename(path), source: artifact.source, ready: artifact.ready });
+ }
for (const file of collectCachedGeneratedFiles(slice, workingDir)) {
const normalized = pathKey(file.path);
if (exactPaths.has(normalized) && changeSets.length > 0) continue;
generatedByPath.set(normalized, file);
}
+ // Delivery tools stay as visible source rows. Preserve their existing
+ // intermediate-file suppression for paths produced by deferred tools too.
+ for (const message of slice) {
+ if (message.role !== 'tool_use') continue;
+ const descriptor = describeToolUse(message.toolName ?? '', message.toolInput);
+ for (const path of sourcePathCandidatesFromDescriptor(descriptor)) {
+ generatedByPath.delete(pathKey(resolveToolFilePath(path, workingDir)));
+ }
+ }
}
const generatedFiles = [...generatedByPath.values()];
if (generatedFiles.length === 0) return;
@@ -2816,10 +2849,11 @@ export function MessageStream({
(row.isPendingPersist === true ||
!!row.blockedByGhost ||
!!row.localSendPrecedingClientIds),
- build: (rows) => {
+ build: (rows, _streaming, historyArtifacts) => {
// History chunks are freshly assembled arrays, not reusable source snapshots.
const chunk = buildRenderItems([...rows], taskUpdates, ghostCardSnapshot, {
historyWindowIncomplete: true,
+ historyArtifacts,
workingDir,
botSessionId: simplifiedBotConversation ? sessionId : undefined,
markdownImageTargetCache: markdownImageTargetCacheRef.current,
@@ -2900,7 +2934,15 @@ export function MessageStream({
);
// subagent-model-chip: parentToolUseId(Agent/Task 行 id)→ 子代理模型,
// 供 AgentActionsBlock 给 Agent/Task 行反查并渲染模型 chip。
- const subagentModelByToolUseId = useMemo(() => buildSubagentModelMap(messages), [messages]);
+ const subagentModelByToolUseId = useMemo(() => {
+ const models = buildSubagentModelMap(messages);
+ for (const summary of historyWorkSummaries(historySnapshot?.items ?? [])) {
+ if (summary.parentToolUseId && summary.model && !models.has(summary.parentToolUseId)) {
+ models.set(summary.parentToolUseId, summary.model);
+ }
+ }
+ return models;
+ }, [messages, historySnapshot?.items]);
// work-group pass:把最终回答前的工作过程折叠成 work_group,无最终回答时
// 继续走旧的 tool_segment + thinking 折叠兼容路径。
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index caedb0229b..7737f12908 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -8065,6 +8065,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
const handleMakerStatusRaw = (raw: unknown, ingress: LiveIngressContext = {}) => {
if (!isCurrentLiveIngress(ingress)) return;
const payload = raw as { sessionId?: string; status?: string } | null;
+ if (payload?.sessionId) getRemoteHistoryView(payload.sessionId)?.invalidate();
if (!payload?.sessionId || payload.status !== 'closed') return;
bumpInteractionReconcileEpoch(payload.sessionId);
supersedeInputProjectionRequests(payload.sessionId, { supersedeOperations: true });
@@ -8436,6 +8437,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
const payload = raw as { sessionId?: string; message?: Message } | null;
if (!payload?.sessionId || !payload.message) return;
const { sessionId, message } = payload;
+ getRemoteHistoryView(sessionId)?.invalidate();
if (isBeforeOrAtRendererClearBoundary(sessionId, message.createdAt)) return;
const [mapped] = mapServerMessages([message]);
if (!mapped) return;
@@ -8544,6 +8546,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
turnUsageDetails?: unknown;
} | null;
if (!p?.sessionId || !p.clientId) return;
+ getRemoteHistoryView(p.sessionId)?.invalidate();
const turnCostIsEstimate = p.turnCostIsEstimate === true;
const turnUsageDetails = normalizeTurnUsageDetails(p.turnUsageDetails);
const normalizedTurnMoney = normalizeRegionalMoney(p.turnMoney);
@@ -11150,14 +11153,14 @@ export function getRemoteHistoryView(sessionId: string) {
function createRemoteHistoryView(sessionId: string) {
const existing = getRemoteHistoryView(sessionId);
const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
- if (!deviceId) return undefined;
+ if (!deviceId && (typeof window === 'undefined' || !window.electronAPI?.localDb?.messages?.historyView)) return undefined;
if (existing) return existing;
const entry = remoteHistoryViews.get(sessionId) ?? {
view: undefined, intentQueue: { tail: Promise.resolve() }, isCurrent: () => false,
};
const owner = getDataOwnerGeneration();
// Begin the protected disk read before taking write tokens for remote requests.
- const cached = readRemoteHistoryCache<HistoryChatMessage>(deviceId, sessionId);
+ const cached = deviceId ? readRemoteHistoryCache<HistoryChatMessage>(deviceId, sessionId) : Promise.resolve(null);
let writeCache: ReturnType<typeof remoteHistoryCacheWriter> | undefined;
let persistTimer: ReturnType<typeof setTimeout> | undefined;
const isCurrent = (): boolean => isDataOwnerGenerationCurrent(owner)
@@ -11168,20 +11171,25 @@ function createRemoteHistoryView(sessionId: string) {
}));
const call = async <T,>(channel: string, args: unknown[]): Promise<T> => {
if (!isCurrent()) throw new Error('History source changed');
- const value = await window.electronAPI.deviceLink.invoke(deviceId, channel, args);
+ const value = deviceId ? await window.electronAPI.deviceLink.invoke(deviceId, channel, args)
+ : channel === 'local-db:messages:view'
+ ? await window.electronAPI.localDb.messages.historyView(sessionId, args[1] as { before?: string; lazyDetails?: boolean })
+ : channel === 'local-db:messages:work-details'
+ ? await window.electronAPI.localDb.messages.workDetails(sessionId, args[1] as import('@cindy/maker-shared/message-window').HistoryWorkReference, args[2] as { after?: string })
+ : undefined;
if (!isCurrent()) throw new Error('History source changed');
return value as T;
};
const view = new HistoryViewController<HistoryChatMessage>({
page: async (before) => {
- const writer = remoteHistoryCacheWriter(deviceId, sessionId);
- const page = await call<HistoryViewPage<Message>>('local-db:messages:view', [sessionId, { before }]);
+ const writer = deviceId ? remoteHistoryCacheWriter(deviceId, sessionId) : undefined;
+ const page = await call<HistoryViewPage<Message>>('local-db:messages:view', [sessionId, { before, lazyDetails: true }]);
if (page == null) throw new Error('[CHANNEL_NOT_ALLOWED] History view is unavailable');
writeCache = writer;
return { ...page, items: mapHistoryViewMessages(page.items, mapRows) };
},
details: async (ref, after) => {
- const writer = remoteHistoryCacheWriter(deviceId, sessionId);
+ const writer = deviceId ? remoteHistoryCacheWriter(deviceId, sessionId) : undefined;
const page = await call<HistoryDetailPage<Message>>('local-db:messages:work-details', [sessionId, ref, { after }]);
writeCache = writer;
return { ...page, messages: mapRows(page.messages) };
@@ -11190,7 +11198,7 @@ function createRemoteHistoryView(sessionId: string) {
// Releasing an old view must still clear its original Host's interest.
// The existing intent queue orders this after any in-flight expand.
if (!refs.length) {
- if (isDataOwnerGenerationCurrent(owner)) {
+ if (deviceId && isDataOwnerGenerationCurrent(owner)) {
await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:messages:view-intent', [sessionId, []]);
}
} else await call<void>('local-db:messages:view-intent', [sessionId, refs]);
@@ -11199,7 +11207,7 @@ function createRemoteHistoryView(sessionId: string) {
entry.view = view;
entry.isCurrent = isCurrent;
remoteHistoryViews.set(sessionId, entry);
- view.setNetworkAvailable(!isRemoteDeviceMarkedDisconnected(deviceId));
+ view.setNetworkAvailable(!deviceId || !isRemoteDeviceMarkedDisconnected(deviceId));
view.subscribe(() => {
if (persistTimer) clearTimeout(persistTimer);
if (!isCurrent() || !sessions.has(sessionId)) return;
@@ -12105,15 +12113,26 @@ function reconcileRemoteMessages(sessionId: string, opts?: {
{
// readPage starts expanded details without awaiting them. Join those
// same reads before certifying receipts; their display may still be old.
- // Force repair also needs collapsed details to hydrate lost live rows.
- await Promise.all(historyWorkSummaries(view.getSnapshot().items)
- .filter((summary) => opts?.force || view.getSnapshot().expanded.has(summary.key))
- .map((summary) => view.loadDetails(summary, { allowCollapsed: opts?.force })));
+ // Historical folded bodies stay lazy. A force recovery must still seal
+ // live rows already on screen when their final push was lost; only
+ // ranges containing those rows may be read without user expansion.
+ const liveRows = opts?.force ? [...rowsAtStart.values()].filter((row) => row.isStreaming) : [];
+ const summaries = historyWorkSummaries(view.getSnapshot().items);
+ const recoveryKeys = new Set(summaries.filter((summary) => liveRows.some((row) => {
+ if (summary.parentToolUseId && !row.parentToolUseId) return false;
+ const createdAt = Date.parse(row.createdAt ?? '');
+ return row.clientId === summary.anchorClientId
+ || (createdAt >= summary.startedAtMs && createdAt <= summary.endedAtMs);
+ })).map((summary) => summary.key));
+ await Promise.all(summaries
+ .filter((summary) => recoveryKeys.has(summary.key) || view.getSnapshot().expanded.has(summary.key))
+ .map((summary) => recoveryKeys.has(summary.key)
+ ? view.loadDetails(summary, { allowCollapsed: true }) : view.loadDetails(summary)));
if (getRemoteHistoryView(sessionId) !== view || !view.isActive()
|| (_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return false;
const detailsSnapshot = view.getSnapshot();
const incompleteDetails = historyWorkSummaries(detailsSnapshot.items).some((summary) => {
- if (!opts?.force && !detailsSnapshot.expanded.has(summary.key)) return false;
+ if (!recoveryKeys.has(summary.key) && !detailsSnapshot.expanded.has(summary.key)) return false;
const detail = detailsSnapshot.details.get(summary.key);
return !detail?.complete || !!detail.error || detail.revision !== summary.revision;
});
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2bdc3b0558..6fc5101076 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4991,6 +4991,8 @@ interface ElectronAPI {
resetCollaborationSettings: () => Promise<unknown>;
};
messages: {
+ historyView: (sessionId: string, opts?: { before?: string | null; lazyDetails?: boolean }) => Promise<import('@cindy/maker-shared/message-window').HistoryViewPage<import('@/lib/ccAgent.types').Message>>;
+ workDetails: (sessionId: string, ref: import('@cindy/maker-shared/message-window').HistoryWorkReference, opts?: { after?: string | null }) => Promise<import('@cindy/maker-shared/message-window').HistoryDetailPage<import('@/lib/ccAgent.types').Message>>;
list: (
sessionId: string,
opts?: { limit?: number; before?: string; beforeTs?: number },
diff --git a/apps/desktop/src/shared/remoteHistoryCache.ts b/apps/desktop/src/shared/remoteHistoryCache.ts
index f55c283448..b074344043 100644
--- a/apps/desktop/src/shared/remoteHistoryCache.ts
+++ b/apps/desktop/src/shared/remoteHistoryCache.ts
@@ -47,6 +47,13 @@ function validSummary(value: unknown, depth: number): boolean {
(key) => typeof value[key] === 'number' && Number.isFinite(value[key]),
) &&
typeof value.isStreaming === 'boolean' &&
+ (value.parentToolUseId === undefined || typeof value.parentToolUseId === 'string') &&
+ (value.model === undefined || typeof value.model === 'string') &&
+ (value.artifacts === undefined || Array.isArray(value.artifacts) && value.artifacts.every((file) =>
+ record(file) && typeof file.path === 'string' && typeof file.createdAt === 'string'
+ && (file.source === 'tool' || file.source === 'command')
+ && (file.ready === undefined || typeof file.ready === 'boolean')
+ && (file.exclude === undefined || file.exclude === 'all' || file.exclude === 'command'))) &&
(value.preview === undefined || validSummary(value.preview, depth + 1))
);
}
@@ -60,7 +67,7 @@ function validItems(value: unknown, depth = 0): boolean {
record(item) &&
typeof item.key === 'string' &&
(item.type === 'messages'
- ? validRows(item.messages)
+ ? validRows(item.messages) && (item.deferred === undefined || validSummary(item.deferred, depth))
: item.type === 'work' &&
validSummary(item.summary, depth) &&
(item.children === undefined || validItems(item.children, depth + 1))),
diff --git a/apps/mobile/src/__tests__/mobileHistoryRender.test.ts b/apps/mobile/src/__tests__/mobileHistoryRender.test.ts
index c639b32b8a..536173f02a 100644
--- a/apps/mobile/src/__tests__/mobileHistoryRender.test.ts
+++ b/apps/mobile/src/__tests__/mobileHistoryRender.test.ts
@@ -3,6 +3,7 @@ import { HistoryViewController, projectHistoryView, type HistoryWorkSummary } fr
import { buildMobileHistoryRenderItems } from '../session/mobileHistoryRender';
import { buildMobileMessageRenderItems, type MobileMessageRenderItem } from '../session/messageRenderModel';
import type { RemoteMessage } from '../session/types';
+import { reconcileMobileMessageRenderItems } from '../session/messageRenderReconcile';
function row(index: number, role: RemoteMessage['role'], content: unknown, toolUseId: string | null = null): RemoteMessage {
return { id: `id-${index}`, clientId: `client-${index}`, sessionId: 'session', role, content, toolUseId,
@@ -14,7 +15,7 @@ const outline = (items: MobileMessageRenderItem[]): unknown[] => items.map((item
? { key: item.key, type: item.type, children: outline(item.children.filter((child) => child.type === 'work_group' || child.type === 'message')) }
: { key: item.key, type: item.type });
-function harness(rows: RemoteMessage[], streaming = false) {
+function harness(rows: RemoteMessage[], streaming = false, lazyDetails = false) {
const details = vi.fn(async (summary: HistoryWorkSummary, after?: string) => {
const start = rows.findIndex((item) => item.id === (after ?? summary.firstMessageId)) + (after ? 1 : 0);
const end = rows.findIndex((item) => item.id === summary.lastMessageId) + 1;
@@ -23,7 +24,7 @@ function harness(rows: RemoteMessage[], streaming = false) {
});
const expanded = vi.fn(async (_refs: readonly HistoryWorkSummary[]) => undefined);
const view = new HistoryViewController<RemoteMessage>({
- page: async () => ({ version: 1, items: projectHistoryView(rows, streaming), hasMore: false, nextCursor: null }),
+ page: async () => ({ version: 1, items: projectHistoryView(rows, streaming, lazyDetails), hasMore: false, nextCursor: null }),
details, expanded,
});
const render = () => buildMobileHistoryRenderItems({ view, snapshot: view.getSnapshot(), messages: [], streaming, sessionId: 'session' });
@@ -118,11 +119,13 @@ describe('remote history preserves original folding', () => {
['explicit user boundary', [row(0, 'user', 'First'), thought(1), row(2, 'assistant', 'Done'), row(3, 'user', 'Second'), thought(4), row(5, 'assistant', 'Done')]],
] as const)('keeps the same group identities and nesting: %s', async (_name, fixture) => {
const rows = [...fixture];
- const { view, render, details } = harness(rows);
+ for (const lazyDetails of [false, true]) {
+ const { view, render, details } = harness(rows, false, lazyDetails);
await view.refresh();
expect(outline(render())).toEqual(outline(buildMobileMessageRenderItems(rows, { isSessionStreaming: false })));
expect(details).not.toHaveBeenCalled();
view.setActive(false);
+ }
});
it('opens only the chosen inner group, reads all pages, and retains the outer hierarchy', async () => {
@@ -170,3 +173,32 @@ describe('remote history preserves original folding', () => {
view.setActive(false);
});
});
+
+
+it.each([true, false])('loads a folded subagent only on expansion while retaining the visible turn (running=%s)', async (streaming) => {
+ const agent = { ...call(1, 'Agent', 'a'), content: { toolName: 'Agent', toolUseId: 'a', input: { description: 'Inspect' } } };
+ const children = Array.from({ length: 40 }, (_, i) => ({ ...thought(i + 2), agentMeta: { parentUuid: 'a' } }));
+ const rows = [row(0, 'user', 'Investigate'), agent, ...children, row(42, 'assistant', 'Visible response')];
+ const { view, details, render } = harness(rows, streaming, true);
+ await view.refresh();
+ expect(details).not.toHaveBeenCalled();
+ const first = render();
+ expect(first.some((item) => item.type === 'message' && item.message.body === 'Visible response')).toBe(true);
+ const card = first.find((item) => item.type === 'subagent_group');
+ if (card?.type !== 'subagent_group') throw new Error('missing card');
+ expect(card.childItems).toEqual([]);
+ expect(card.status).toBe(streaming ? 'running' : 'completed');
+ expect(card.deferred).toBeDefined();
+ card.deferred!.toggle();
+ await vi.waitFor(() => expect(view.getSnapshot().details.get(card.deferred!.key!)?.complete).toBe(true));
+ expect(details).toHaveBeenCalledTimes(20);
+ const expanded = render().find((item) => item.type === 'subagent_group');
+ expect(expanded?.type === 'subagent_group' && expanded.childItems.length).toBeGreaterThan(0);
+ expect(expanded?.type === 'subagent_group' && expanded.deferred?.loading).toBe(false);
+ if (expanded?.type === 'subagent_group' && expanded.deferred) {
+ const pending = { ...expanded, deferred: { ...expanded.deferred, loading: true } };
+ const reconciled = reconcileMobileMessageRenderItems([pending], [expanded]);
+ expect(reconciled[0]).toBe(expanded);
+ }
+ view.setActive(false);
+});
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index ce2dbe4bb7..ba4037e7be 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -1023,7 +1023,7 @@ export function createMobileMakerTransport({
listMessages: (sessionId, opts) =>
call("local-db:messages:list", [sessionId, opts]),
readHistoryView: (sessionId, before) =>
- call("local-db:messages:view", [sessionId, { before }]),
+ call("local-db:messages:view", [sessionId, { before, lazyDetails: true }]),
readWorkDetails: (sessionId, ref, after) =>
call("local-db:messages:work-details", [sessionId, ref, { after }]),
setHistoryExpanded: (sessionId, refs) =>
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index a2540774f5..0836a2db27 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -4660,6 +4660,12 @@ function SubagentCard({
const { colors } = useTheme();
const { t } = useTranslation();
const styles = useThemedStyles(makeStyles);
+ const [expanded, toggleExpanded] = useFoldableExpandedState(item.key, false);
+ const deferred = item.deferred;
+ useEffect(() => {
+ deferred?.setVisible?.(expanded, false);
+ return () => deferred?.setVisible?.(false, false);
+ }, [deferred?.owner, deferred?.key, expanded]);
const title = item.header.subagentType
? t('message.renderer.subagentTyped', { type: item.header.subagentType })
: t('message.renderer.subagent');
@@ -4670,6 +4676,8 @@ function SubagentCard({
return (
<CollabCardShell
blockId={item.key}
+ controlledExpanded={expanded}
+ onControlledToggle={toggleExpanded}
leadingIcon={<Bot color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />}
title={title}
subtitle={subtitle || undefined}
@@ -4678,6 +4686,18 @@ function SubagentCard({
>
{(layout) => (
<View style={[styles.stack, { gap: layout.stackGap }]}>
+ {deferred?.loading ? <CompactActivityIndicator color={colors.textTertiary} size={iconSize.md} /> : null}
+ {deferred?.failed ? (
+ <MessageListActionButton
+ accessibilityLabel={t('message.renderer.retryPreview')}
+ disabled={deferred.loading}
+ onPress={deferred.retry}
+ style={[styles.payloadOpenButton, { minHeight: MESSAGE_CONTROL_TOUCH_SIZE, minWidth: MESSAGE_CONTROL_TOUCH_SIZE }]}
+ testID="message.subagentDetailsRetry"
+ >
+ <Text style={styles.payloadOpenButtonText}>{t('message.renderer.retryPreview')}</Text>
+ </MessageListActionButton>
+ ) : null}
{/* 两级展开(与 WorkGroupCard 同规则):内层子卡保持各自折叠头行,按需下钻。 */}
{item.childItems.map((child) => (
<RenderItemView key={child.key} item={child} actions={actions} />
diff --git a/apps/mobile/src/session/messageRenderModel.ts b/apps/mobile/src/session/messageRenderModel.ts
index 5d3ba1d4dc..8365c98e16 100644
--- a/apps/mobile/src/session/messageRenderModel.ts
+++ b/apps/mobile/src/session/messageRenderModel.ts
@@ -1,3 +1,4 @@
+import type { DeferredHistoryWork } from '@cindy/maker-shared/message-window';
import {
buildMessageRenderItems,
extractTodosFromSourceMessage,
@@ -42,6 +43,8 @@ export type MobileWorkGroupItem = MessageRenderWorkGroupItem<NormalizedRemoteMes
*/
export interface MobileSubagentGroupItem {
type: 'subagent_group';
+ sourceClientId?: string;
+ deferred?: DeferredHistoryWork;
key: string;
header: { description: string | null; subagentType: string | null };
/** 子 agent 内层 render items(递归,可含更深 subagent_group)。 */
diff --git a/apps/mobile/src/session/messageRenderReconcile.ts b/apps/mobile/src/session/messageRenderReconcile.ts
index f92ef6121c..f0018ebd02 100644
--- a/apps/mobile/src/session/messageRenderReconcile.ts
+++ b/apps/mobile/src/session/messageRenderReconcile.ts
@@ -5,9 +5,17 @@ import type {
} from '@/session/messageRenderModel';
import type { RemoteMessage } from '@/session/types';
import { deepValueEqual } from '@/utils/valueEquality';
+import type { DeferredHistoryWork } from '@cindy/maker-shared/message-window';
type ReconciledRenderItem = MobileMessageRenderItem | MobileWorkChildItem;
+function sameDeferred(a?: DeferredHistoryWork, b?: DeferredHistoryWork): boolean {
+ if (!a || !b) return a === b;
+ return a.owner === b.owner && a.key === b.key && a.revision === b.revision
+ && a.expanded === b.expanded && a.loading === b.loading && a.failed === b.failed
+ && a.previewComplete === b.previewComplete;
+}
+
/**
* Reuse semantically unchanged message-row view models between render-model rebuilds.
*
@@ -131,6 +139,7 @@ function reconcileRenderItem(
&& prior.durationMs === next.durationMs
&& prior.isStreaming === next.isStreaming
&& prior.startedAtMs === next.startedAtMs
+ && sameDeferred(prior.deferred, next.deferred)
) {
return prior;
}
@@ -146,6 +155,7 @@ function reconcileRenderItem(
&& prior.summary === next.summary
&& prior.status === next.status
&& prior.durationMs === next.durationMs
+ && sameDeferred(prior.deferred, next.deferred)
) {
return prior;
}
diff --git a/apps/mobile/src/session/mobileHistoryRender.ts b/apps/mobile/src/session/mobileHistoryRender.ts
index 92cc39b998..7035094947 100644
--- a/apps/mobile/src/session/mobileHistoryRender.ts
+++ b/apps/mobile/src/session/mobileHistoryRender.ts
@@ -30,12 +30,13 @@ export function buildMobileHistoryRenderItems(options: {
}),
children: (item) => item.type === 'work_group' ? item.children
: item.type === 'subagent_group' ? item.childItems : undefined,
- sourceIds: (item) => item.type === 'message' || item.type === 'thinking' ? [item.message.source.clientId]
+ sourceIds: (item) => item.type === 'subagent_group' && item.sourceClientId ? [item.sourceClientId]
+ : item.type === 'message' || item.type === 'thinking' ? [item.message.source.clientId]
: item.type === 'tool_group' || item.type === 'tool_media' ? item.tools.map((tool) => tool.source.clientId)
: item.type === 'agent_task' && item.toolCall ? [item.toolCall.source.clientId] : [],
rebuild: (item, children, deferred) => item.type === 'work_group'
? { ...item, children: children as MobileWorkChildItem[], deferred }
- : item.type === 'subagent_group' ? { ...item, childItems: children } : item,
+ : item.type === 'subagent_group' ? { ...item, childItems: children, deferred } : item,
},
});
}
diff --git a/apps/mobile/src/session/remoteHistoryDiskCache.ts b/apps/mobile/src/session/remoteHistoryDiskCache.ts
index 8dfe652df3..e3c008fe26 100644
--- a/apps/mobile/src/session/remoteHistoryDiskCache.ts
+++ b/apps/mobile/src/session/remoteHistoryDiskCache.ts
@@ -32,6 +32,7 @@ function validSummary(value: unknown, depth = 0): boolean {
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]))
+ && (s.parentToolUseId === undefined || typeof s.parentToolUseId === 'string')
&& typeof s.isStreaming === 'boolean' && (!s.preview || validSummary(s.preview, depth + 1));
}
function validItems(value: unknown, depth = 0): boolean {
@@ -39,7 +40,7 @@ function validItems(value: unknown, depth = 0): boolean {
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')
+ && typeof m.createdAt === 'string') && (!item.deferred || validSummary(item.deferred))
: item.type === 'work' && validSummary(item.summary)
&& (!item.children || validItems(item.children, depth + 1))
));
@@ -78,7 +79,7 @@ export async function writeHistoryDisk(authority: Authority, snapshot: HistoryVi
...(value.preview ? { preview: summary(value.preview) } : {}),
});
const items = (values: readonly HistoryViewItem<RemoteMessage>[]): HistoryViewItem<RemoteMessage>[] => values.map(item =>
- item.type === 'messages' ? { ...item, messages: messages(item.messages) }
+ item.type === 'messages' ? { ...item, messages: messages(item.messages), ...(item.deferred ? { deferred: summary(item.deferred) } : {}) }
: { ...item, summary: summary(item.summary), ...(item.children ? { children: items(item.children) } : {}) });
const text = JSON.stringify({ version: 1, items: items(snapshot.items),
details: [...snapshot.details].filter(([, detail]) => detail.complete && !detail.loading && !detail.error)
diff --git a/apps/mobile/src/session/subagentGrouping.ts b/apps/mobile/src/session/subagentGrouping.ts
index e8caa01846..b86ae0b866 100644
--- a/apps/mobile/src/session/subagentGrouping.ts
+++ b/apps/mobile/src/session/subagentGrouping.ts
@@ -156,6 +156,7 @@ function buildSubagentGroup(
: undefined;
return {
type: 'subagent_group',
+ sourceClientId: agent.source.clientId,
key: `subagent-${id ?? agent.key}`,
header: { description, subagentType },
childItems,
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 0835f421d7..72b4912f3a 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -69,6 +69,19 @@ Mobile 未新增卡片入口。服务端无需改动。
## 手机首页会话活动快照
+### 可见历史优先读取
+
+`local-db:messages:view` 的可选 `{ lazyDetails: true }` 启用轻量历史投影:
+被控 Desktop 先读取分组所需字段,再只按 ID 读取本页可见正文和卡片。
+隐藏子代理记录通过 `messages.deferred` 保存范围,展开后由既有
+`local-db:messages:work-details` 分页读取;可选 `parentToolUseId` 限制到该子代理及其后代,
+不会顺带加载同一时间段的其它子代理。摘要可携带轻量文件产物候选及排除信息,
+文件卡原有的存在性、时间窗与权限校验不变。媒体和文档交付仍保留原始可见来源。
+
+旧控制端不请求该选项,收到原有投影;旧主机忽略选项,新控制端继续兼容原投影和原有
+raw history 降级。任务列表活动推送不变,当前轮的正文、工具卡和可见进度继续实时更新。
+没有新增 channel、relay 类型、数据库 schema 或 Mobile 原生依赖,云端无需改动。
+
现有 `maker:list-active` 的可选 `{ summary: true }` 响应在运行标记之外增加
`activityPhase` / `activityAttention` 两个可选字段。被控端从现有会话活动投影提供这两个
状态字段;活动服务已就绪但该会话不在活动账本中时,明确返回 `idle` / `false`,不下发活动正文。
diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.ts
index 81f2ad6647..c91db9f939 100644
--- a/packages/maker-shared/src/__tests__/historyView.test.ts
+++ b/packages/maker-shared/src/__tests__/historyView.test.ts
@@ -85,6 +85,26 @@ describe('automatic process detail reading', () => {
import { HistoryViewController } from '../historyViewController.js';
import { renderHistoryView } from '../historyViewRender.js';
+
+it('does not bind subagent detail fetching to a desktop summary-only enclosing group', async () => {
+ const source = [row(0, 'user', 'Question'), row(1, 'tool_use', { toolName: 'Agent', toolUseId: 'toolu_a', input: {} }),
+ { ...row(2, 'thinking', 'Internal'), agentMeta: { parentUuid: 'toolu_a' } }, row(3, 'assistant', 'Answer')];
+ const details = vi.fn();
+ const view = new HistoryViewController<HistoryMessageSource>({
+ page: async () => ({ version: 1, items: projectHistoryView(source, false, true), hasMore: false, nextCursor: null }),
+ details, expanded: async () => undefined,
+ });
+ await view.refresh();
+ type Item = { ids: string[]; children?: Item[]; deferred?: unknown };
+ const rendered = renderHistoryView<HistoryMessageSource, Item>({ view, snapshot: view.getSnapshot(), liveMessages: [], streaming: false,
+ build: () => [{ ids: [], children: [{ ids: ['c1'] }] }],
+ structure: { placeholder: () => source[0], children: (item) => item.children, sourceIds: (item) => item.ids,
+ rebuild: (item, children, deferred) => ({ ...item, children, deferred }) },
+ });
+ expect(rendered[0].deferred).toBeUndefined();
+ expect(details).not.toHaveBeenCalled();
+ view.setActive(false);
+});
import type { HistoryViewPage } from '../historyView.js';
const ungroupedStructure = {
placeholder: (summary: import('../historyView.js').HistoryWorkSummary) => ({ ...row(1, 'thinking', ''),
diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.ts
index 7b73a17386..d122b78eec 100644
--- a/packages/maker-shared/src/historyView.ts
+++ b/packages/maker-shared/src/historyView.ts
@@ -8,6 +8,17 @@ export function isHistoryViewUnavailable(error: unknown): boolean {
return /CHANNEL_NOT_ALLOWED|UNSUPPORTED_CAPABILITY|not registered|No handler/i.test(String(error));
}
+/** Visible file candidates, independent of the folded tool body that produced them. */
+export interface HistoryFileArtifact {
+ path: string;
+ source: 'tool' | 'command';
+ createdAt: string;
+ toolUseId?: string;
+ ready?: boolean;
+ /** Preserve file-card suppression when the editing tool body is deferred. */
+ exclude?: 'command' | 'all';
+}
+
export interface HistoryMessageSource {
id: string;
clientId: string;
@@ -17,6 +28,8 @@ export interface HistoryMessageSource {
rowid?: number;
toolUseId?: string | null;
agentMeta?: object | null;
+ /** Host outline only; transferred in work summaries, never as a replacement body. */
+ historyArtifacts?: HistoryFileArtifact[];
}
/** Both endpoints are real host message IDs, inclusive, in host database order. */
@@ -28,11 +41,16 @@ export interface HistoryWorkReference {
firstStoredMessageId?: string;
lastStoredMessageId?: string;
liveMessageIds?: string[];
+ /** Restricts a subagent detail range to this tool and its descendants. */
+ parentToolUseId?: string;
}
export interface HistoryWorkSummary extends HistoryWorkReference {
/** Original activity anchor; stable when its body has not been read yet. */
anchorClientId?: string;
+ artifacts?: HistoryFileArtifact[];
+ /** Actual child model from persisted metadata; not the requested model. */
+ model?: string;
/** Existing detail endpoint can read just the visible desktop tail. */
preview?: HistoryWorkSummary;
startedAtMs: number;
@@ -48,6 +66,7 @@ export interface HistoryWorkSummary extends HistoryWorkReference {
export interface DeferredHistoryWork {
owner?: object;
key?: string;
+ revision?: string;
setVisible?(expanded: boolean, preview: boolean): void;
previewComplete?: boolean;
expanded: boolean;
@@ -58,7 +77,7 @@ export interface DeferredHistoryWork {
}
export type HistoryViewItem<TMessage extends HistoryMessageSource> =
- | { type: 'messages'; key: string; messages: TMessage[] }
+ | { type: 'messages'; key: string; messages: TMessage[]; deferred?: HistoryWorkSummary }
| { type: 'work'; key: string; summary: HistoryWorkSummary; children?: HistoryViewItem<TMessage>[] };
/** Outer summaries retain only prose and action references, never hidden bodies. */
@@ -68,7 +87,7 @@ export function historyViewLeaves<T extends HistoryMessageSource>(items: readonl
export function historyWorkSummaries<T extends HistoryMessageSource>(items: readonly HistoryViewItem<T>[]): HistoryWorkSummary[] {
return historyViewLeaves(items).flatMap((item) => item.type === 'work'
- ? [item.summary, ...(item.summary.preview ? [item.summary.preview] : [])] : []);
+ ? [item.summary, ...(item.summary.preview ? [item.summary.preview] : [])] : item.deferred ? [item.deferred] : []);
}
export function mapHistoryViewMessages<T extends HistoryMessageSource, U extends HistoryMessageSource>(
diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.ts
index 8a2fb8102b..ca287c936f 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -271,13 +271,14 @@ export class HistoryViewController<T extends HistoryMessageSource> {
if (item.type === 'messages') {
const found = item.messages.find((row) => row.clientId === clientId);
if (found) return found;
- } else if (!tried.has(item.key) && targetMs >= item.summary.startedAtMs && targetMs <= item.summary.endedAtMs) {
- tried.add(item.key);
- const summary = item.summary;
+ }
+ const summary = item.type === 'work' ? item.summary : item.deferred;
+ if (summary && !tried.has(summary.key) && targetMs >= summary.startedAtMs && targetMs <= summary.endedAtMs) {
+ tried.add(summary.key);
const current = () => this.active && generation === this.generation
&& historyWorkSummaries(this.state.items).some((value) => value.key === summary.key && value.revision === summary.revision
&& value.firstMessageId === summary.firstMessageId && value.lastMessageId === summary.lastMessageId);
- const cached = this.state.details.get(item.key);
+ const cached = this.state.details.get(summary.key);
let messages = cached?.complete && cached.revision === summary.revision ? [...cached.messages] : [];
if (!messages.length && this.networkAvailable) {
// Search reads the bounded range without changing user expansion memory
@@ -294,7 +295,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
}
if (!current()) return null;
const details = new Map(this.state.details);
- details.set(item.key, { messages, revision: summary.revision, lastMessageId: summary.lastMessageId,
+ details.set(summary.key, { messages, revision: summary.revision, lastMessageId: summary.lastMessageId,
loading: false, complete: true, error: null });
this.publish({ details });
}
diff --git a/packages/maker-shared/src/historyViewProjection.ts b/packages/maker-shared/src/historyViewProjection.ts
index ede220cfb7..29a35fcbec 100644
--- a/packages/maker-shared/src/historyViewProjection.ts
+++ b/packages/maker-shared/src/historyViewProjection.ts
@@ -1,4 +1,5 @@
import { groupWorkRuns } from './workRunGrouping.js';
+import { describeToolUse } from './toolUseDescriptor.js';
import { isAgentPlanToolName, isDeliveryProseText } from './messageRender.js';
import { isAgentTaskToolName } from './agentTask.js';
import { extractPayloadToolResultMedia, extractPayloadToolResultFiles, extractPayloadToolCardIds } from './payloadSummary.js';
@@ -33,6 +34,13 @@ export function hasVisibleHistoryResult(content: unknown): boolean {
} catch { return false; }
}
+function hasFileDelivery(row: HistoryMessageSource): boolean {
+ if (row.role !== 'tool_use') return false;
+ const tool = parseMessageToolUse(row);
+ const descriptor = describeToolUse(tool.toolName, tool.input);
+ return descriptor.kind === 'mcp' && !!descriptor.createdPath;
+}
+
/**
* Uses the same turn/seal/delivery boundaries as both renderers. Unknown cards and
* reference-bearing results stay as source rows, so platform presentation keeps
@@ -41,6 +49,62 @@ export function hasVisibleHistoryResult(content: unknown): boolean {
export function projectHistoryView<T extends HistoryMessageSource>(
rows: readonly T[],
streaming: boolean,
+ lazyDetails = false,
+): HistoryViewItem<T>[] {
+ if (lazyDetails) {
+ const scopes = historySubagentScopes(rows);
+ const visibleTools = new Set(rows.filter((row) => row.role === 'tool_result' && hasVisibleHistoryResult(row.content)).map((row) => row.toolUseId));
+ for (const row of rows) if (hasFileDelivery(row)) visibleTools.add(parseMessageToolUse(row).toolUseId);
+ const children = new Map<string, T[]>();
+ const visible = rows.filter((row) => {
+ const parent = scopes.get(row.id);
+ // Visible artifacts remain available to the desktop's media hoisting.
+ const toolId = row.role === 'tool_use' ? parseMessageToolUse(row).toolUseId : row.toolUseId;
+ if (!parent || (toolId && visibleTools.has(toolId))) return true;
+ const bucket = children.get(parent) ?? [];
+ bucket.push(row);
+ children.set(parent, bucket);
+ return false;
+ });
+ const results = new Map(rows.filter((row) => row.role === 'tool_result').map((row) => [row.toolUseId, row]));
+ const withArtifacts = (row: T): T => row.historyArtifacts?.length ? { ...row, historyArtifacts:
+ row.historyArtifacts.filter((file) => {
+ const result = file.toolUseId && results.get(file.toolUseId);
+ return !result || !messageContentToPreview(result.content).includes('<tool_use_error>');
+ }).map((file) => ({ ...file, ready: !file.toolUseId || results.has(file.toolUseId) })) } : row;
+ const projected = projectHistorySourceView(visible.map(withArtifacts), streaming, false);
+ const attach = (items: HistoryViewItem<T>[]): HistoryViewItem<T>[] => items.map((item) => {
+ if (item.type === 'work') return { ...item, ...(item.children ? { children: attach(item.children) } : {}) };
+ const header = item.messages.find((row) => row.role === 'tool_use');
+ const toolId = header && parseMessageToolUse(header).toolUseId;
+ const body = toolId ? children.get(toolId) : undefined;
+ if (!header || !toolId || !body?.length) return item;
+ const first = body[0], last = body[body.length - 1];
+ const model = body.map((row) => row.agentMeta as { parentUuid?: string; model?: unknown } | null)
+ .find((meta) => meta?.parentUuid === toolId && typeof meta.model === 'string' && meta.model)?.model;
+ return { ...item, deferred: {
+ key: `subagent-work-${header.clientId}`, anchorClientId: header.clientId,
+ parentToolUseId: toolId,
+ ...(typeof model === 'string' ? { model } : {}),
+ firstMessageId: first.id, lastMessageId: last.id,
+ ...(body.some((row) => row.id.startsWith('history-live:')) ? {
+ firstStoredMessageId: body.find((row) => !row.id.startsWith('history-live:'))?.id,
+ lastStoredMessageId: [...body].reverse().find((row) => !row.id.startsWith('history-live:'))?.id,
+ liveMessageIds: body.filter((row) => row.id.startsWith('history-live:')).map((row) => row.id),
+ } : {}),
+ startedAtMs: Date.parse(first.createdAt), endedAtMs: Date.parse(last.createdAt),
+ artifacts: body.flatMap((row) => withArtifacts(row).historyArtifacts ?? []),
+ messageCount: body.length, toolCount: body.filter((row) => row.role === 'tool_use').length,
+ isStreaming: streaming, revision: `${last.id}:${body.length}`,
+ } };
+ });
+ return attach(projected);
+ }
+ return projectHistorySourceView(rows, streaming, true);
+}
+
+function projectHistorySourceView<T extends HistoryMessageSource>(
+ rows: readonly T[], streaming: boolean, preserveMixedSegments: boolean,
): HistoryViewItem<T>[] {
const names = new Map<string, string>();
const visibleResults = new Set<string>();
@@ -49,6 +113,7 @@ export function projectHistoryView<T extends HistoryMessageSource>(
if (row.role === 'tool_use') {
const tool = parseMessageToolUse(row);
if (tool.toolUseId) names.set(tool.toolUseId, tool.toolName);
+ if (!preserveMixedSegments && tool.toolUseId && hasFileDelivery(row)) visibleResults.add(tool.toolUseId);
if (tool.toolUseId && (row.agentMeta as { parentUuid?: unknown } | null)?.parentUuid) nestedCalls.add(tool.toolUseId);
}
if (row.role === 'tool_result' && row.toolUseId && hasVisibleHistoryResult(row.content)) {
@@ -68,7 +133,7 @@ export function projectHistoryView<T extends HistoryMessageSource>(
: !!thought?.text || !!thought?.durationMs || thought?.isRedacted === true);
const activity = !nested && (visibleThinking || (
(row.role === 'tool_use' || row.role === 'tool_result')
- && isHistoryDetailTool(toolName ?? '')
+ && (isHistoryDetailTool(toolName ?? '') || (!preserveMixedSegments && ['Edit', 'Write', 'MultiEdit', 'edit', 'write'].includes(toolName ?? '')))
&& !(toolId && visibleResults.has(toolId))
));
const plainAssistant = !nested && row.role === 'assistant' && typeof row.content === 'string'
@@ -83,7 +148,8 @@ export function projectHistoryView<T extends HistoryMessageSource>(
// between its tools, which would move the media and create an extra work group.
let toolSegment: SourceItem<T>[] = [];
const flushToolSegment = () => {
- if (toolSegment.some((item) => !item.activity)) {
+ if ((preserveMixedSegments || toolSegment.some((item) => item.row.role === 'tool_result' && hasVisibleHistoryResult(item.row.content)))
+ && toolSegment.some((item) => !item.activity)) {
for (const item of toolSegment) { item.activity = false; item.archivable = false; }
}
toolSegment = [];
@@ -121,6 +187,7 @@ export function projectHistoryView<T extends HistoryMessageSource>(
} : {}),
startedAtMs: Number.isFinite(startedAtMs) ? startedAtMs : 0,
endedAtMs: Number.isFinite(endedAtMs) ? endedAtMs : 0,
+ ...(run.some((item) => item.row.historyArtifacts?.length) ? { artifacts: run.flatMap((item) => item.row.historyArtifacts ?? []) } : {}),
messageCount: run.length,
toolCount: run.filter((item) => item.row.role === 'tool_use').length,
isStreaming: active,
@@ -192,3 +259,29 @@ export function projectHistoryView<T extends HistoryMessageSource>(
});
return grouped.map(toViewItem);
}
+
+/** Resolve complete subagent trees without making orphan rows disappear. */
+export function historySubagentScopes(rows: readonly HistoryMessageSource[], rootToolUseId?: string): Map<string, string> {
+ const parents = new Map<string, string>();
+ const agents = new Set<string>(rootToolUseId ? [rootToolUseId] : []);
+ for (const row of rows) {
+ if (row.role !== 'tool_use') continue;
+ const tool = parseMessageToolUse(row);
+ if (!tool.toolUseId) continue;
+ if (tool.toolName === 'Agent') agents.add(tool.toolUseId);
+ const parent = (row.agentMeta as { parentUuid?: string } | null)?.parentUuid;
+ if (parent) parents.set(tool.toolUseId, parent);
+ }
+ const result = new Map<string, string>();
+ for (const row of rows) {
+ let parent = (row.agentMeta as { parentUuid?: string } | null)?.parentUuid
+ || (row.toolUseId ? parents.get(row.toolUseId) : undefined);
+ if (!parent || !agents.has(parent)) continue;
+ const seen = new Set<string>();
+ while (parents.has(parent) && agents.has(parents.get(parent)!) && !seen.has(parent)) {
+ seen.add(parent); parent = parents.get(parent)!;
+ }
+ result.set(row.id, parent);
+ }
+ return result;
+}
diff --git a/packages/maker-shared/src/historyViewRender.ts b/packages/maker-shared/src/historyViewRender.ts
index d7768096b8..9c11d7e6dd 100644
--- a/packages/maker-shared/src/historyViewRender.ts
+++ b/packages/maker-shared/src/historyViewRender.ts
@@ -1,4 +1,4 @@
-import { historyViewLeaves, type HistoryMessageSource, type HistoryWorkSummary, type DeferredHistoryWork } from './historyView.js';
+import { historyViewLeaves, historyWorkSummaries, type HistoryFileArtifact, type HistoryMessageSource, type HistoryWorkSummary, type DeferredHistoryWork } from './historyView.js';
import type { HistoryViewController, HistoryViewSnapshot } from './historyViewController.js';
import { liveContentWithHistoryOrder } from './historyViewHandoff.js';
@@ -7,7 +7,7 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
view: HistoryViewController<T>;
snapshot: HistoryViewSnapshot<T>;
liveMessages: readonly T[];
- build(messages: readonly T[], streaming: boolean): TItem[];
+ build(messages: readonly T[], streaming: boolean, artifacts?: readonly HistoryFileArtifact[]): TItem[];
streaming: boolean;
isLive?(message: T): boolean;
/** Already displayed assistant identities in observation order, awaiting history. */
@@ -39,6 +39,21 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
seen.add(row.clientId);
endMs = Math.max(endMs, Date.parse(row.createdAt));
}
+ if (item.deferred) {
+ references.set(item.deferred.anchorClientId ?? item.key, item.deferred);
+ const summary = item.deferred;
+ const cached = snapshot.details.get(summary.key)?.messages ?? [];
+ const matches = (row: T, id: string) => row.id === id
+ || (id.startsWith('history-live:') && row.clientId === id.slice('history-live:'.length));
+ const first = cached.findIndex((row) => matches(row, summary.firstMessageId));
+ const last = cached.findIndex((row) => matches(row, summary.lastMessageId));
+ const body = first < 0 ? [] : cached.slice(first, last < first ? undefined : last + 1);
+ for (const row of body) {
+ if (!sourceIds.has(row.clientId) && !seen.has(row.clientId)) {
+ rows.push(row); seen.add(row.clientId);
+ }
+ }
+ }
continue;
}
const summary = item.summary;
@@ -81,7 +96,7 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
isPendingHandoff(source) && !seen.has(source.clientId)
? pendingTail[pendingIndex++] : source);
for (const row of orderedLiveMessages) {
- if (isLive(row) && !seen.has(row.clientId) && (row.role === 'assistant' || row.role === 'user')
+ if (isLive(row) && !seen.has(row.clientId)
&& (Date.parse(row.createdAt) >= endMs
|| isPendingHandoff(row))) rows.push(row);
}
@@ -105,13 +120,19 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
const children = structure.children(item);
if (!children) return item;
const refs = new Map<string, HistoryWorkSummary>();
+ for (const id of structure.sourceIds(item)) {
+ const summary = references.get(id);
+ if (summary) refs.set(summary.key, summary);
+ }
const next: TItem[] = [];
for (const child of children) {
if (structure.children(child)) { next.push(bind(child)); continue; }
const ids = structure.sourceIds(child);
for (const id of ids) {
const summary = references.get(id);
- if (summary) refs.set(summary.key, summary);
+ // A platform that only shows a subagent summary has no child-detail
+ // surface. Its enclosing work group must not fetch those hidden bodies.
+ if (summary && !summary.parentToolUseId) refs.set(summary.key, summary);
}
if (!ids.some((id) => placeholders.has(id))) next.push(child);
}
@@ -128,6 +149,7 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
};
return structure.rebuild(item, next, {
owner: view, key: summaries.map((summary) => summary.key).join('|'), expanded,
+ revision: summaries.map((summary) => summary.revision).join('|'),
previewComplete: summaries.every((summary) => summary.preview?.firstMessageId === summary.firstMessageId),
loading: states.some((state) => state?.loading), failed: states.some((state) => !!state?.error),
setVisible,
@@ -136,5 +158,5 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
summary.preview && view.getSnapshot().expanded.has(summary.preview.key) ? summary.preview : summary); },
});
};
- return options.build(rows, options.streaming).map(bind);
+ return options.build(rows, options.streaming, historyWorkSummaries(snapshot.items).flatMap((summary) => summary.artifacts ?? [])).map(bind);
}
diff --git a/packages/maker-shared/src/messageWindow.ts b/packages/maker-shared/src/messageWindow.ts
index b8a0483652..f5906ea06e 100644
--- a/packages/maker-shared/src/messageWindow.ts
+++ b/packages/maker-shared/src/messageWindow.ts
@@ -1,6 +1,6 @@
export { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from './remoteTextStream.js';
export * from './historyView.js';
-export { projectHistoryView, isHistoryDetailTool, hasVisibleHistoryResult } from './historyViewProjection.js';
+export { projectHistoryView, historySubagentScopes, isHistoryDetailTool, hasVisibleHistoryResult } from './historyViewProjection.js';
export * from './historyViewController.js';
export { renderHistoryView } from './historyViewRender.js';
export { HistoryViewHandoff } from './historyViewHandoff.js';