Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(history): 避免折叠子任务跨页触发历史降级
Dash562805d0ac2d
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.tsindex 5bbec0edfa..27a6bf25b6 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from 'vitest';import { throwIpcError } from '../../../utils/ipcValidate';import { createHistoryViewReader } from '../historyViewReader';-import { projectHistoryView, type HistoryMessageSource, type HistoryViewItem } from '@cindy/maker-shared/message-window';+import { historyViewLeaves, projectHistoryView, type HistoryMessageSource, type HistoryViewItem } from '@cindy/maker-shared/message-window';function row(n: number, role = 'thinking'): HistoryMessageSource {return { id: String(n), clientId: `c${n}`, rowid: n, role, content: 'body '.repeat(200), createdAt: new Date(1700000000000 + n).toISOString() };}@@ -349,17 +349,21 @@ describe('outline history reads', () => {expect(card?.type === 'messages' && card.deferred?.messageCount).toBe(1201);});+ // Phone regression (2026-10-22): the 20-item cut separated an Agent header from+ // its children and disabled folded history. Unit coverage now requires paging+ // every source row exactly once, including deferred results and live children.it.each([{ lazy: false, outlined: false, large: false },{ lazy: true, outlined: false, large: false },{ lazy: true, outlined: true, large: false },{ lazy: true, outlined: true, large: true },+ { lazy: true, outlined: true, large: true, newerTail: true },{ lazy: true, outlined: true, large: false, resultOnly: true },{ lazy: true, outlined: true, large: false, liveTail: true },- ])('falls back instead of cutting an Agent with the returned cursor ($lazy/$outlined/$large/$resultOnly/$liveTail)', async ({ lazy, outlined, large, resultOnly = false, liveTail = false }) => {+ ])('pages an intact Agent across the item target, retaining the byte limit ($lazy/$outlined/$large/$resultOnly/$liveTail/$newerTail)', async ({ lazy, outlined, large, resultOnly = false, liveTail = false, newerTail = false }) => {let n = 0;const source = [row(n++, 'user'),- { ...row(n++, 'tool_use'), toolUseId: 'a', content: { toolName: 'Agent', input: {} } }];+ { ...row(n++, 'tool_use'), toolUseId: 'a', content: { toolName: 'Agent', input: { description: 'Full agent description' } } }];if (resultOnly) source.push({ ...row(n++, 'tool_use'), toolUseId: 'child-call', content: { toolName: 'Bash', input: {} }, agentMeta: { parentUuid: 'a' } });for (let i = 0; i < (large ? 6 : 30); i++) {source.push(resultOnly || liveTail ? row(n++) : { ...row(n++), agentMeta: { parentUuid: 'a' } });@@ -369,11 +373,53 @@ describe('outline history reads', () => {: { ...row(n++), agentMeta: { parentUuid: 'a' } };const live = liveTail ? [{ ...tail, id: `history-live:${tail.clientId}` }] : [];if (!liveTail) source.push(tail);+ if (newerTail) source.push(row(n++, 'user'));const base = reader(source);const api = createHistoryViewReader({ list: base.list,- ...(outlined ? { outline: base.list, hydrate: async (_sid: string, ids: string[]) => source.filter((r) => ids.includes(r.id)) } : {}),+ ...(outlined ? {+ outline: async (sid: string, opts: { before?: string; after?: string; limit: number }) =>+ (await base.list(sid, opts)).map((message) => message.role === 'tool_use'+ ? { ...message, content: { ...message.content as object, input: {} } }+ : message.role === 'assistant' ? { ...message, content: '# Result\nOutline' } : message),+ hydrate: async (_sid: string, ids: string[]) => source.filter((r) => ids.includes(r.id)),+ } : {}),anchor: async (_sid, id) => [...source, ...live].find((r) => r.id === id)!, running: () => liveTail, live: () => live });- await expect(api.page('s', undefined, lazy)).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });+ if (large) {+ let before: string | undefined;+ if (newerTail) {+ const page = await api.page('s', undefined, lazy);+ expect(page.items).toHaveLength(1);+ expect(page.items[0]).toMatchObject({ type: 'messages', messages: [source.at(-1)] });+ expect(page.hasMore).toBe(true);+ before = page.nextCursor!;+ }+ await expect(api.page('s', before, lazy)).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });+ return;+ }+ const seen: string[] = [];+ let before: string | undefined;+ do {+ const page = await api.page('s', before, lazy);+ for (const item of historyViewLeaves(page.items)) {+ if (item.type === 'messages') {+ seen.push(...item.messages.map((message) => message.id));+ // The extra header outside the usual 20 items must also be hydrated.+ for (const message of item.messages) expect(message.content).toEqual(source.find((r) => r.id === message.id)?.content);+ }+ const ref = item.type === 'work' ? item.summary : item.deferred;+ if (ref) {+ let after: string | undefined;+ do {+ const detail = await api.details('s', ref, after);+ seen.push(...detail.messages.map((message) => message.id));+ after = detail.nextCursor ?? undefined;+ } while (after);+ }+ }+ expect(page.nextCursor).not.toBe(before);+ before = page.nextCursor ?? undefined;+ } while (before);+ expect(seen.sort()).toEqual([...source, ...live].map((message) => message.id).sort());});it('reads visible bodies first across thousands of interleaved subagent rows, then pages only the expanded agent', async () => {diff --git a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts b/apps/desktop/src/main/localDb/ipc/historyViewReader.tsindex 3e5ff3df53..9e4fc15971 100644--- a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts+++ b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts@@ -92,6 +92,49 @@ function cutsHistoryToolContext(rows: readonly HistoryMessageSource[], start: nureturn false;}+/** Legal source cursors keep every deferred child with its owning Agent header. */+function historyPageSafeStarts(rows: readonly HistoryMessageSource[]): Set<string> {+ const scopes = historySubagentScopes(rows);+ const headers = new Map<string, number>();+ rows.forEach((row, index) => {+ if (row.role === 'tool_use') {+ const id = parseMessageToolUse(row).toolUseId;+ if (id) headers.set(id, index);+ }+ });+ const safe = new Set<string>();+ let requiredStart = rows.length;+ for (let index = rows.length - 1; index >= 0; index--) {+ const parent = scopes.get(rows[index].id);+ if (parent) requiredStart = Math.min(requiredStart, headers.get(parent) ?? index);+ if (requiredStart >= index) safe.add(rows[index].id);+ }+ return safe;+}++/** Twenty items is a target; the byte limit still bounds an intact tool span. */+function historyPageStart<T extends HistoryMessageSource>(+ items: readonly HistoryViewItem<T>[], safeStarts: ReadonlySet<string>, measureBytes: boolean,+): number {+ let start = items.length;+ let bytes = 1024;+ for (let index = items.length - 1; index >= 0; index--) {+ if (measureBytes) {+ bytes += Buffer.byteLength(JSON.stringify(items[index]), 'utf8');+ // Preserve the existing single-item delivery exception. A multi-item+ // Agent span may not bypass the page byte budget.+ if (index < items.length - 1 && bytes > HISTORY_VIEW_PAGE_BYTES) break;+ }+ if (!safeStarts.has(firstId(items[index]))) continue;+ start = index;+ if (items.length - index >= HISTORY_VIEW_PAGE_ITEMS) break;+ }+ if (items.length && start === items.length) {+ throwIpcError('UNSUPPORTED_CAPABILITY', 'History page would split tool context');+ }+ return start;+}+export function createHistoryViewReader<T extends HistoryMessageSource>(deps: HistoryViewReaderDependencies<T>) {let readRevision = 0;const readerEpoch = randomUUID();@@ -178,10 +221,11 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hiraw = chunks.slice().reverse().flat();const live = liveRows(raw);items = project(live);+ const safeStarts = historyPageSafeStarts([...raw, ...live]);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 candidate = items.slice(historyPageStart(items, safeStarts, false));const ids: string[] = [];mapHistoryViewMessages(candidate, (rows) => {ids.push(...rows.filter((row) => !row.id.startsWith('history-live:')).map((row) => row.id));@@ -226,24 +270,8 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi// 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--) {- const size = Buffer.byteLength(JSON.stringify(items[index]), 'utf8');- if (selected.length > 0 && (selected.length >= HISTORY_VIEW_PAGE_ITEMS || bytes + size > HISTORY_VIEW_PAGE_BYTES)) break;- selected.unshift(items[index]);- bytes += size;- }+ const selected = items.slice(historyPageStart(items, safeStarts, true));const hasMore = !exhausted || selected.length < items.length;- if (hasMore && selected.length) {- const rows = [...raw, ...live];- const start = rows.findIndex((row) => row.id === firstId(selected[0]));- // A deferred card can own rows newer than its own header. A cursor inside- // that span would lose them on the older page; use the existing raw path.- if (start >= 0 && cutsHistoryToolContext(rows, start, historySubagentScopes(rows))) {- throwIpcError('UNSUPPORTED_CAPABILITY', 'History page would split tool context');- }- }// A clear/rewind during the scan invalidates the whole snapshot, including// already-read rows. Never publish a prefix from the previous history epoch.// The cursor can also supply grouping context without appearing in raw.@@ -270,15 +298,17 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hielse 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 (ref.parentToolUseId) {+ const outlined = !!deps.outline && !!deps.hydrate;+ const read = outlined ? deps.outline! : deps.list;+ const first = await deps.anchor(sessionId, ref.firstMessageId, outlined);+ const last = await deps.anchor(sessionId, ref.lastMessageId, outlined);if (compareRows(first, last) > 0) throwIpcError('INVALID_PARAMS', 'Invalid history range');- const cursorAnchor = after ? await deps.anchor(sessionId, after, true) : undefined;+ const cursorAnchor = after ? await deps.anchor(sessionId, after, outlined) : 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;+ const revision = outlined && !ref.liveMessageIds?.length && deps.revision ? await deps.revision() : undefined;if (revision !== detailRevision) {detailRanges.clear(); detailCacheBytes = 0; detailRevision = revision;}@@ -290,15 +320,21 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi}if (!scoped) {const headers: T[] = [];+ let fullBytes = 0;+ const append = (rows: T[]) => {+ if (!outlined) fullBytes += Buffer.byteLength(JSON.stringify(rows), 'utf8');+ if (headers.length + rows.length > (outlined ? 100000 : MAX_HISTORY_SCAN_ROWS)+ || fullBytes > MAX_HISTORY_SCAN_BYTES) throwIpcError('INVALID_PARAMS', 'History detail range is too large');+ headers.push(...rows);+ };if (!first.id.startsWith('history-live:')) {- headers.push(first);+ append([first]);let cursor = first.id;while (cursor !== (ref.lastStoredMessageId ?? last.id)) {- const batch = (await deps.outline(sessionId, { limit: 1000, after: cursor }, true)).slice().reverse();+ const batch = (await read(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');+ append(bounded);const next = batch.at(-1)!.id;if (next === cursor) throwIpcError('INTERNAL', 'History detail cursor did not advance');cursor = next;@@ -307,7 +343,7 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi}for (const id of ref.liveMessageIds ?? []) {const row = await deps.anchor(sessionId, id);- if (!headers.some((stored) => stored.clientId === row.clientId)) headers.push(row);+ if (!headers.some((stored) => stored.clientId === row.clientId)) append([row]);}const scopes = historySubagentScopes(headers, ref.parentToolUseId);scoped = headers.filter((row) => scopes.get(row.id) === ref.parentToolUseId);@@ -332,7 +368,7 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hifor (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]));+ const full = new Map((outlined ? await deps.hydrate!(sessionId, stored.map((row) => row.id)) : stored).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');diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 43bb327b6d..d781332c6c 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -337,6 +337,12 @@ stale 时不能再用消息时间戳复活已被接收顺序判定为旧的正重置来源及行数;手机滚动采样携带相同短引用和可见列表项数,区分数据替换与布局重测,不记录正文、不扩展遥测上传。+历史页以 20 个可见项为目标;边界跨过子任务时,主机将起点前移到完整子任务入口,+并恢复额外可见项的正文,折叠详情仍按需读取。实际正文恢复后继续执行原有 1 MiB 页预算;+可先返回的完整较短后缀照常返回,只有不可分割范围本身超限时沿用旧的降级行为。+分页游标仍是原始消息 ID,返回结构、权限、缓存与 Mobile 原生配置不变;现有手机和+远程桌面均可读取超过 20 项的完整页,修复只需更新提供历史的主机。+`messages:list` / `messages:view` 的 options 可选携带 `messageBodies: { version: 1, known }`,known 是消息 ID 与主机提供的 SHA-256 正文指纹对。支持的主机在授权、净化之后返回`message-bodies-v1` 包装,只省略指纹吻合的正文,顺序、分页与消息元数据始终重新读取。