Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(device-link): 远程运行中工作组改由电脑端下发最近 5 行活动并就地更新
Dash303370439b6a
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.tsindex d733caa4ae..781b11a8d5 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts@@ -52,6 +52,7 @@ import { currentDbRpcAdmissionClass } from '../../localDb/client/rpcAdmission';import { getDeviceLinkInvokeContext } from '../invoke-context';import { HistoryViewController, type HistoryViewPage, type HistoryMessageSource } from '@cindy/maker-shared/message-window';import * as subscriptions from '../subscriptions';+import { setHistoryWorkPageReader } from '../historyViewPush';/** 最小 mock client:只实现被测路径用到的两个发送方法。 */function mkClient(@@ -273,6 +274,62 @@ describe('history detail interest', () => {vi.useRealTimers();}});+ it('replaces the notice with a work patch only for a same-account work-line controller whose page shape held', async () => {+ vi.useFakeTimers();+ const shape = (revision: string, keys = ['c0', 'work-c1']) => ({+ keys, fingerprints: keys.map((key) => key === 'work-c1' ? 'running:m1' : `fp-${key}`), running: new Map([['work-c1', revision]]),+ });+ const summary = { key: 'work-c1', firstMessageId: 'm1', lastMessageId: 'm9', startedAtMs: 1, endedAtMs: 2,+ isStreaming: true, messageCount: 3, toolCount: 2, revision: 'r2', lines: [] };+ let next = shape('r2');+ setHistoryWorkPageReader(async (_sid, onShape) => {+ onShape(next);+ return { version: 1, hasMore: false, nextCursor: null, items: [+ { type: 'messages', key: 'c0', messages: [] },+ { type: 'work', key: 'work-c1', summary: { ...summary, revision: next.running.get('work-c1')! } },+ ] };+ });+ try {+ const client = mkClient();+ __testing.setActiveClient(client as never);+ for (const peer of ['lines', 'plain']) subscriptions.subscribe(peer, ['session:s1']);+ subscriptions.prepareHistoryView('lines', 's1')!.update(['work-c1'], { workLines: true, shape: shape('r1') });+ subscriptions.prepareHistoryView('plain', 's1')!.update(['work-c1']);+ const toolUse = { sessionId: 's1', event: { type: 'tool_use', data: { toolUseId: 't9', toolName: 'Read', input: { file_path: '/a' } } } };+ __testing.forwardPush('maker:event', toolUse);+ await vi.advanceTimersByTimeAsync(500);+ const sent = () => client.sendPush.mock.calls.filter(([, channel]) => channel !== 'maker:event');+ expect(sent()).toEqual(expect.arrayContaining([+ ['plain', 'maker:history-view-changed', { sessionId: 's1' }],+ ['lines', 'maker:history-work-patch', { version: 1, sessionId: 's1', baseRevision: 'r1',+ item: { type: 'work', key: 'work-c1', summary: { ...summary, revision: 'r2' } } }],+ ]));+ expect(sent()).toHaveLength(2);++ // A new top-level item means the page itself moved: the controller re-reads as before.+ client.sendPush.mockClear();+ next = shape('r3', ['c0', 'c5', 'work-c1']);+ __testing.forwardPush('maker:event', toolUse);+ await vi.advanceTimersByTimeAsync(500);+ expect(sent()).toEqual(expect.arrayContaining([['lines', 'maker:history-view-changed', { sessionId: 's1' }]]));++ // Folded thinking deltas reach a work-line controller only while its single line can change.+ client.sendPush.mockClear();+ subscriptions.prepareHistoryView('lines', 's1')!.update(['work-c1'], { workLines: true, shape: shape('r3') });+ next = shape('r4');+ const delta = (text: string) => ({ sessionId: 's1', event: { type: 'thinking', data: { stage: 'delta', blockId: 'b7', text } } });+ __testing.forwardPush('maker:event', delta('x'.repeat(200)));+ await vi.advanceTimersByTimeAsync(500);+ __testing.forwardPush('maker:event', delta('more'));+ await vi.advanceTimersByTimeAsync(500);+ expect(sent().filter(([peer]) => peer === 'lines')).toHaveLength(1);+ expect(sent().filter(([peer]) => peer === 'plain')).toHaveLength(0);+ } finally {+ setHistoryWorkPageReader(null);+ __testing.reset();+ vi.useRealTimers();+ }+ });it.each(['first', 'second'])('sends full thinking to peers with %s streaming group expanded and coalesces folded summaries', async (expandedKey) => {vi.useFakeTimers();try {diff --git a/apps/desktop/src/main/device-link/__tests__/historyWorkPatch.test.ts b/apps/desktop/src/main/device-link/__tests__/historyWorkPatch.test.tsnew file mode 100644index 0000000000..56fb5b9f43--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/historyWorkPatch.test.ts@@ -0,0 +1,208 @@+import { afterEach, describe, expect, it } from 'vitest';+import type { HistoryMessageSource, HistoryViewPage } from '@cindy/maker-shared/message-window';+import { createHistoryViewReader, type HistoryPageShape } from '../../localDb/ipc/historyViewReader';+import {+ buildHistoryWorkPatch,+ historyWorkPatchKey,+ setHistoryWorkPageReader,+ thinkingDeltaUpdatesWorkLine,+} from '../historyViewPush';++let clock = 0;+function at(): string {+ clock += 1;+ return new Date(1_700_000_000_000 + clock).toISOString();+}+function user(n: number): HistoryMessageSource {+ return { id: `m${n}`, clientId: `c${n}`, rowid: n, role: 'user', content: 'please work', createdAt: at() };+}+function assistant(n: number, text: string): HistoryMessageSource {+ return { id: `m${n}`, clientId: `c${n}`, rowid: n, role: 'assistant', content: text, createdAt: at() };+}+function toolUse(n: number, toolName: string, input: unknown): HistoryMessageSource {+ return { id: `m${n}`, clientId: `c${n}`, rowid: n, role: 'tool_use', content: { toolName, toolUseId: `t${n}`, input }, createdAt: at() };+}+function toolResult(n: number, useN: number, content: string): HistoryMessageSource {+ return { id: `m${n}`, clientId: `c${n}`, rowid: n, role: 'tool_result', toolUseId: `t${useN}`, content, createdAt: at() };+}+function thinking(n: number, text: string): HistoryMessageSource {+ return { id: `m${n}`, clientId: `c${n}`, rowid: n, role: 'thinking', content: text, createdAt: at() };+}++/** Outline reads omit bodies like the real Host; every write bumps the DB-wide revision. */+function host(source: HistoryMessageSource[]) {+ let writes = 0;+ const list = async (_sid: string, opts: { before?: string; after?: string; limit: number }) => {+ const start = opts.after ? source.findIndex((r) => r.id === opts.after) + 1 : 0;+ const end = opts.before ? source.findIndex((r) => r.id === opts.before) : source.length;+ const selected = source.slice(start, end);+ return (opts.after ? selected.slice(0, opts.limit) : selected.slice(-opts.limit)).reverse();+ };+ const reader = createHistoryViewReader({+ list,+ // Mirrors historyOutlineContent: bodies stay on disk, only grouping facts are read.+ outline: async (sid, opts) => (await list(sid, opts)).map((row) => {+ 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 === 'tool_use') {+ return { ...row, content: { toolName: content.toolName, toolUseId: content.toolUseId,+ input: { file_path: content.input?.file_path, path: content.input?.path, command: content.input?.command } } };+ }+ return row;+ }),+ hydrate: async (_sid, ids) => source.filter((row) => ids.includes(row.id)),+ revision: async () => `db:${writes}`,+ anchor: async (_sid, id) => {+ const found = source.find((row) => row.id === id);+ if (!found) throw new Error('NOT_FOUND');+ return found;+ },+ running: () => true,+ });+ return {+ write(...rows: HistoryMessageSource[]) {+ source.push(...rows);+ 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; } });+ return { page, shape: shape! };+ },+ reader,+ };+}++const bytes = (value: unknown) => Buffer.byteLength(JSON.stringify(value), 'utf8');+const bigOutput = (n: number) => `line ${n}: ${'output '.repeat(3000)}`;++afterEach(() => setHistoryWorkPageReader(null));++describe('running work lines', () => {+ it('attaches the latest five Host-projected lines to the running item without any body', async () => {+ const source = [user(0), assistant(1, 'Starting.')];+ let n = 2;+ for (let step = 0; step < 8; step += 1) {+ source.push(toolUse(n, 'Bash', { command: `pnpm test --filter pkg${step}` }), toolResult(n + 1, n, bigOutput(step)));+ n += 2;+ }+ source.push(thinking(n, `Now I should\ncheck ${'the next thing '.repeat(40)}`));+ const { page, shape } = await host(source).page();+ const running = page.items.at(-1);+ if (running?.type !== 'work') throw new Error('missing running item');+ const lines = running.summary.lines!;+ expect(lines).toHaveLength(5);+ expect(lines.at(-1)).toMatchObject({ kind: 'thinking', truncated: true });+ const last = lines.at(-1)!;+ expect(last.kind === 'thinking' ? last.text.length : Infinity).toBeLessThanOrEqual(160);+ expect(lines.slice(0, 4).every((line) => line.kind === 'tool' && line.status === 'done')).toBe(true);+ expect(JSON.stringify(lines)).not.toContain('output output');+ expect(shape.running.get(running.key)).toBe(running.summary.revision);+ });++ it('resolves intent from the full command before cutting it, so a long command keeps its intent', async () => {+ const command = `cat src/a.ts && ${'echo filler; '.repeat(80)}`;+ const source = [user(0), toolUse(1, 'Bash', { command, description: '' })];+ const { page } = await host(source).page();+ const running = page.items.at(-1);+ if (running?.type !== 'work') throw new Error('missing running item');+ const [line] = running.summary.lines!;+ if (line.kind !== 'tool' || line.descriptor.kind !== 'command') throw new Error('expected command line');+ expect(line.descriptor.command.length).toBeLessThanOrEqual(300);+ expect(line.status).toBe('running');+ });++ it('keeps the page shape stable across DB writes that touch only the running item', async () => {+ const source = [user(0), assistant(1, 'Earlier answer'), user(2), toolUse(3, 'Read', { file_path: '/repo/a.ts' })];+ const h = host(source);+ const first = await h.page();+ h.write(toolResult(4, 3, 'contents of a'), toolUse(5, 'Grep', { pattern: 'needle', path: '/repo' }));+ const second = await h.page();+ // Completed items carry a DB-wide revision suffix that changed; their fingerprints must not.+ expect(second.shape.fingerprints).toEqual(first.shape.fingerprints);+ const key = historyWorkPatchKey(first.shape, second.shape);+ expect(key).toBe(second.page.items.at(-1)!.key);+ });++ it('refuses a patch whenever anything besides the running item moved', async () => {+ const source = [user(0), toolUse(1, 'Read', { file_path: '/repo/a.ts' })];+ const h = host(source);+ const first = await h.page();+ h.write(toolResult(2, 1, 'ok'), assistant(3, 'Found it, continuing.'), toolUse(4, 'Read', { file_path: '/repo/b.ts' }));+ const second = await h.page();+ expect(historyWorkPatchKey(first.shape, second.shape)).toBeNull();+ });++ it('builds a patch against the delivered revision, reports no-ops, and refreshes on reshape', async () => {+ const source = [user(0), toolUse(1, '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(await buildHistoryWorkPatch('s', delivered.shape)).toEqual({ kind: 'unchanged' });++ h.write(toolResult(2, 1, 'ok'));+ const result = await buildHistoryWorkPatch('s', delivered.shape);+ if (result.kind !== 'patch') throw new Error(`expected patch, got ${result.kind}`);+ const running = delivered.page.items.at(-1)!;+ if (running.type !== 'work') throw new Error('missing running item');+ expect(result.patch.baseRevision).toBe(running.summary.revision);+ expect(result.patch.item.summary.lines!.at(-1)).toMatchObject({ kind: 'tool', status: 'done' });++ h.write(assistant(3, 'Done reading.'), user(4));+ expect((await buildHistoryWorkPatch('s', result.shape)).kind).toBe('refresh');+ });++ it('leaves an oversized summary to the page read and its frame handling', async () => {+ const source = [user(0), toolUse(1, 'Read', { file_path: '/repo/a.ts' })];+ const h = host(source);+ const delivered = await h.page();+ setHistoryWorkPageReader(async (sid, onShape) => {+ const page = await h.reader.page(sid, undefined, true, { workLines: true, onShape });+ const running = page.items.at(-1);+ if (running?.type === 'work') {+ running.summary.artifacts = Array.from({ length: 2000 }, (_, i) => ({ path: `/repo/out/${i}.png`, source: 'tool' as const, createdAt: '' }));+ }+ return page;+ });+ h.write(toolResult(2, 1, 'ok'));+ expect((await buildHistoryWorkPatch('s', delivered.shape)).kind).toBe('refresh');+ });++ it('costs a small fraction of the page re-read that each activity notice used to trigger', async () => {+ const source = [user(0), assistant(1, 'Plan: '.concat('details '.repeat(400)))];+ const h = host(source);+ setHistoryWorkPageReader((sid, onShape) => h.reader.page(sid, undefined, true, { workLines: true, onShape }));+ let delivered = (await h.page()).shape;+ let n = 2;+ let rereadBytes = 0;+ let patchBytes = 0;+ for (let step = 0; step < 30; step += 1) {+ h.write(toolUse(n, 'Read', { file_path: `/repo/file${step}.ts` }), toolResult(n + 1, n, bigOutput(step)));+ n += 2;+ const reread = await h.reader.page('s', undefined, true);+ rereadBytes += bytes(reread);+ const result = await buildHistoryWorkPatch('s', delivered);+ if (result.kind === 'patch') {+ patchBytes += bytes(result.patch);+ delivered = result.shape;+ } else {+ // The first activity opens a new group: the controller re-reads, as before.+ expect(step).toBe(0);+ const fresh = await h.page();+ patchBytes += bytes(fresh.page);+ delivered = fresh.shape;+ }+ }+ expect(patchBytes * 2).toBeLessThan(rereadBytes);+ });++ it('notifies thinking deltas only while they still change the single line', () => {+ const delta = (text: string, blockId = 'b1') => ({ sessionId: 's', event: { type: 'thinking', data: { stage: 'delta', blockId, text } } });+ expect(thinkingDeltaUpdatesWorkLine('s', delta('a'.repeat(100)))).toBe(true);+ expect(thinkingDeltaUpdatesWorkLine('s', delta('b'.repeat(100)))).toBe(true);+ expect(thinkingDeltaUpdatesWorkLine('s', delta('c'))).toBe(false);+ expect(thinkingDeltaUpdatesWorkLine('s', delta('d', 'b2'))).toBe(true);+ expect(thinkingDeltaUpdatesWorkLine('s', { sessionId: 's', event: { type: 'tool_use', data: {} } })).toBe(false);+ });+});diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 2347943653..2b40350a88 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -99,7 +99,8 @@ import { remoteDesktop, requestRemoteDesktop } from '../remote-desktop';import { remoteCredentialHost } from '../remote-desktop/credentialHost';import { ORCA_REMOTE_WORKER_OPEN_CHANNEL, REMOTE_DESKTOP_CHANNEL } from '@cindy/device-link';import type { DeviceLinkClient } from '@cindy/device-link';-import { isDeferredHistoryPush, deferredToolBoundary } from './historyViewPush';+import { isDeferredHistoryPush, deferredToolBoundary, buildHistoryWorkPatch, thinkingDeltaUpdatesWorkLine } from './historyViewPush';+import { HISTORY_WORK_PATCH_CHANNEL } from '@cindy/maker-shared/message-window';import { mapHistoryViewMessages, type HistoryMessageSource, type HistoryViewItem } from '@cindy/maker-shared/message-window';import { createLogger } from '../logger';import { projectMobileMessagePage, projectMobileToolPush } from './mobileToolProjection';@@ -1940,13 +1941,54 @@ function stageHistoryNotice(dst: string, sessionId: string, ownerStamp?: PushOwnconst timer = setTimeout(() => {pending.delete(sessionId);if (pending.size === 0) historyNoticeStages.delete(dst);- if (subscriptions.getControllersForTopic(`session:${sessionId}`).includes(dst)) {- sendPushBestEffort(dst, 'maker:history-view-changed', { sessionId }, ownerStamp);- }+ if (!subscriptions.getControllersForTopic(`session:${sessionId}`).includes(dst)) return;+ if (!isSharedTaskPeer(dst) && subscriptions.historyWorkPatchTarget(dst, sessionId)) {+ sendHistoryWorkUpdate(dst, sessionId, ownerStamp);+ } else sendPushBestEffort(dst, 'maker:history-view-changed', { sessionId }, ownerStamp);}, 500);pending.set(sessionId, { timer, ownerStamp });historyNoticeStages.set(dst, pending);}++/**+ * Work-line controllers get the changed running item instead of a re-read notice when+ * nothing else on their delivered page moved. One computation per controller and task+ * runs at a time; notices arriving meanwhile coalesce into one more pass.+ */+const historyWorkRuns = new Map<string, { again: boolean; ownerStamp?: PushOwnerStamp }>();+function sendHistoryWorkUpdate(dst: string, sessionId: string, ownerStamp?: PushOwnerStamp): void {+ const runKey = `${dst}\u0000${sessionId}`;+ const running = historyWorkRuns.get(runKey);+ if (running) {+ running.again = true;+ running.ownerStamp = ownerStamp;+ return;+ }+ const state = { again: true, ownerStamp };+ historyWorkRuns.set(runKey, state);+ const subscribed = () => subscriptions.getControllersForTopic(`session:${sessionId}`).includes(dst);+ void (async () => {+ try {+ while (state.again && subscribed()) {+ state.again = false;+ const target = subscriptions.historyWorkPatchTarget(dst, sessionId);+ if (!target) {+ sendPushBestEffort(dst, 'maker:history-view-changed', { sessionId }, state.ownerStamp);+ continue;+ }+ const startedAt = Date.now();+ const result = await buildHistoryWorkPatch(sessionId, target.shape);+ log.debug(`history work update ${result.kind} in ${Date.now() - startedAt}ms`);+ if (!subscribed() || result.kind === 'unchanged') continue;+ if (result.kind === 'patch' && subscriptions.recordHistoryWorkPatch(dst, sessionId, target.seq, result.shape)) {+ sendPushBestEffort(dst, HISTORY_WORK_PATCH_CHANNEL, result.patch, state.ownerStamp);+ } else sendPushBestEffort(dst, 'maker:history-view-changed', { sessionId }, state.ownerStamp);+ }+ } finally {+ historyWorkRuns.delete(runKey);+ }+ })();+}function clearHistoryNotices(dst: string): void {for (const item of historyNoticeStages.get(dst)?.values() ?? []) clearTimeout(item.timer);historyNoticeStages.delete(dst);@@ -2060,6 +2102,7 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerStconst historySessionId = readPushSessionId(remotePayload);const deferred = historySessionId !== null && isDeferredHistoryPush(channel, remotePayload,(id) => readHistoryToolName(historySessionId, id));+ const thinkingLine = deferred && historySessionId !== null && thinkingDeltaUpdatesWorkLine(historySessionId, remotePayload);const offlineTargets = targetsFor(true).filter((dst) => !liveTargets.includes(dst));for (const dst of offlineTargets) {@@ -2083,7 +2126,8 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerStconst folded = subscriptions.projectsHistoryDetails(dst, historySessionId);const event = (remotePayload as { event?: { type?: string; data?: { stage?: string } } })?.event;// A folded duration ticks locally. Token deltas do not change its summary.- if (!folded || event?.type !== 'thinking' || event.data?.stage !== 'delta') stageHistoryNotice(dst, historySessionId, ownerStamp);+ if (!folded || event?.type !== 'thinking' || event.data?.stage !== 'delta'+ || (thinkingLine && subscriptions.historyWorkPatchTarget(dst, historySessionId))) stageHistoryNotice(dst, historySessionId, ownerStamp);if (folded) {const boundary = channel === MAKER_PUSH.EVENT ? deferredToolBoundary(remotePayload) : null;if (boundary === null) continue;diff --git a/apps/desktop/src/main/device-link/historyViewPush.ts b/apps/desktop/src/main/device-link/historyViewPush.tsindex 5e9e0b7b28..2e55929fbb 100644--- a/apps/desktop/src/main/device-link/historyViewPush.ts+++ b/apps/desktop/src/main/device-link/historyViewPush.ts@@ -1,4 +1,8 @@-import { isHistoryDetailTool, hasVisibleHistoryResult } from '@cindy/maker-shared/message-window';+import {+ HISTORY_WORK_LINE_TEXT_CHARS, isHistoryDetailTool, hasVisibleHistoryResult,+ type HistoryMessageSource, type HistoryViewPage, type HistoryWorkPatch,+} from '@cindy/maker-shared/message-window';+import type { HistoryPageShape } from '../localDb/ipc/historyViewReader';function record(value: unknown): Record<string, unknown> | null {return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;}@@ -36,3 +40,71 @@ export function deferredToolBoundary(payload: unknown): unknown | null {? { ...push, event: { ...event, data: { toolUseId: data.toolUseId, toolName: data.toolName, input: null } } }: null;}++const HISTORY_WORK_PATCH_MAX_BYTES = 64 * 1024;++type WorkPageReader = (sessionId: string, onShape: (shape: HistoryPageShape) => void) => Promise<HistoryViewPage<HistoryMessageSource>>;+let workPageReader: WorkPageReader | null = null;++/** Registered by the history IPC module; dispatch reads the same latest page the controller would. */+export function setHistoryWorkPageReader(reader: WorkPageReader | null): void {+ workPageReader = reader;+}++/**+ * The single running top-level item whose replacement turns `delivered` into `next`,+ * or null when anything else on the page changed (new group, prose, cards, a cleared or+ * rewound range, a different page window) and the controller must re-read the page.+ */+export function historyWorkPatchKey(delivered: HistoryPageShape, next: HistoryPageShape): string | null {+ if (next.running.size !== 1 || delivered.running.size !== 1) return null;+ if (delivered.keys.length !== next.keys.length || delivered.keys.some((key, index) => key !== next.keys[index])) return null;+ if (delivered.fingerprints.some((value, index) => value !== next.fingerprints[index])) return null;+ const [key] = next.running.keys();+ return delivered.running.has(key) ? key : null;+}++export type HistoryWorkPatchResult =+ | { kind: 'patch'; patch: HistoryWorkPatch; shape: HistoryPageShape }+ | { kind: 'unchanged' }+ | { kind: 'refresh' };++/** Build the push that replaces an activity notice for a controller with a delivered shape. */+export async function buildHistoryWorkPatch(sessionId: string, delivered: HistoryPageShape): Promise<HistoryWorkPatchResult> {+ if (!workPageReader) return { kind: 'refresh' };+ let shape: HistoryPageShape | undefined;+ let page: HistoryViewPage<HistoryMessageSource>;+ try {+ page = await workPageReader(sessionId, (value) => { shape = value; });+ } catch {+ // The controller's own read reports a real failure through its existing path.+ return { kind: 'refresh' };+ }+ const key = shape ? historyWorkPatchKey(delivered, shape) : null;+ const item = key ? page.items.find((value) => value.key === key) : undefined;+ if (!shape || !key || item?.type !== 'work' || item.children) return { kind: 'refresh' };+ const baseRevision = delivered.running.get(key)!;+ if (item.summary.revision === baseRevision) return { kind: 'unchanged' };+ const patch: HistoryWorkPatch = { version: 1, sessionId, baseRevision, item: { type: 'work', key, summary: item.summary } };+ // A summary with an unusually long artifact list goes through the page read, which+ // owns the oversized-frame handling; a push has none.+ if (Buffer.byteLength(JSON.stringify(patch), 'utf8') > HISTORY_WORK_PATCH_MAX_BYTES) return { kind: 'refresh' };+ return { kind: 'patch', shape, patch };+}++/**+ * 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.+ */+const thinkingLineChars = new Map<string, { blockId: unknown; chars: number }>();+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;+}diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.tsindex ebf66657ba..5be27ceafd 100644--- a/apps/desktop/src/main/device-link/subscriptions.ts+++ b/apps/desktop/src/main/device-link/subscriptions.ts@@ -14,6 +14,7 @@*/import type { Topic } from '@cindy/device-link';+import type { HistoryPageShape } from '../localDb/ipc/historyViewReader';/** legacy 老控制端(link-open)订阅的「全部」topic 标记。 */export const LEGACY_TOPIC = '*';@@ -48,13 +49,24 @@ const rememberedTopicsByController = new Map<string, Set<StoredTopic>>();* 新控制端误判成 legacy,否则 set-model 的显式 provider null 会被当成占位。*/const rememberedCapabilitiesByController = new Map<string, Set<string>>();-const historyViewsByController = new Map<string, Map<string, { ready: boolean; liveKeys: readonly string[]; expanded: Set<string> }>>();+interface HistoryViewRecord {+ ready: boolean;+ liveKeys: readonly string[];+ expanded: Set<string>;+ /** The controller's latest page asked for work lines, so it also accepts work patches. */+ workLines: boolean;+ /** Last latest-page shape this controller received, by page read or work patch. */+ shape?: HistoryPageShape;+ shapeSeq: number;+}+const historyViewsByController = new Map<string, Map<string, HistoryViewRecord>>();/** Capture this subscription before reading; only its successful result may enable filtering. */export function prepareHistoryView(deviceId: string, sessionId: string) {if (!controllerHasTopic(deviceId, `session:${sessionId}`)) return undefined;const views = historyViewsByController.get(deviceId) ?? new Map();- const view = views.get(sessionId) ?? { ready: false, liveKeys: [], expanded: new Set<string>() };+ const view: HistoryViewRecord = views.get(sessionId)+ ?? { ready: false, liveKeys: [], expanded: new Set<string>(), workLines: false, shapeSeq: 0 };views.set(sessionId, view);historyViewsByController.set(deviceId, views);const isCurrent = () => historyViewsByController.get(deviceId)?.get(sessionId) === view;@@ -62,10 +74,15 @@ export function prepareHistoryView(deviceId: string, sessionId: string) {disable(): void {if (isCurrent()) views.delete(sessionId);},- update(liveKeys: readonly string[]): void {+ update(liveKeys: readonly string[], latest?: { workLines: boolean; shape?: HistoryPageShape }): void {if (!isCurrent()) return;view.liveKeys = [...liveKeys];view.ready = true;+ if (latest) {+ view.workLines = latest.workLines;+ view.shape = latest.shape;+ view.shapeSeq += 1;+ }},setExpanded(keys: readonly string[]): void {// Intent alone cannot opt a peer in or revive an old link/subscription.@@ -85,6 +102,21 @@ export function hasHistoryView(deviceId: string, sessionId: string, includePendireturn !!view && (includePending || view.ready);}+/** A controller that opted into work lines; `seq` changes whenever its delivered shape changes. */+export function historyWorkPatchTarget(deviceId: string, sessionId: string): { shape: HistoryPageShape; seq: number } | null {+ const view = historyViewsByController.get(deviceId)?.get(sessionId);+ return view?.ready && view.workLines && view.shape ? { shape: view.shape, seq: view.shapeSeq } : null;+}++/** Record a patched shape unless a newer page read was delivered meanwhile. */+export function recordHistoryWorkPatch(deviceId: string, sessionId: string, seq: number, shape: HistoryPageShape): boolean {+ const view = historyViewsByController.get(deviceId)?.get(sessionId);+ if (!view?.ready || view.shapeSeq !== seq) return false;+ view.shape = shape;+ view.shapeSeq += 1;+ return true;+}+export function projectsHistoryDetails(deviceId: string, sessionId: string): boolean {const view = historyViewsByController.get(deviceId)?.get(sessionId);return !!view?.ready && !view.liveKeys.some((key) => view.expanded.has(key));diff --git a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts b/apps/desktop/src/main/localDb/ipc/historyViewReader.tsindex fe08be34bd..84586555ad 100644--- a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts+++ b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts@@ -1,17 +1,45 @@-import { randomUUID } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import { throwIpcError } from '../../utils/ipcValidate';import { isDeliveryProseText } from '@cindy/maker-shared/message-render';import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';import {HISTORY_VIEW_PAGE_BYTES, HISTORY_VIEW_PAGE_ITEMS, HISTORY_DETAIL_PAGE_BYTES,- projectHistoryView, historySubagentScopes, mapHistoryViewMessages, historyWorkSummaries, type HistoryMessageSource, type HistoryViewItem,- type HistoryViewPage, type HistoryDetailPage, type HistoryWorkReference,+ projectHistoryView, projectHistoryWorkLines, historySubagentScopes, mapHistoryViewMessages, historyWorkSummaries,+ type HistoryMessageSource, 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;interface ReadOptions { limit: number; before?: string; after?: string }++/**+ * What a latest page looked like when it was delivered. Each top-level item has a+ * fingerprint taken before the outline revision suffix (a DB-wide write counter that+ * changes on every write); a running leaf work item is identified only by its start,+ * because its contents are exactly what a work patch replaces.+ */+export interface HistoryPageShape {+ keys: string[];+ fingerprints: string[];+ /** Running top-level leaf work items, key → revision exactly as delivered. */+ running: Map<string, string>;+}++export interface HistoryPageOptions {+ /** Attach Host-projected single-line activities to running top-level work items. */+ workLines?: boolean;+ /** Receives the latest page's shape; never serialized. */+ onShape?: (shape: HistoryPageShape) => void;+}++function isRunningLeafWork<T extends HistoryMessageSource>(item: HistoryViewItem<T>): item is Extract<HistoryViewItem<T>, { type: 'work' }> {+ return item.type === 'work' && !item.children && item.summary.isStreaming;+}++function fingerprint(value: unknown): string {+ return createHash('sha1').update(JSON.stringify(value)).digest('base64');+}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. */@@ -70,7 +98,7 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hilet detailRevision: string | undefined;let detailCacheBytes = 0;return {- async page(sessionId: string, before?: string, lazyDetails = false): Promise<HistoryViewPage<T>> {+ async page(sessionId: string, before?: string, lazyDetails = false, options: HistoryPageOptions = {}): Promise<HistoryViewPage<T>> {const outlined = lazyDetails && !!deps.outline && !!deps.hydrate;const batchSize = outlined ? 1000 : 100;const rowBudget = outlined ? 100000 : MAX_HISTORY_SCAN_ROWS;@@ -158,6 +186,31 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hiconst 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)));+ }+ if (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);+ 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);+ }+ item.summary.lines = projectHistoryWorkLines(tail, true);+ } catch {+ // Lines are a display hint. A range changing mid-read keeps the page usable;+ // the next activity notice recomputes them.+ item.summary.lines = [];+ }+ }+ }+ const fingerprints = options.onShape && !before ? new Map(items.map((item) => [item,+ isRunningLeafWork(item) ? `running:${item.summary.firstMessageId}` : fingerprint(item)])) : undefined;+ if (outlined) {// 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.@@ -187,6 +240,13 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hiconst anchors = raw.length ? [raw[0].id, raw[raw.length - 1].id] : [];if (beforeAnchor) anchors.push(beforeAnchor.id);await Promise.all(anchors.map((id) => deps.anchor(sessionId, id, outlined)));+ if (fingerprints) {+ options.onShape!({+ keys: selected.map((item) => item.key),+ fingerprints: selected.map((item) => fingerprints.get(item)!),+ running: new Map(selected.filter(isRunningLeafWork).map((item) => [item.key, item.summary.revision])),+ });+ }return { version: 1, items: selected, hasMore,nextCursor: hasMore && selected.length ? firstId(selected[0]) : null };},diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex 453943a3dd..3b0285dc2b 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -68,7 +68,8 @@ import { capReferenceMessageRows } from './history.js';import type { Message, MessageRole, AgentMeta } from '../../../renderer/lib/ccAgent.types';import { scheduleBotRemoteResourceChangedForSession } from '../../maker-ipc/botRemoteResourceInvalidation';import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer';-import { createHistoryViewReader, MAX_HISTORY_SCAN_ROWS } from './historyViewReader';+import { createHistoryViewReader, MAX_HISTORY_SCAN_ROWS, type HistoryPageShape } from './historyViewReader';+import { setHistoryWorkPageReader } from '../../device-link/historyViewPush';const log = createLogger('localDb/messages');@@ -418,18 +419,25 @@ export function registerMessageIpc(if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);const sid = requireString(sessionId, 'sessionId');const before = (opts as { before?: unknown } | null)?.before;+ const context = getDeviceLinkInvokeContext();+ // Work lines and their patches serve same-account remote controllers only; a shared+ // guest keeps the existing projection and authorization path unchanged.+ const workLines = (opts as { workLines?: unknown } | null)?.workLines === true && !!context?.historyView && !context.sharedTask;+ let shape: HistoryPageShape | undefined;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();+ (opts as { lazyDetails?: unknown } | null)?.lazyDetails === true,+ workLines ? { workLines, onShape: (value) => { shape = value; } } : {}).catch((error) => {+ if (isHistoryViewUnavailable(error)) context?.historyView?.disable();throw error;});if (before == null) {const liveKeys = historyViewLeaves(page.items).filter((item) => item.type === 'work' && item.summary.isStreaming).map((item) => item.key);- getDeviceLinkInvokeContext()?.historyView?.update(liveKeys);+ context?.historyView?.update(liveKeys, { workLines, shape });}return page;});+ setHistoryWorkPageReader((sid, onShape) => historyView.page(sid, undefined, true, { workLines: true, onShape }));ipcMain.handle('local-db:messages:view-intent', (event, sessionId: unknown, refs: unknown) => {if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);requireString(sessionId, 'sessionId');diff --git a/apps/desktop/src/renderer/__tests__/workGroupBlockLivePreview.test.tsx b/apps/desktop/src/renderer/__tests__/workGroupBlockLivePreview.test.tsxindex ddcc9a2d22..df8d5b58d4 100644--- a/apps/desktop/src/renderer/__tests__/workGroupBlockLivePreview.test.tsx+++ b/apps/desktop/src/renderer/__tests__/workGroupBlockLivePreview.test.tsx@@ -24,6 +24,8 @@ vi.mock('@/components/chat/AgentActionRow', () => ({status?: 'running' | 'done';toolResult?: string;intentOverride?: { action: string; target?: string };+ descriptorOverride?: { kind: string };+ onActivateOverride?: () => void;}) => {const toolInput = props.message.toolInput as { command?: unknown } | undefined;const command = typeof toolInput?.command === 'string'@@ -37,7 +39,9 @@ vi.mock('@/components/chat/AgentActionRow', () => ({'data-result': props.toolResult,'data-intent': props.intentOverride?.action,'data-target': props.intentOverride?.target,+ 'data-descriptor': props.descriptorOverride?.kind,'aria-label': `chat.agentActionRow.status.${props.status ?? 'done'}`,+ onClick: props.onActivateOverride,},command,);@@ -643,3 +647,36 @@ describe('WorkGroupBlock — running latest-five preview', () => {expect(screen.getAllByLabelText('chat.agentActionRow.status.running')).toHaveLength(1);});});++describe('WorkGroupBlock — Host-projected running lines', () => {+ const deferred = (lines?: import('@cindy/maker-shared/message-window').HistoryWorkLine[]) => ({+ owner: {}, key: 'work-remote', expanded: false, loading: false, failed: false,+ toggle: vi.fn(), retry: vi.fn(), setVisible: vi.fn(), ...(lines ? { lines } : {}),+ });+ const placeholder = thinking({ ...mkThinking('placeholder', ''), thinkingRedacted: true });++ it('renders Host lines without asking for the detail preview, and a line opens the group', () => {+ const remote = deferred([+ { kind: 'tool', key: 'c1', toolName: 'exec', status: 'done',+ descriptor: { kind: 'command', toolName: 'exec', command: 'pnpm test', intent: { action: 'test' } } },+ { kind: 'thinking', key: 'c2', text: 'Checking the failing case' },+ ]);+ const { container } = render(createElement(WorkGroupBlock, {+ blockId: 'work:remote', isStreaming: true, childItems: [placeholder], deferred: remote,+ }));+ expect(remote.setVisible).toHaveBeenLastCalledWith(false, false);+ expect(container.querySelector('[data-live-work-preview]')).not.toBeNull();+ expect(screen.getByTestId('direct-tool').getAttribute('data-descriptor')).toBe('command');+ expect(screen.getByText('Checking the failing case')).toBeTruthy();+ fireEvent.click(screen.getByTestId('direct-tool'));+ expect(remote.setVisible).toHaveBeenLastCalledWith(true, false);+ });++ it('keeps the detail preview for a Host that sends no lines', () => {+ const remote = deferred();+ render(createElement(WorkGroupBlock, {+ blockId: 'work:remote-old', isStreaming: true, childItems: [placeholder], deferred: remote,+ }));+ expect(remote.setVisible).toHaveBeenLastCalledWith(false, true);+ });+});diff --git a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsxindex 97b2e1165a..98e102a92e 100644--- a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx@@ -733,6 +733,13 @@ export interface AgentActionRowProps {* isSessionStreaming 计算后传入;缺省按已完成渲染(历史消息路径)。*/status?: 'running' | 'done';+ /**+ * Host-resolved descriptor of a remote single-line activity. Its input is not on this+ * device, so the row never re-describes a partial input.+ */+ descriptorOverride?: ToolUseDescriptor;+ /** Replaces the row's own details: a remote line opens its whole work group instead. */+ onActivateOverride?: () => void;}type LightboxState =@@ -769,6 +776,8 @@ export function AgentActionRow({showRawCommand = false,intentOverride,status = 'done',+ descriptorOverride,+ onActivateOverride,}: AgentActionRowProps) {const { t } = useTranslation();const compactedToolResult = parseToolResultCompactionMarker(toolResult);@@ -797,10 +806,11 @@ export function AgentActionRow({}, [toolName, inp, installedGhosts]);const descriptor = useMemo(() => {+ if (descriptorOverride) return descriptorOverride;const resolved = describeToolUse(toolName, inp);if (!intentOverride || resolved.kind !== 'command' || resolved.description) return resolved;return { ...resolved, intent: intentOverride };- }, [toolName, inp, intentOverride]);+ }, [toolName, inp, intentOverride, descriptorOverride]);const isFileChange = descriptor.kind === 'fileChange';// command 类带模型 description 时,description 自含动词语义("查看工作区// 状态"),再渲染英文动词 label 会变成"Ran 查看工作区状态"的中英混排 —@@ -921,6 +931,10 @@ export function AgentActionRow({* - Read → 文稿/图片 lightbox*/const onActivate = async (anchor: HTMLElement) => {+ if (onActivateOverride) {+ onActivateOverride();+ return;+ }const diffPayload = buildDiffPayload(descriptor, inp, asyncDiff ?? syncDiff);if (diffPayload) {triggerRef.current = anchor;@@ -1058,7 +1072,7 @@ export function AgentActionRow({onClick={(e) => void onActivate(e.currentTarget)}onContextMenu={onRowContextMenu}onKeyDown={onRowKeyDown}- aria-expanded={isInlineExpand ? expanded : undefined}+ aria-expanded={isInlineExpand && !onActivateOverride ? expanded : undefined}aria-label={ghostInfo? `${rowVerbLabel} ${ghostInfo.name} ${ghostInfo.tool}`diff --git a/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx b/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsxindex 2e9592cdb6..db4e0cf016 100644--- a/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx+++ b/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx@@ -207,6 +207,81 @@ function ThinkingActivityRow({ activity }: { activity: ProjectedThinkingActivity);}+type HistoryWorkLine = import('@cindy/maker-shared/message-window').HistoryWorkLine;++/** Remote running line: the Host already resolved the descriptor from the full input. */+function ToolLineRow({+ line,+ onActivate,+}: {+ line: Extract<HistoryWorkLine, { kind: 'tool' }>;+ onActivate: () => void;+}) {+ const message = useMemo<ChatMessage>(+ () => ({+ clientId: line.key,+ role: 'tool_use',+ content: '',+ toolName: line.toolName,+ toolInput: line.ghost ? { ghost_id: line.ghost.id, tool: line.ghost.tool } : null,+ }),+ [line.key, line.toolName, line.ghost],+ );+ return (+ <div data-live-work-activity="tool" className="w-full min-w-0">+ <AgentActionRow+ message={message}+ showRawCommand+ status={line.status}+ descriptorOverride={line.descriptor}+ onActivateOverride={onActivate}+ />+ </div>+ );+}++/** Remote running thought: only its opening is on this device; the full text opens with the group. */+function ThinkingLineRow({+ line,+ onActivate,+}: {+ line: Extract<HistoryWorkLine, { kind: 'thinking' }>;+ onActivate: () => void;+}) {+ return (+ <button+ type="button"+ data-live-work-activity="thinking"+ data-message-client-id={line.key}+ data-scroll-disclosure-header=""+ onClick={onActivate}+ className={cn(+ 'group flex w-full min-w-0 cursor-pointer select-none items-center gap-1.5 px-2 py-[3px] text-left outline-none',+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ ACTIVITY_ROW_RADIUS_CLASS,+ ACTIVITY_ROW_COLOR_TRANSITION_CLASS,+ ACTIVITY_ROW_HOVER_SURFACE_CLASS,+ )}+ >+ <span+ aria-hidden="true"+ className="inline-flex h-[18px] w-4 shrink-0 items-center justify-center text-[var(--msg-tool-card-chevron)]"+ >+ <Sparkles size={13} />+ </span>+ <span+ className="min-w-0 flex-1 truncate text-14 italic text-[var(--thinking-body-text)]"+ title={line.text}+ >+ <ThinkingText content={line.text} />+ </span>+ <span aria-hidden="true" className={ACTIVITY_ROW_CHEVRON_SLOT_CLASS}>+ <ChevronRight size={13} />+ </span>+ </button>+ );+}+/** 展开动作段里的 thinking:与 live preview 共用 ThinkingActivityRow,* 保证右侧三角槽同一套布局;redacted 仍走 ThinkingCard。 */function ExpandedThinkingRow({ message }: { message: ChatMessage }) {@@ -277,14 +352,18 @@ export function WorkGroupBlock({: (deferred?.expanded ?? rememberedExpanded);const deferredRef = useRef(deferred);deferredRef.current = deferred;+ // A Host that projects running lines makes the folded preview need no detail read.+ // Older Hosts omit them and keep the latest-five detail tail below.+ const workLines = !compact && isStreaming ? deferred?.lines : undefined;+ const lineMode = workLines !== undefined;// Register before paint. Switching back to a running task remounts this group;// a passive effect can lag 50–300ms behind the stream's mount, showing a// preview-less header until the cached tail reappears and the pinned list jumps.useLayoutEffect(() => {const current = deferredRef.current;- current?.setVisible?.(expanded, !compact && isStreaming);+ current?.setVisible?.(expanded, !compact && isStreaming && !lineMode);return () => current?.setVisible?.(false, false);- }, [deferred?.owner, deferred?.key, expanded, isStreaming, compact]);+ }, [deferred?.owner, deferred?.key, expanded, isStreaming, compact, lineMode]);const [elapsedMs, setElapsedMs] = useState(0);useEffect(() => {@@ -299,10 +378,10 @@ export function WorkGroupBlock({// 多取一条即可判断展开是否能露出更多活动,显示仍只取最近 5 条。const recentActivities = useMemo(() =>- !compact && isStreaming+ !compact && isStreaming && !lineMode? projectRecentWorkActivities(childItems, true, MAX_LIVE_WORK_ACTIVITIES + 1): [],- [childItems, isStreaming, compact],+ [childItems, isStreaming, compact, lineMode],);const liveActivities = useMemo(() => recentActivities.slice(-MAX_LIVE_WORK_ACTIVITIES),@@ -323,13 +402,15 @@ export function WorkGroupBlock({// 运行中预览已经等于全部内容时,折叠/展开是视觉空操作 — 组头不提供交互。const canToggle =compact ||+ lineMode ||(!!deferred && !deferred.previewComplete) ||!isStreaming ||hasBeyondPreviewChild ||recentActivities.length > MAX_LIVE_WORK_ACTIVITIES;const effectiveExpanded = expanded && canToggle;const isLivePreviewVisible =- !compact && isStreaming && !effectiveExpanded && liveActivities.length > 0;+ !compact && isStreaming && !effectiveExpanded+ && (workLines ? workLines.length > 0 : liveActivities.length > 0);// 完成态只计算一次完整摘要;运行态保持折叠时走上面的反向 latest-five// 热路径,用户主动展开后才投影全部历史。const activityProjection = useMemo(@@ -441,13 +522,21 @@ export function WorkGroupBlock({'flex flex-col',)}>- {liveActivities.map((activity) =>- activity.kind === 'tool' ? (- <ToolActivityRow key={activity.key} activity={activity} />- ) : (- <ThinkingActivityRow key={activity.key} activity={activity} />- ),- )}+ {workLines+ ? workLines.map((line) =>+ line.kind === 'tool' ? (+ <ToolLineRow key={line.key} line={line} onActivate={onToggle} />+ ) : (+ <ThinkingLineRow key={line.key} line={line} onActivate={onToggle} />+ ),+ )+ : liveActivities.map((activity) =>+ activity.kind === 'tool' ? (+ <ToolActivityRow key={activity.key} activity={activity} />+ ) : (+ <ThinkingActivityRow key={activity.key} activity={activity} />+ ),+ )}</div>)}diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 99a9f7ec4f..42a97e3887 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -35,7 +35,7 @@ import { parsePluginConnectionInput } from '@cindy/device-link';* - User-initiated stopSession (NOT called on session switch anymore)*/-import { HistoryViewController, isHistoryViewUnavailable, mapHistoryViewMessages, historyViewLeaves, historyWorkSummaries, type HistoryViewPage, type HistoryDetailPage } from '@cindy/maker-shared/message-window';+import { HISTORY_WORK_PATCH_CHANNEL, HistoryViewController, isHistoryViewUnavailable, mapHistoryViewMessages, historyViewLeaves, historyWorkSummaries, type HistoryViewPage, type HistoryDetailPage, type HistoryWorkPatch } from '@cindy/maker-shared/message-window';import type { CindyRegion } from '@cindy/maker-shared/brand-identity';import { SESSION_SYNC_CHANNEL } from '@cindy/device-link';import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from '@cindy/maker-shared/message-window';@@ -8992,7 +8992,8 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {if (inboundSid && isRemoteHeavyInboundChannel(push.channel)) _markInboundEvent(inboundSid);if (inboundSid) {const view = getRemoteHistoryView(inboundSid);- if (view && ['maker:history-view-changed', 'local-db:messages:created', 'maker:status-changed'].includes(push.channel)) view.invalidate();+ if (view && push.channel === HISTORY_WORK_PATCH_CHANNEL) view.applyWorkPatch(push.payload as HistoryWorkPatch);+ else if (view && ['maker:history-view-changed', 'local-db:messages:created', 'maker:status-changed'].includes(push.channel)) view.invalidate();}switch (push.channel) {case SESSION_SYNC_CHANNEL: {@@ -11546,7 +11547,8 @@ function createRemoteHistoryView(sessionId: string) {const view = new HistoryViewController<HistoryChatMessage>({page: async (before) => {const writer = deviceId ? remoteHistoryCacheWriter(deviceId, sessionId) : undefined;- const page = await call<HistoryViewPage<Message>>('local-db:messages:view', [sessionId, { before, lazyDetails: true }]);+ // Remote reads ask for Host-projected running lines; a local view already holds live rows.+ const page = await call<HistoryViewPage<Message>>('local-db:messages:view', [sessionId, { before, lazyDetails: true, ...(deviceId ? { workLines: true } : {}) }]);if (page == null) throw new Error('[CHANNEL_NOT_ALLOWED] History view is unavailable');writeCache = writer;return { ...page, items: mapHistoryViewMessages(page.items, mapRows) };diff --git a/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageActionDesktopFirst.test.tsindex 13f90a2d4c..b08739da5d 100644--- a/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts@@ -130,10 +130,15 @@ describe('mobile message actions desktop-first surface', () => {expect(workGroupSource).toContain('chevronSize={header.chevronSize}');expect(workGroupSource).toContain('title={title}');expect(workGroupSource).toContain('subtitle={header.subtitle ?? undefined}');- // Work group 受控展开;折叠态只保留卡头,不提前构造任何隐藏活动行。+ // Work group 受控展开;折叠态不提前构造任何隐藏活动行。运行中只渲染电脑端已投影好的+ // 单行活动(deferred.lines),既不读工作明细,也不在本机重新解析工具输入。expect(workGroupSource).not.toContain('defaultExpanded');expect(workGroupSource).toContain('controlledExpanded={expanded}');- expect(workGroupSource).not.toContain('collapsedBody=');+ expect(workGroupSource).toContain('const lines = isStreaming && !expanded ? item.deferred?.lines : undefined;');+ expect(workGroupSource).toContain('collapsedBody={lines?.length ? (');+ expect(workGroupSource).toContain('<WorkLineRow key={line.key} line={line} onPress={onToggle} />');+ expect(workGroupSource).toContain('formatToolRowText(line.descriptor, mobileToolRowWording)');+ expect(workGroupSource).not.toContain('summarizeToolUseText');expect(workGroupSource).toContain('onControlledToggle={onToggle}');expect(workGroupSource).not.toContain('live-preview-dismissed');expect(workGroupSource).toContain('? <CompactActivityIndicator color={colors.textTertiary}');diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 5fd71bd09b..3a843297b0 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -1,6 +1,6 @@import Constants from 'expo-constants';import { tryMobilePeerInvoke, resetMobilePeer } from './peerFileRegistry';-import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';+import { isHistoryViewUnavailable, type HistoryWorkPatch } from '@cindy/maker-shared/message-window';import { findRemoteHistoryView } from '@/session/remoteHistoryView';import { createBackgroundConnection } from './backgroundConnection';import { invokeWithHistoryViewCapability } from './historyViewCapability';@@ -1715,6 +1715,10 @@ export function routeFrame(env: Envelope, handlers: {historyView?.invalidate();return;}+ if (push.channel === 'maker:history-work-patch') {+ historyView?.applyWorkPatch(push.payload as HistoryWorkPatch);+ return;+ }remoteSessionStore.applyRemotePush(env.src, push.channel, push.payload);const patch = (push.payload as { patch?: { clearedAt?: unknown; status?: unknown } } | null)?.patch;if (historyView && push.channel === 'local-db:sessions:patched'diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex 419b8f74df..243d9fb7da 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -1137,7 +1137,8 @@ export function createMobileMakerTransport({listMessages: (sessionId, opts) =>call("local-db:messages:list", [sessionId, opts]),readHistoryView: (sessionId, before) =>- call("local-db:messages:view", [sessionId, { before, lazyDetails: true }]),+ // workLines: the Host projects running single-line activities and may send work patches.+ call("local-db:messages:view", [sessionId, { before, lazyDetails: true, workLines: 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.tsxindex 14f69a5802..715f46fe3a 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -316,6 +316,7 @@ import {} from '@cindy/maker-shared/agent-task';import {buildMessageActionBarPresentation,+ formatToolRowText,summarizeMessageBubblePresentation,summarizeTodoCardPresentation,summarizeToolGroupPresentation,@@ -417,6 +418,7 @@ import { i18n } from '@/i18n';import { formatLocalizedDuration } from '@/session/sessionDurationFormat';import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';import { mobileToolRowWording } from '@/i18n/toolWording';+import type { HistoryWorkLine } from '@cindy/maker-shared/message-window';const MESSAGE_CONTROL_HIT_SLOP = { bottom: 10, left: 10, right: 10, top: 10 };const MESSAGE_CONTROL_TOUCH_SIZE = 44;@@ -4727,6 +4729,9 @@ function WorkGroupCard({].filter(Boolean).join(' · ');const onToggle = item.deferred?.setVisible ? toggleExpanded : item.deferred?.toggle ?? toggleExpanded;const pluginWork = actions.companionPluginWork?.get(item.key);+ // The Host projects running lines for this view; folded groups render them as they are,+ // without building the hidden activity tree or reading any work details.+ const lines = isStreaming && !expanded ? item.deferred?.lines : undefined;return (<>{pluginWork ? <PluginInvocationHeader plugins={pluginWork.plugins} running={pluginWork.running}@@ -4736,6 +4741,13 @@ function WorkGroupCard({chevronPosition={header.chevronPosition}chevronSize={header.chevronSize}controlledExpanded={expanded}+ collapsedBody={lines?.length ? (+ <Rail layout={layout}>+ <View style={styles.workActivityStack}>+ {lines.map((line) => <WorkLineRow key={line.key} line={line} onPress={onToggle} />)}+ </View>+ </Rail>+ ) : undefined}onControlledToggle={onToggle}title={title}subtitle={header.subtitle ?? undefined}@@ -4792,6 +4804,48 @@ function WorkGroupCard({);}+/** One Host-projected running line; pressing it opens the whole work group. */+const WorkLineRow = memo(function WorkLineRow({+ line,+ onPress,+}: {+ line: HistoryWorkLine;+ onPress: () => void;+}) {+ const { colors } = useTheme();+ const { i18n } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const label = useMemo(+ () => (line.kind === 'tool' ? formatToolRowText(line.descriptor, mobileToolRowWording).label || line.toolName : line.text),+ [i18n.language, line],+ );+ return (+ <Pressable+ accessibilityLabel={label}+ accessibilityRole="button"+ onPress={onPress}+ style={({ pressed }) => [line.kind === 'tool' ? styles.toolRowHeader : styles.workThinkingRow, pressed && styles.pressed]}+ testID="message.workLine"+ >+ {line.kind === 'tool' ? (+ <>+ <ToolRowStatusIcon hasError={line.hasError === true} status={line.status} />+ <Text numberOfLines={1} style={[styles.toolName, styles.toolNameFlex]}>{label}</Text>+ </>+ ) : (+ <>+ <View style={stylesStatic.workActivityIconSlot}>+ <Sparkles color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />+ </View>+ <Text numberOfLines={1} style={[styles.workActivityText, styles.italicText, styles.workThinkingText]}>+ <ThinkingInlineText content={label} />+ </Text>+ </>+ )}+ </Pressable>+ );+});+/** The clock must not re-render an expanded group's entire activity tree. */function WorkGroupElapsed({ sinceIso }: { sinceIso: string | undefined }) {const styles = useThemedStyles(makeStyles);@@ -4970,6 +5024,7 @@ function FoldablePanel({title,subtitle,children,+ collapsedBody,controlledExpanded,defaultExpanded = false,layout,@@ -4991,6 +5046,8 @@ function FoldablePanel({title: string;subtitle?: string;children: ReactNode;+ /** Running work lines shown under a folded header; the full body is still built only when expanded. */+ collapsedBody?: ReactNode;/** Controlled mode used by work groups. */controlledExpanded?: boolean;/** 仅无 blockId 的本地 state 路径生效;blockId 存在时由共享记忆决定(默认折叠)。 */@@ -5074,6 +5131,18 @@ function FoldablePanel({]}>{children}</View>+ ) : collapsedBody ? (+ <View style={[+ styles.foldBody,+ variant === 'plain'+ ? styles.foldBodyPlain+ : {+ paddingBottom: layout.foldBodyPaddingBottom,+ paddingHorizontal: layout.foldBodyPaddingHorizontal,+ },+ ]}>+ {collapsedBody}+ </View>) : null}</View>);diff --git a/apps/mobile/src/session/messagePresentation.ts b/apps/mobile/src/session/messagePresentation.tsindex 4ee885ca9f..cb501b76b4 100644--- a/apps/mobile/src/session/messagePresentation.ts+++ b/apps/mobile/src/session/messagePresentation.ts@@ -6,6 +6,7 @@ import {import {buildMessageActionBarPresentation,countMessageRenderItemDiffs,+ formatToolRowText,isToolErrorLike,summarizeMessageBubblePresentation,summarizeTodoCardPresentation,@@ -33,6 +34,7 @@ import {export {buildMessageActionBarPresentation,+ formatToolRowText,isToolErrorLike,summarizeMessageBubblePresentation,summarizeTodoCardPresentation,diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex bac616dc80..ee9b4852bc 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -405,6 +405,25 @@ Mobile 的「仅查看」改为纯本地开关:只停止转发输入、关闭raw history 降级。任务列表活动推送不变,当前轮的正文、工具卡和可见进度继续实时更新。没有新增 channel、relay 类型、数据库 schema 或 Mobile 原生依赖,云端无需改动。+### 运行中工作组的单行活动与就地更新++同账号控制端读取最新一页时可再带 `{ workLines: true }`。被控 Desktop 只为顶层、无嵌套、+运行中的工作组摘要附加可选 `lines`:最多 5 行,用与两端相同的共享投影(Codex 拆行、+重复读取去重)从完整记录算出,每行只含工具名、按完整输入解析后再截短的展示描述、状态、+是否失败,或思考开头的单行文字;不含工具结果、diff 与完整输入,整窗有 UTF-8 字节上限。+控制端据此显示运行中的最近 5 行,不再为预览读取 `work-details`。++声明过 `workLines` 的控制端,折叠工作组的活动通知改为新推送 `maker:history-work-patch`+`{ version: 1, sessionId, baseRevision, item }`:仅当它上次收到的最新一页里,除这一个运行中+条目外的所有条目指纹都未变(指纹在库级写入计数后缀之前计算)时才发送,`baseRevision`+是该条目上次送达的修订号。控制端只在条目存在、修订号与范围起点一致、且没有读取进行中时+原地替换,其余情况退回原有的页面刷新;新分组、正文、卡片、清空或回退都继续走+`maker:history-view-changed`。思考增量只在单行文字还会变化时触发通知。++旧控制端不带参数,收不到 `lines` 与新推送;旧主机忽略参数:新 Mobile 只显示卡头(与此前相同),+新 Desktop 继续用原有 5 条明细预览。共享任务访客与供应商分享不启用这两项,读取与授权路径不变。+没有新增 relay 类型、数据库 schema、权限或 Mobile 原生依赖,云端无需改动。+现有 `maker:list-active` 的可选 `{ summary: true }` 响应在运行标记之外增加`activityPhase` / `activityAttention` 两个可选字段。被控端从现有会话活动投影提供这两个状态字段;活动服务已就绪但该会话不在活动账本中时,明确返回 `idle` / `false`,不下发活动正文。diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex e001689595..d41e8828e8 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -680,6 +680,8 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([// maker-ipc MAKER_PUSH'maker:event','maker:history-view-changed',+ // Running work item replacement for controllers whose latest view read asked for work lines.+ 'maker:history-work-patch',// Device-level runtime Agent roster changes; controllers refresh their local availability cache.'maker:agents:changed',// Host-owned resource provider 的通用失效通知;payload 只含 collection/ref/revision。diff --git a/packages/maker-shared/src/__tests__/historyWorkLines.test.ts b/packages/maker-shared/src/__tests__/historyWorkLines.test.tsnew file mode 100644index 0000000000..f2c2c5f6e3--- /dev/null+++ b/packages/maker-shared/src/__tests__/historyWorkLines.test.ts@@ -0,0 +1,162 @@+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';++let n = 0;+function row(role: string, content: unknown, extra: Partial<HistoryMessageSource> = {}): HistoryMessageSource {+ n += 1;+ return { id: `m${n}`, clientId: `c${n}`, role, content, createdAt: new Date(1_700_000_000_000 + n).toISOString(), ...extra };+}+function tool(name: string, input: unknown, extra: Partial<HistoryMessageSource> = {}) {+ const use = row('tool_use', { toolName: name, toolUseId: `t${n + 1}`, input }, extra);+ return use;+}+function result(use: HistoryMessageSource, content: string) {+ return row('tool_result', content, { toolUseId: (use.content as { toolUseId: string }).toolUseId });+}++describe('projectHistoryWorkLines', () => {+ it('uses the shared latest-five projection: Codex split actions and repeated reads', () => {+ const codex = tool('exec', {+ command: 'cat a.ts && rg needle && ls src',+ cwd: '/repo',+ commandActions: [+ { type: 'read', command: 'cat a.ts', name: 'a.ts', path: 'a.ts' },+ { type: 'search', command: 'rg needle', query: 'needle' },+ { type: 'listFiles', command: 'ls src', path: 'src' },+ ],+ });+ const readA = tool('Read', { file_path: '/repo/a.ts' });+ const readAAgain = tool('Read', { file_path: '/repo/a.ts' });+ const lines = projectHistoryWorkLines([codex, result(codex, 'ok'), readA, result(readA, 'x'), readAAgain], true);+ // `cat a.ts` in /repo and both later reads open the same file: only the newest read stays.+ expect(lines.map((line) => line.key)).toEqual([+ `${codex.clientId}:action:1`, `${codex.clientId}:action:2`, readAAgain.clientId,+ ]);+ expect(lines.at(-1)).toMatchObject({ kind: 'tool', status: 'running' });+ expect(lines[0]).toMatchObject({ kind: 'tool', status: 'done', descriptor: { intent: { action: 'search' } } });+ });++ it('keeps child-agent rows inside their own card', () => {+ const parent = tool('Task', { description: 'investigate' });+ const child = tool('Read', { file_path: '/repo/child.ts' }, { agentMeta: { parentUuid: 'task-1' } });+ const lines = projectHistoryWorkLines([parent, child], true);+ expect(lines.map((line) => line.key)).toEqual([parent.clientId]);+ });++ it('marks failed results with the row failure rules and never ships results or diffs', () => {+ const failing = tool('Bash', { command: 'pnpm build' });+ const edit = tool('apply_patch', { changes: [{ path: 'a.ts', kind: 'update', diff: '+'.repeat(5000) }] });+ const lines = projectHistoryWorkLines([failing, result(failing, 'Error: exit code 2'), edit], true);+ expect(lines[0]).toMatchObject({ kind: 'tool', hasError: true });+ expect(JSON.stringify(lines)).not.toContain('+++++');+ expect(JSON.stringify(lines)).not.toContain('exit code 2');+ });++ it('collapses and caps a thought, and drops older lines before exceeding the window budget', () => {+ const thought = row('thinking', `first\n\n second ${'word '.repeat(100)}`);+ const [line] = projectHistoryWorkLines([thought], true);+ expect(line).toMatchObject({ kind: 'thinking', truncated: true });+ 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(Buffer.byteLength(JSON.stringify(lines), 'utf8')).toBeLessThanOrEqual(HISTORY_WORK_LINES_MAX_BYTES);+ });+});++function summary(key: string, revision: string, lines?: HistoryWorkSummary['lines']): HistoryWorkSummary {+ return {+ key, firstMessageId: 'm-first', lastMessageId: 'm-last', startedAtMs: 1, endedAtMs: 2,+ isStreaming: true, messageCount: 2, toolCount: 1, revision, ...(lines ? { lines } : {}),+ };+}+const answer = { type: 'messages' as const, key: 'c0', messages: [row('user', 'go')] };+function page(items: HistoryViewPage<HistoryMessageSource>['items']): HistoryViewPage<HistoryMessageSource> {+ return { version: 1, items, hasMore: false, nextCursor: null };+}+function patch(baseRevision: string, revision: string): HistoryWorkPatch {+ return { version: 1, sessionId: 's', baseRevision,+ item: { type: 'work', key: 'work-c1', summary: summary('work-c1', revision, [{ kind: 'thinking', key: 'c9', text: 'next' }]) } };+}++describe('HistoryViewController.applyWorkPatch', () => {+ afterEach(() => vi.useRealTimers());++ async function fixture() {+ const transport = {+ page: vi.fn(async () => page([answer, { type: 'work', key: 'work-c1', summary: summary('work-c1', 'r1', []) }])),+ details: vi.fn(async () => ({ version: 1 as const, messages: [], hasMore: false, nextCursor: null })),+ expanded: vi.fn(async () => undefined),+ };+ const view = new HistoryViewController(transport);+ await view.refresh();+ return { view, transport };+ }++ it('replaces the running item in place without reading the page or any details', async () => {+ const { view, transport } = await fixture();+ const before = view.getSnapshot().items;+ view.applyWorkPatch(patch('r1', 'r2'));+ const items = view.getSnapshot().items;+ expect(items[0]).toBe(before[0]);+ expect(items[1]).toMatchObject({ summary: { revision: 'r2', lines: [{ text: 'next' }] } });+ expect(transport.page).toHaveBeenCalledTimes(1);+ expect(transport.details).not.toHaveBeenCalled();+ });++ it('still reloads an expanded running group, exactly like a page read would', async () => {+ const { view, transport } = await fixture();+ view.setExpanded('work-c1', true);+ await vi.waitFor(() => expect(transport.details).toHaveBeenCalledTimes(1));+ view.applyWorkPatch(patch('r1', 'r2'));+ await vi.waitFor(() => expect(transport.details).toHaveBeenCalledTimes(2));+ });++ it.each([+ ['another base revision', () => patch('stale', 'r2')],+ ['an unknown item', () => ({ ...patch('r1', 'r2'), item: { ...patch('r1', 'r2').item, key: 'work-other' } })],+ ['a different range start', () => {+ const value = patch('r1', 'r2');+ return { ...value, item: { ...value.item, summary: { ...value.item.summary, firstMessageId: 'm-elsewhere' } } };+ }],+ ])('falls back to the page refresh for %s', async (_label, build) => {+ const { view, transport } = await fixture();+ vi.useFakeTimers();+ view.applyWorkPatch(build());+ expect(view.getSnapshot().items[1]).toMatchObject({ summary: { revision: 'r1' } });+ await vi.advanceTimersByTimeAsync(600);+ expect(transport.page).toHaveBeenCalledTimes(2);+ });++ it('never applies over a page read in flight', async () => {+ const { view, transport } = await fixture();+ let finish!: (value: HistoryViewPage<HistoryMessageSource>) => void;+ transport.page.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const reading = view.refresh(false, true);+ view.applyWorkPatch(patch('r1', 'r2'));+ expect(view.getSnapshot().items[1]).toMatchObject({ summary: { revision: 'r1' } });+ finish(page([answer, { type: 'work', key: 'work-c1', summary: summary('work-c1', 'r3', []) }]));+ await reading;+ expect(view.getSnapshot().items[1]).toMatchObject({ summary: { revision: 'r3' } });+ });++ it('hands the Host lines to the renderer through the deferred binding', async () => {+ const { view } = await fixture();+ view.applyWorkPatch(patch('r1', 'r2'));+ type Item = { key: string; ids: string[]; children?: Item[]; deferred?: { lines?: unknown } };+ const items = renderHistoryView<HistoryMessageSource, Item>({+ view, snapshot: view.getSnapshot(), liveMessages: [], streaming: true,+ build: (rows) => [{ key: 'work', ids: [], children: rows.map((r) => ({ key: r.clientId, ids: [r.clientId] })) }],+ structure: {+ placeholder: (value) => row('thinking', '', { clientId: `placeholder-${value.key}` }),+ children: (item) => item.children,+ sourceIds: (item) => item.ids,+ rebuild: (item, children, deferred) => ({ ...item, children, deferred }),+ },+ });+ expect(items[0].deferred?.lines).toEqual([{ kind: 'thinking', key: 'c9', text: 'next' }]);+ });+});diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.tsindex 8ee34a21ea..b7e485a0f7 100644--- a/packages/maker-shared/src/historyView.ts+++ b/packages/maker-shared/src/historyView.ts@@ -1,3 +1,5 @@+import type { HistoryWorkLine } from './historyWorkLines.js';+/** Reading projections never replace persisted messages or the agent transcript. */export const HISTORY_VIEW_VERSION = 1 as const;export const HISTORY_VIEW_PAGE_ITEMS = 20;@@ -53,6 +55,11 @@ export interface HistoryWorkSummary extends HistoryWorkReference {model?: string;/** Existing detail endpoint can read just the visible desktop tail. */preview?: HistoryWorkSummary;+ /**+ * Latest single-line activities of a running range, already projected by the Host.+ * Present only when the controller asked for `workLines`; old Hosts omit it.+ */+ lines?: HistoryWorkLine[];startedAtMs: number;endedAtMs: number;isStreaming: boolean;@@ -69,6 +76,8 @@ export interface DeferredHistoryWork {revision?: string;setVisible?(expanded: boolean, preview: boolean): void;previewComplete?: boolean;+ /** Host-projected running lines; when present a folded preview needs no detail read. */+ lines?: readonly HistoryWorkLine[];expanded: boolean;loading: boolean;failed: boolean;@@ -105,6 +114,20 @@ export interface HistoryViewPage<TMessage extends HistoryMessageSource> {hasMore: boolean;}+/**+ * Host → controller replacement of one running top-level work item. The Host sends it+ * only when everything else on the latest page is unchanged since its last delivery to+ * that controller; `baseRevision` is the item revision that delivery carried.+ */+export interface HistoryWorkPatch {+ version: typeof HISTORY_VIEW_VERSION;+ sessionId: string;+ baseRevision: string;+ item: { type: 'work'; key: string; summary: HistoryWorkSummary };+}++export const HISTORY_WORK_PATCH_CHANNEL = 'maker:history-work-patch';+export interface HistoryDetailPage<TMessage extends HistoryMessageSource> {version: typeof HISTORY_VIEW_VERSION;messages: TMessage[];diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.tsindex beff22dd42..9ca2456395 100644--- a/packages/maker-shared/src/historyViewController.ts+++ b/packages/maker-shared/src/historyViewController.ts@@ -1,6 +1,6 @@import {readHistoryWorkDetails, isHistoryViewUnavailable, historyWorkSummaries, historyViewLeaves, type HistoryDetailPage, type HistoryMessageSource,- type HistoryViewItem, type HistoryViewPage, type HistoryWorkSummary,+ type HistoryViewItem, type HistoryViewPage, type HistoryWorkPatch, type HistoryWorkSummary,} from './historyView.js';export interface HistoryWorkDetailState<T extends HistoryMessageSource> {@@ -125,6 +125,29 @@ export class HistoryViewController<T extends HistoryMessageSource> {}, 500);}+ /**+ * Replace one running top-level work item in place. Anything this controller cannot+ * prove to be the Host's base (a read in flight, a missing or reshaped item, another+ * revision) falls back to the ordinary page refresh the notice used to trigger.+ */+ applyWorkPatch(patch: HistoryWorkPatch): void {+ if (!this.isActive()) return;+ const index = this.state.items.findIndex((item) => item.key === patch.item.key);+ const current = this.state.items[index];+ if (this.pagePromise || this.refreshTimer || !this.state.ready || !current || current.type !== 'work' || current.children+ || current.summary.revision !== patch.baseRevision+ || current.summary.firstMessageId !== patch.item.summary.firstMessageId) {+ this.invalidate();+ return;+ }+ const items = [...this.state.items];+ items[index] = patch.item;+ this.publish({ items });+ for (const summary of historyWorkSummaries([patch.item])) {+ if (this.state.expanded.has(summary.key)) void this.loadDetails(summary);+ }+ }+private async readPage(older: boolean): Promise<void> {if (!this.isActive() || this.state.loading || (older && !this.state.hasMore)) return;const generation = this.generation;diff --git a/packages/maker-shared/src/historyViewRender.ts b/packages/maker-shared/src/historyViewRender.tsindex e79084f00c..3519d6f573 100644--- a/packages/maker-shared/src/historyViewRender.ts+++ b/packages/maker-shared/src/historyViewRender.ts@@ -154,10 +154,12 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(optionsif (summary.preview) view.setExpanded(summary.preview.key, !full && preview);}};+ const lines = [...summaries].reverse().find((summary) => summary.lines)?.lines;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),+ ...(lines ? { lines } : {}),loading: states.some((state) => state?.loading), failed: states.some((state) => !!state?.error),setVisible,toggle: () => setVisible(!expanded, false),diff --git a/packages/maker-shared/src/historyWorkLines.ts b/packages/maker-shared/src/historyWorkLines.tsnew file mode 100644index 0000000000..679bcb5dda--- /dev/null+++ b/packages/maker-shared/src/historyWorkLines.ts@@ -0,0 +1,162 @@+/**+ * Single-line work activities for a running remote work group.+ *+ * The Host projects them from the complete rows with the same latest-N projection+ * every client already uses (Codex command splitting, repeated-read de-duplication),+ * then sends only display facts. Clients localize the descriptor themselves and never+ * re-describe a truncated input, so a cut command cannot change its recognized intent.+ */++import type { HistoryMessageSource } from './historyView.js';+import { isToolResultFailureLike } from './messagePresentation.js';+import { messageContentToPreview, parseMessageToolUse } from './messageNormalize.js';+import { describeToolUse, type ToolUseDescriptor } from './toolUseDescriptor.js';+import {+ projectRecentWorkActivities,+ type ProjectableWorkChild,+ type WorkActivityMessageLike,+} from './workActivityProjection.js';++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;++export type HistoryWorkLine =+ | {+ kind: 'tool';+ key: string;+ toolName: string;+ /** Resolved from the full input (intent override applied); long text cut afterwards. */+ descriptor: ToolUseDescriptor;+ status: 'running' | 'done';+ hasError?: true;+ /** ghost_call identity, the only input fields a row header reads besides the descriptor. */+ ghost?: { id: string; tool: string };+ }+ | {+ kind: 'thinking';+ key: string;+ /** Whitespace-collapsed opening of the thought. */+ text: string;+ truncated?: true;+ };++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);+ 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);+ }+ return result;+}++function utf8Length(text: string): number {+ let bytes = 0;+ for (let index = 0; index < text.length; index += 1) {+ const code = text.charCodeAt(index);+ if (code < 0x80) bytes += 1;+ else if (code < 0x800) bytes += 2;+ else if (code >= 0xd800 && code <= 0xdbff && index + 1 < text.length) {+ bytes += 4;+ index += 1;+ } else bytes += 3;+ }+ return bytes;+}++interface LineSource extends WorkActivityMessageLike {+ toolInput?: unknown;+}++function thinkingText(content: unknown): { text: string; redacted: boolean } {+ if (typeof content === 'string') return { text: content, redacted: false };+ const thought = content as { text?: unknown; isRedacted?: unknown } | null;+ return {+ text: typeof thought?.text === 'string' ? thought.text : '',+ redacted: thought?.isRedacted === true,+ };+}++/**+ * Project the latest lines from the rows of one running work range. Rows belonging to+ * a child agent stay inside that agent's own card and never become main-timeline lines.+ */+export function projectHistoryWorkLines(+ rows: readonly HistoryMessageSource[],+ isStreaming: boolean,+ limit = HISTORY_WORK_LINE_LIMIT,+): HistoryWorkLine[] {+ const children: ProjectableWorkChild<LineSource>[] = [];+ const toolClientIds = new Map<string, string>();+ const results = new Map<string, string>();+ const inputs = new Map<string, unknown>();+ let tools: ProjectableWorkChild<LineSource> | null = null;+ for (const row of rows) {+ if ((row.agentMeta as { parentUuid?: unknown } | null | undefined)?.parentUuid) continue;+ if (row.role === 'tool_use') {+ const tool = parseMessageToolUse(row);+ if (tool.toolUseId) toolClientIds.set(tool.toolUseId, row.clientId);+ inputs.set(row.clientId, tool.input);+ if (!tools) {+ tools = { kind: 'tools', key: row.clientId, toolCalls: [], resultMap: results };+ children.push(tools);+ }+ tools.toolCalls!.push({ clientId: row.clientId, content: '', toolName: tool.toolName, toolInput: tool.input });+ continue;+ }+ if (row.role === 'tool_result') {+ const owner = row.toolUseId ? toolClientIds.get(row.toolUseId) : undefined;+ if (owner) results.set(owner, messageContentToPreview(row.content));+ continue;+ }+ if (row.role === 'thinking') {+ const thought = thinkingText(row.content);+ tools = null;+ children.push({+ kind: 'thinking',+ key: row.clientId,+ message: { clientId: row.clientId, content: thought.text, thinkingRedacted: thought.redacted },+ });+ }+ }++ const lines = projectRecentWorkActivities(children, isStreaming, limit).map((activity): HistoryWorkLine => {+ if (activity.kind === 'thinking') {+ const text = cut(activity.content, HISTORY_WORK_LINE_TEXT_CHARS);+ return { kind: 'thinking', key: activity.key, text, ...(text !== activity.content ? { truncated: true as const } : {}) };+ }+ const toolName = activity.message.toolName ?? '';+ const input = inputs.get(activity.message.clientId);+ const resolved = describeToolUse(toolName, input);+ const descriptor = activity.intentOverride && resolved.kind === 'command' && !resolved.description+ ? { ...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;+ return {+ kind: 'tool',+ key: activity.key,+ toolName: cut(toolName, DESCRIPTOR_TEXT_CHARS),+ descriptor: liteDescriptor(descriptor) as ToolUseDescriptor,+ status: activity.status,+ ...(activity.toolResult !== undefined && isToolResultFailureLike(descriptor, activity.toolResult) ? { hasError: true as const } : {}),+ ...(ghost ? { ghost } : {}),+ };+ });+ // 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();+ return lines;+}diff --git a/packages/maker-shared/src/messagePresentation.ts b/packages/maker-shared/src/messagePresentation.tsindex 06ed3bd3ad..ce7fa302ad 100644--- a/packages/maker-shared/src/messagePresentation.ts+++ b/packages/maker-shared/src/messagePresentation.ts@@ -673,6 +673,12 @@ export function isToolErrorLike(.test(text);}+/** Same failure decision as a tool row, for a Host that only holds the descriptor and result text. */+export function isToolResultFailureLike(descriptor: ToolUseDescriptor, result: string): boolean {+ const tool = { body: '', secondaryBody: result };+ return isContentOutputDescriptor(descriptor) ? isContentToolFailureLike(tool) : isToolErrorLike(tool);+}+/** 结果正文是「内容」的工具(读文件 / 搜索 / 网页):对其输出跑全文错误关键词匹配没有意义。 */function isContentOutputDescriptor(descriptor: ToolUseDescriptor): boolean {if (descriptor.kind === 'file') return descriptor.action === 'read';diff --git a/packages/maker-shared/src/messageWindow.ts b/packages/maker-shared/src/messageWindow.tsindex f5906ea06e..30f985d4f2 100644--- a/packages/maker-shared/src/messageWindow.ts+++ b/packages/maker-shared/src/messageWindow.ts@@ -1,5 +1,6 @@export { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from './remoteTextStream.js';export * from './historyView.js';+export * from './historyWorkLines.js';export { projectHistoryView, historySubagentScopes, isHistoryDetailTool, hasVisibleHistoryResult } from './historyViewProjection.js';export * from './historyViewController.js';export { renderHistoryView } from './historyViewRender.js';