Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 补全运行中活动行的失效、字节上限、补读与思考通知门限
Dashc33b0130cc0e
diff --git a/apps/desktop/src/main/device-link/__tests__/historyWorkPatch.test.ts b/apps/desktop/src/main/device-link/__tests__/historyWorkPatch.test.tsindex 56fb5b9f43..719df50bf6 100644--- a/apps/desktop/src/main/device-link/__tests__/historyWorkPatch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/historyWorkPatch.test.ts@@ -40,16 +40,19 @@ function host(source: HistoryMessageSource[]) {};const reader = createHistoryViewReader({list,- // Mirrors historyOutlineContent: bodies stay on disk, only grouping facts are read.+ // Mirrors historyOutlineContent + historyOutlineContentStamp: bodies stay on disk,+ // only grouping facts and a body stamp are read.outline: async (sid, opts) => (await list(sid, opts)).map((row) => {+ const body = typeof row.content === 'string' ? row.content : JSON.stringify(row.content);+ const stamped = { ...row, historyContentStamp: `${body.length}:${body.slice(-24)}` };const content = row.content as { toolName?: string; toolUseId?: string; input?: Record<string, unknown> };- if (row.role === 'thinking') return { ...row, content: { isRedacted: true } };- if (row.role === 'tool_result') return { ...row, content: '' };+ if (row.role === 'thinking') return { ...stamped, content: { isRedacted: true } };+ if (row.role === 'tool_result') return { ...stamped, content: '' };if (row.role === 'tool_use') {- return { ...row, content: { toolName: content.toolName, toolUseId: content.toolUseId,+ return { ...stamped, content: { toolName: content.toolName, toolUseId: content.toolUseId,input: { file_path: content.input?.file_path, path: content.input?.path, command: content.input?.command } } };}- return row;+ return stamped;}),hydrate: async (_sid, ids) => source.filter((row) => ids.includes(row.id)),revision: async () => `db:${writes}`,@@ -65,6 +68,12 @@ function host(source: HistoryMessageSource[]) {source.push(...rows);writes += 1;},+ /** In-place body rewrite, like a later full tool result or a background completion. */+ rewrite(id: string, content: unknown) {+ const row = source.find((value) => value.id === id)!;+ row.content = content;+ writes += 1;+ },async page(): Promise<{ page: HistoryViewPage<HistoryMessageSource>; shape: HistoryPageShape }> {let shape: HistoryPageShape | undefined;const page = await reader.page('s', undefined, true, { workLines: true, onShape: (value) => { shape = value; } });@@ -205,4 +214,47 @@ describe('running work lines', () => {expect(thinkingDeltaUpdatesWorkLine('s', delta('d', 'b2'))).toBe(true);expect(thinkingDeltaUpdatesWorkLine('s', { sessionId: 's', event: { type: 'tool_use', data: {} } })).toBe(false);});++ it('measures the thinking line after the projection collapses whitespace, across chunks', () => {+ const delta = (text: string) => ({ sessionId: 'w', event: { type: 'thinking', data: { stage: 'delta', blockId: 'b', text } } });+ // Leading whitespace is invisible: nothing to send yet, and it does not use up the line.+ expect(thinkingDeltaUpdatesWorkLine('w', delta(' '.repeat(160)))).toBe(false);+ expect(thinkingDeltaUpdatesWorkLine('w', delta('Now a useful thought'))).toBe(true);+ // A run split across chunks still collapses to one space; slow output keeps updating.+ for (let n = 0; n < 20; n += 1) {+ expect(thinkingDeltaUpdatesWorkLine('w', delta('\n\n '))).toBe(false);+ expect(thinkingDeltaUpdatesWorkLine('w', delta('word'))).toBe(true);+ }+ // Once more than a line is known, further text cannot change what is shown.+ for (let n = 0; n < 20; n += 1) thinkingDeltaUpdatesWorkLine('w', delta(' more'));+ expect(thinkingDeltaUpdatesWorkLine('w', delta(' and more'))).toBe(false);+ });++ it('refreshes when a completed group hidden body is rewritten while another group runs', async () => {+ const source = [user(0), toolUse(1, 'Bash', { command: 'pnpm build' }), toolResult(2, 1, 'summary'),+ assistant(3, 'Build started, checking tests.'), toolUse(4, 'Read', { file_path: '/repo/a.ts' })];+ const h = host(source);+ setHistoryWorkPageReader((sid, onShape) => h.reader.page(sid, undefined, true, { workLines: true, onShape }));+ const delivered = await h.page();+ expect(delivered.page.items.filter((item) => item.type === 'work')).toHaveLength(2);+ // Only the completed group's tool result changes: its outline body is still empty.+ h.rewrite('m2', `summary\n${'full build log '.repeat(200)}`);+ expect((await buildHistoryWorkPatch('s', delivered.shape)).kind).toBe('refresh');+ });++ it('widens past repeated reads so five display lines survive de-duplication', async () => {+ const source = [user(0)];+ let n = 1;+ for (const file of ['/a', '/b', '/c', '/d', '/e', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z',+ '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z', '/z']) {+ source.push(toolUse(n, 'Read', { file_path: file }), toolResult(n + 1, n, `contents of ${file}`));+ n += 2;+ }+ source.push(thinking(n, ' '));+ const { page } = await host(source).page();+ const running = page.items.at(-1);+ if (running?.type !== 'work') throw new Error('missing running item');+ expect(running.summary.lines!.map((line) => line.kind === 'tool' && line.descriptor.kind === 'file' ? line.descriptor.filePath : line.kind))+ .toEqual(['/b', '/c', '/d', '/e', '/z']);+ });});diff --git a/apps/desktop/src/main/device-link/historyViewPush.ts b/apps/desktop/src/main/device-link/historyViewPush.tsindex 2e55929fbb..71be26ab84 100644--- a/apps/desktop/src/main/device-link/historyViewPush.ts+++ b/apps/desktop/src/main/device-link/historyViewPush.ts@@ -94,17 +94,33 @@ export async function buildHistoryWorkPatch(sessionId: string, delivered: Histor/*** Folded thinking deltas normally produce no notice. A work-line controller still needs- * the opening of the thought, so deltas notify until that single line can no longer change.+ * the opening of the thought, so deltas notify while its visible line can still change.+ * The visible prefix follows the line projection: leading and trailing whitespace is+ * dropped and every whitespace run becomes one space, including runs split across chunks.*/-const thinkingLineChars = new Map<string, { blockId: unknown; chars: number }>();+const thinkingLinePrefixes = new Map<string, { blockId: unknown; visible: string; pendingSpace: boolean }>();export function thinkingDeltaUpdatesWorkLine(sessionId: string, payload: unknown): boolean {const event = record(record(payload)?.event);const data = record(event?.data);if (event?.type !== 'thinking' || data?.stage !== 'delta') return false;- const current = thinkingLineChars.get(sessionId);- const before = current && current.blockId === data.blockId ? current.chars : 0;- thinkingLineChars.delete(sessionId);- thinkingLineChars.set(sessionId, { blockId: data.blockId, chars: before + (typeof data.text === 'string' ? data.text.length : 0) });- if (thinkingLineChars.size > 256) thinkingLineChars.delete(thinkingLineChars.keys().next().value!);- return before < HISTORY_WORK_LINE_TEXT_CHARS;+ const current = thinkingLinePrefixes.get(sessionId);+ const state = current && current.blockId === data.blockId+ ? current : { blockId: data.blockId, visible: '', pendingSpace: false };+ const before = state.visible;+ // One character past the line length decides whether the line shows an ellipsis.+ const text = typeof data.text === 'string' ? data.text : '';+ for (let index = 0; index < text.length && state.visible.length <= HISTORY_WORK_LINE_TEXT_CHARS; index += 1) {+ const char = text[index];+ if (/\s/.test(char)) {+ state.pendingSpace = state.visible.length > 0;+ continue;+ }+ if (state.pendingSpace) state.visible += ' ';+ state.pendingSpace = false;+ state.visible += char;+ }+ thinkingLinePrefixes.delete(sessionId);+ thinkingLinePrefixes.set(sessionId, state);+ if (thinkingLinePrefixes.size > 256) thinkingLinePrefixes.delete(thinkingLinePrefixes.keys().next().value!);+ return state.visible !== before;}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.tsindex 3e052426e4..69f40b9c63 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts@@ -1,7 +1,7 @@import { DatabaseSync } from 'node:sqlite';import { SQLiteSyncDialect } from 'drizzle-orm/sqlite-core';import { describe, expect, it } from 'vitest';-import { historyOutlineContent, withHistoryArtifacts } from '../historyViewOutline';+import { historyOutlineContent, historyOutlineContentStamp, withHistoryArtifacts } from '../historyViewOutline';function outline(role: string, content: unknown, agentMeta: unknown = null, raw = false) {const db = new DatabaseSync(':memory:');@@ -14,7 +14,24 @@ function outline(role: string, content: unknown, agentMeta: unknown = null, raw} finally { db.close(); }}+function stamp(content: string) {+ const db = new DatabaseSync(':memory:');+ try {+ db.exec('CREATE TABLE messages (content TEXT)');+ db.prepare('INSERT INTO messages VALUES (?)').run(content);+ const query = new SQLiteSyncDialect().sqlToQuery(historyOutlineContentStamp());+ return db.prepare(`SELECT ${query.sql} AS stamp FROM messages`).get(...query.params as string[])!.stamp as string;+ } finally { db.close(); }+}+describe('SQLite history outline', () => {+ it('stamps a body with a short fact that changes when it is rewritten in place', () => {+ const summary = JSON.stringify('build summary');+ const full = JSON.stringify(`build summary\n${'full log line\n'.repeat(50000)}`);+ expect(stamp(summary)).not.toBe(stamp(full));+ expect(stamp(full).length).toBeLessThan(64);+ expect(stamp(JSON.stringify('结果:完成'))).toBe(stamp(JSON.stringify('结果:完成')));+ });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);diff --git a/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts b/apps/desktop/src/main/localDb/ipc/historyViewOutline.tsindex 77721bde39..6fe4a0da78 100644--- a/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts+++ b/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts@@ -63,6 +63,15 @@ export function historyOutlineContent(): SQL<string> {}+/**+ * A cheap fact that changes when a hidden body is rewritten in place (a later full tool+ * result, a background completion). The outline already reads every body, so length and+ * tail cost nothing extra; grouping revisions hash it, and it never reaches the wire.+ */+export function historyOutlineContentStamp(): SQL<string> {+ return sql<string>`length(${messages.content}) || ':' || substr(${messages.content}, -24)`;+}+/** 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;diff --git a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts b/apps/desktop/src/main/localDb/ipc/historyViewReader.tsindex 84586555ad..cdb30bdf6f 100644--- a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts+++ b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts@@ -4,12 +4,15 @@ import { isDeliveryProseText } from '@cindy/maker-shared/message-render';import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';import {HISTORY_VIEW_PAGE_BYTES, HISTORY_VIEW_PAGE_ITEMS, HISTORY_DETAIL_PAGE_BYTES,- projectHistoryView, projectHistoryWorkLines, historySubagentScopes, mapHistoryViewMessages, historyWorkSummaries,- type HistoryMessageSource, type HistoryViewItem, type HistoryViewPage, type HistoryDetailPage, type HistoryWorkReference,+ HISTORY_WORK_LINE_LIMIT, projectHistoryView, projectHistoryWorkLines, historySubagentScopes, mapHistoryViewMessages, historyWorkSummaries,+ type HistoryMessageSource, type HistoryWorkLine, type HistoryViewItem, type HistoryViewPage, type HistoryDetailPage, type HistoryWorkReference,} from '@cindy/maker-shared/message-window';export const MAX_HISTORY_SCAN_ROWS = 2000;const MAX_HISTORY_SCAN_BYTES = 8 * 1024 * 1024;+const WORK_LINE_SOURCE_BATCH = 24;+/** Bounds the bodies read for one running preview; a longer duplicate run shows fewer lines. */+const MAX_WORK_LINE_SOURCE_ROWS = 384;interface ReadOptions { limit: number; before?: string; after?: string }@@ -190,17 +193,23 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hiif (options.workLines && !before) {const rows = [...raw, ...live];for (const item of items.filter(isRunningLeafWork)) {- const range = item.summary.preview ?? item.summary;- const start = rows.findIndex((row) => row.id === range.firstMessageId);- const end = rows.findIndex((row) => row.id === range.lastMessageId);- let tail = start < 0 || end < start ? [] : rows.slice(start, end + 1);+ const start = rows.findIndex((row) => row.id === item.summary.firstMessageId);+ const end = rows.findIndex((row) => row.id === item.summary.lastMessageId);try {- if (outlined) {- const full = new Map((await deps.hydrate!(sessionId, tail.filter((row) => !row.id.startsWith('history-live:'))- .map((row) => row.id))).map((row) => [row.id, row]));- tail = tail.map((row) => full.get(row.id) ?? row);+ // Repeated reads and empty thoughts are dropped by the projection, so a fixed+ // source tail can yield fewer lines than are visible. Widen from the end until+ // five display lines exist or the group starts, hydrating each row only once.+ const full = new Map<string, T>();+ let lines: HistoryWorkLine[] = [];+ for (let take = WORK_LINE_SOURCE_BATCH; start >= 0 && end >= start; take *= 2) {+ const from = Math.max(start, end + 1 - Math.min(take, MAX_WORK_LINE_SOURCE_ROWS));+ const tail = rows.slice(from, end + 1);+ const missing = outlined ? tail.filter((row) => !row.id.startsWith('history-live:') && !full.has(row.id)) : [];+ if (missing.length) for (const row of await deps.hydrate!(sessionId, missing.map((row) => row.id))) full.set(row.id, row);+ lines = projectHistoryWorkLines(tail.map((row) => full.get(row.id) ?? row), true);+ if (lines.length >= HISTORY_WORK_LINE_LIMIT || from === start || take >= MAX_WORK_LINE_SOURCE_ROWS) break;}- item.summary.lines = projectHistoryWorkLines(tail, true);+ item.summary.lines = lines;} catch {// Lines are a display hint. A range changing mid-read keeps the page usable;// the next activity notice recomputes them.diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex 3b0285dc2b..8e29fa4159 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -23,7 +23,7 @@ import {type SQL,} from 'drizzle-orm';import { createId } from '@paralleldrive/cuid2';-import { historyOutlineContent, withHistoryArtifacts } from './historyViewOutline';+import { historyOutlineContent, historyOutlineContentStamp, withHistoryArtifacts } from './historyViewOutline';import { historyViewLeaves, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';import { getDbClient, getCurrentDbClientSnapshot } from '../client/current';@@ -320,7 +320,7 @@ export async function readMessagesList(sessionId: unknown, opts: unknown, skipImconst rows = await db.select({...getMessageSelectFields(),- ...(outline ? { content: historyOutlineContent() } : {}),+ ...(outline ? { content: historyOutlineContent(), historyContentStamp: historyOutlineContentStamp() } : {}),rowid: messageRowid,}).from(messages)@@ -333,7 +333,9 @@ export async function readMessagesList(sessionId: unknown, opts: unknown, skipImconst orderedRows = afterCursor ? rows.slice().reverse() : rows;const restored = await restoreTaskImageRows(imageDbClient, orderedRows);const listed = await hydrateLegacyUserTurnCosts(restored.map(messageToCamelWithRowid));- return outline ? listed.map(withHistoryArtifacts) : listed;+ if (!outline) return listed;+ const stamps = new Map(orderedRows.map((row) => [row.id, (row as { historyContentStamp?: string }).historyContentStamp]));+ return listed.map((row) => withHistoryArtifacts({ ...row, historyContentStamp: stamps.get(row.id) ?? undefined }));}export function registerMessageIpc(diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex ee9b4852bc..2872028101 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -409,16 +409,22 @@ raw history 降级。任务列表活动推送不变,当前轮的正文、工同账号控制端读取最新一页时可再带 `{ workLines: true }`。被控 Desktop 只为顶层、无嵌套、运行中的工作组摘要附加可选 `lines`:最多 5 行,用与两端相同的共享投影(Codex 拆行、-重复读取去重)从完整记录算出,每行只含工具名、按完整输入解析后再截短的展示描述、状态、-是否失败,或思考开头的单行文字;不含工具结果、diff 与完整输入,整窗有 UTF-8 字节上限。-控制端据此显示运行中的最近 5 行,不再为预览读取 `work-details`。+重复读取去重)从完整记录算出,并从组尾向前有界地补读,直到凑足 5 个展示活动。每行只含+工具名、按完整输入解析后再截短的展示描述、状态、是否失败,或思考开头的单行文字;不含+工具结果、diff 与完整输入。每行和整窗都有严格的 UTF-8 字节上限,超出时逐级缩短文字与+列表(列表保留条目数),最后只保留工具名。控制端据此显示运行中的最近 5 行,不再为预览+读取 `work-details`。++轻量读取为每行附带仅在主机内使用的正文戳(长度与末尾片段),参与工作组修订号,使后续+全文覆盖、后台完成等原地改写也会改变修订号;该字段不进入线上内容。声明过 `workLines` 的控制端,折叠工作组的活动通知改为新推送 `maker:history-work-patch``{ version: 1, sessionId, baseRevision, item }`:仅当它上次收到的最新一页里,除这一个运行中条目外的所有条目指纹都未变(指纹在库级写入计数后缀之前计算)时才发送,`baseRevision`是该条目上次送达的修订号。控制端只在条目存在、修订号与范围起点一致、且没有读取进行中时原地替换,其余情况退回原有的页面刷新;新分组、正文、卡片、清空或回退都继续走-`maker:history-view-changed`。思考增量只在单行文字还会变化时触发通知。+`maker:history-view-changed`。思考增量按与投影相同的空白归一化计算可见前缀,只在这一行+还会变化时触发通知。旧控制端不带参数,收不到 `lines` 与新推送;旧主机忽略参数:新 Mobile 只显示卡头(与此前相同),新 Desktop 继续用原有 5 条明细预览。共享任务访客与供应商分享不启用这两项,读取与授权路径不变。diff --git a/packages/maker-shared/src/__tests__/historyWorkLines.test.ts b/packages/maker-shared/src/__tests__/historyWorkLines.test.tsindex f2c2c5f6e3..51e481b586 100644--- a/packages/maker-shared/src/__tests__/historyWorkLines.test.ts+++ b/packages/maker-shared/src/__tests__/historyWorkLines.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { HistoryViewController } from '../historyViewController.js';import type { HistoryMessageSource, HistoryViewPage, HistoryWorkPatch, HistoryWorkSummary } from '../historyView.js';import { renderHistoryView } from '../historyViewRender.js';-import { HISTORY_WORK_LINES_MAX_BYTES, projectHistoryWorkLines } from '../historyWorkLines.js';+import { HISTORY_WORK_LINE_MAX_BYTES, HISTORY_WORK_LINES_MAX_BYTES, projectHistoryWorkLines } from '../historyWorkLines.js';let n = 0;function row(role: string, content: unknown, extra: Partial<HistoryMessageSource> = {}): HistoryMessageSource {@@ -62,9 +62,26 @@ describe('projectHistoryWorkLines', () => {expect(line.kind === 'thinking' && line.text.startsWith('first second')).toBe(true);const wide = Array.from({ length: 5 }, (_, index) => tool('mcp__srv__do_it', { query: `${index}${'界'.repeat(2000)}` }));const lines = projectHistoryWorkLines(wide, true);- expect(lines.length).toBeGreaterThan(0);+ expect(lines).toHaveLength(5);expect(Buffer.byteLength(JSON.stringify(lines), 'utf8')).toBeLessThanOrEqual(HISTORY_WORK_LINES_MAX_BYTES);});++ it.each([+ ['ASCII', (index: number) => `/repo/${'nested/'.repeat(40)}file${index}.ts`],+ ['CJK', (index: number) => `/仓库/${'深层目录/'.repeat(60)}文件${index}.ts`],+ ])('keeps every real file_change line, including the newest, inside the byte budget (%s paths)', (_label, path) => {+ const change = (count: number) => tool('file_change', { changes: Array.from({ length: count }, (_, index) => ({+ path: path(index), kind: { type: 'update', move_path: path(index + 100) }, diff: '+x\n'.repeat(500),+ })) });+ const lines = projectHistoryWorkLines([change(20), change(20), change(3), change(20), change(15)], true);+ expect(lines).toHaveLength(5);+ expect(Buffer.byteLength(JSON.stringify(lines), 'utf8')).toBeLessThanOrEqual(HISTORY_WORK_LINES_MAX_BYTES);+ for (const line of lines) expect(Buffer.byteLength(JSON.stringify(line), 'utf8')).toBeLessThanOrEqual(HISTORY_WORK_LINE_MAX_BYTES);+ const newest = lines.at(-1)!;+ if (newest.kind !== 'tool') throw new Error('expected a tool line');+ // The count a multi-file row shows survives the reduction.+ expect(newest.descriptor.kind === 'fileChange' ? newest.descriptor.changes.length : newest.descriptor.kind).toBe(15);+ });});function summary(key: string, revision: string, lines?: HistoryWorkSummary['lines']): HistoryWorkSummary {diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.tsindex b7e485a0f7..a72cb3d7f4 100644--- a/packages/maker-shared/src/historyView.ts+++ b/packages/maker-shared/src/historyView.ts@@ -32,6 +32,8 @@ export interface HistoryMessageSource {agentMeta?: object | null;/** Host outline only; transferred in work summaries, never as a replacement body. */historyArtifacts?: HistoryFileArtifact[];+ /** Host outline only: changes when the hidden body is rewritten; hashed into revisions. */+ historyContentStamp?: string;}/** Both endpoints are real host message IDs, inclusive, in host database order. */diff --git a/packages/maker-shared/src/historyViewProjection.ts b/packages/maker-shared/src/historyViewProjection.tsindex 546e2690d6..f9076db87d 100644--- a/packages/maker-shared/src/historyViewProjection.ts+++ b/packages/maker-shared/src/historyViewProjection.ts@@ -15,6 +15,16 @@ type SourceItem<T extends HistoryMessageSource> = {};type GroupItem<T extends HistoryMessageSource> = { type: 'group'; summary: HistoryWorkSummary; children?: HistoryViewItem<T>[] };+/** Content-sensitive range revision: outline rows carry a body stamp instead of the body. */+function historyRowsHash(rows: readonly HistoryMessageSource[]): number {+ let hash = 2166136261;+ for (const row of rows) {+ const text = JSON.stringify(row);+ for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 16777619);+ }+ return hash >>> 0;+}+/** A tool can carry a durable card/interaction even before its result exists. */export function isHistoryDetailTool(name: string): boolean {return !!name && !isAgentTaskToolName(name) && !isAgentPlanToolName(name)@@ -96,7 +106,7 @@ export function projectHistoryView<T extends HistoryMessageSource>(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}`,+ isStreaming: streaming, revision: `${last.id}:${body.length}:${historyRowsHash(body)}`,} };});return attach(projected);@@ -172,11 +182,7 @@ function projectHistorySourceView<T extends HistoryMessageSource>(const anchor = run.find((item) => item.activity && item.row.role !== 'tool_result')?.row ?? first;const startedAtMs = boundary ?? Date.parse(first.createdAt);const endedAtMs = Date.parse(last.createdAt);- let hash = 2166136261;- for (const item of run) {- const text = JSON.stringify(item.row);- for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 16777619);- }+ const hash = historyRowsHash(run.map((item) => item.row));return { type: 'group', summary: {key: `work-${anchor.clientId || anchor.id}`,anchorClientId: anchor.clientId || anchor.id,@@ -192,7 +198,7 @@ function projectHistorySourceView<T extends HistoryMessageSource>(messageCount: run.length,toolCount: run.filter((item) => item.row.role === 'tool_use').length,isStreaming: active,- revision: `${last.id}:${run.length}:${hash >>> 0}`,+ revision: `${last.id}:${run.length}:${hash}`,} };};// Consumers read artifacts from leaf summaries only (historyWorkSummaries), sodiff --git a/packages/maker-shared/src/historyWorkLines.ts b/packages/maker-shared/src/historyWorkLines.tsindex 679bcb5dda..d859e0f63c 100644--- a/packages/maker-shared/src/historyWorkLines.ts+++ b/packages/maker-shared/src/historyWorkLines.ts@@ -20,10 +20,16 @@ import {export const HISTORY_WORK_LINE_LIMIT = 5;/** One rendered line never shows more; longer values only cost bytes. */export const HISTORY_WORK_LINE_TEXT_CHARS = 160;-const DESCRIPTOR_TEXT_CHARS = 300;-const DESCRIPTOR_LIST_ITEMS = 20;/** UTF-8 budget for the whole window, so one patch stays a small push. */export const HISTORY_WORK_LINES_MAX_BYTES = 6 * 1024;+/** Each line fits its share of the window, so five lines always fit together. */+export const HISTORY_WORK_LINE_MAX_BYTES = Math.floor(HISTORY_WORK_LINES_MAX_BYTES / HISTORY_WORK_LINE_LIMIT);+/** Descriptor reductions tried in order until the whole line fits its byte share. */+const DESCRIPTOR_LIMITS = [+ { text: 300, items: 20 },+ { text: 80, items: 4 },+ { text: 40, items: 1 },+] as const;export type HistoryWorkLine =| {@@ -49,14 +55,24 @@ function cut(text: string, limit: number): string {return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;}-/** Display facts only: diffs are dropped, strings and lists bounded. */-function liteDescriptor(value: unknown): unknown {- if (typeof value === 'string') return cut(value, DESCRIPTOR_TEXT_CHARS);- if (Array.isArray(value)) return value.slice(0, DESCRIPTOR_LIST_ITEMS).map(liteDescriptor);+/** A list keeps at most this many entries, so counts such as "edited N files" stay exact up to it. */+const DESCRIPTOR_LIST_ENTRIES = 20;++/**+ * Display facts only: diffs are dropped, strings and lists bounded. Entries past+ * `limits.items` become empty shells that only keep a list's length: a row reads list+ * entries only when there is exactly one, and a remote line opens its group on click.+ */+function liteDescriptor(value: unknown, limits: { text: number; items: number }): unknown {+ if (typeof value === 'string') return cut(value, limits.text);+ if (Array.isArray(value)) {+ return value.slice(0, DESCRIPTOR_LIST_ENTRIES)+ .map((entry, index) => index < limits.items ? liteDescriptor(entry, limits) : {});+ }if (!value || typeof value !== 'object') return value;const result: Record<string, unknown> = {};for (const [key, entry] of Object.entries(value)) {- result[key] = key === 'diff' ? '' : liteDescriptor(entry);+ result[key] = key === 'diff' ? '' : liteDescriptor(entry, limits);}return result;}@@ -143,20 +159,34 @@ export function projectHistoryWorkLines(? { ...resolved, intent: activity.intentOverride }: resolved;const record = input && typeof input === 'object' && !Array.isArray(input) ? input as Record<string, unknown> : null;- const ghost = /(?:^|:|__)ghost_call$/.test(toolName) && typeof record?.ghost_id === 'string'- ? { id: cut(record.ghost_id, DESCRIPTOR_TEXT_CHARS), tool: cut(typeof record.tool === 'string' ? record.tool : '', DESCRIPTOR_TEXT_CHARS) }- : undefined;+ const hasError = activity.toolResult !== undefined && isToolResultFailureLike(descriptor, activity.toolResult);+ for (const limits of DESCRIPTOR_LIMITS) {+ const ghost = /(?:^|:|__)ghost_call$/.test(toolName) && typeof record?.ghost_id === 'string'+ ? { id: cut(record.ghost_id, limits.text), tool: cut(typeof record.tool === 'string' ? record.tool : '', limits.text) }+ : undefined;+ const line: HistoryWorkLine = {+ kind: 'tool',+ key: activity.key,+ toolName: cut(toolName, limits.text),+ descriptor: liteDescriptor(descriptor, limits) as ToolUseDescriptor,+ status: activity.status,+ ...(hasError ? { hasError: true as const } : {}),+ ...(ghost ? { ghost } : {}),+ };+ if (utf8Length(JSON.stringify(line)) <= HISTORY_WORK_LINE_MAX_BYTES) return line;+ }+ // Nothing descriptive fits: the tool name alone still reports the activity and its state.+ const last = DESCRIPTOR_LIMITS[DESCRIPTOR_LIMITS.length - 1].text;return {kind: 'tool',key: activity.key,- toolName: cut(toolName, DESCRIPTOR_TEXT_CHARS),- descriptor: liteDescriptor(descriptor) as ToolUseDescriptor,+ toolName: cut(toolName, last),+ descriptor: { kind: 'generic', toolName: cut(toolName, last) },status: activity.status,- ...(activity.toolResult !== undefined && isToolResultFailureLike(descriptor, activity.toolResult) ? { hasError: true as const } : {}),- ...(ghost ? { ghost } : {}),+ ...(hasError ? { hasError: true as const } : {}),};});- // Older lines give way first; the newest line always fits after the per-field caps.- while (lines.length > 1 && utf8Length(JSON.stringify(lines)) > HISTORY_WORK_LINES_MAX_BYTES) lines.shift();+ // Every line is within its share, so this only guards the invariant itself.+ while (lines.length > 0 && utf8Length(JSON.stringify(lines)) > HISTORY_WORK_LINES_MAX_BYTES) lines.shift();return lines;}