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): 按可见内容分页并按需读取工作详情
Dashedbd2e267e69
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex cf04b22977..2b89d0b6e0 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -86,6 +86,7 @@ import {onInteractionMessage,onInteractionResolved,onThinkingEvent,+ getSessionThinkingSnapshots,flushAssistantBlock,sealAssistantBlockForLateFinal,flushOrphanToolResults,@@ -1683,6 +1684,19 @@ describe('done orphan:残留 buffer 在 turn 末 flush', () => {});describe('thinking persistence', () => {+ it('recovers thinking accumulated while folded, then rejects it after an owner change', () => {+ onThinkingEvent(SESSION, { stage: 'start', blockId: 'live-thought' }, null);+ onThinkingEvent(SESSION, { stage: 'delta', blockId: 'live-thought', text: 'first ' }, null);+ onThinkingEvent(SESSION, { stage: 'delta', blockId: 'live-thought', text: 'second' }, null);+ expect(getSessionThinkingSnapshots(SESSION)).toEqual([expect.objectContaining({+ clientId: 'live-thought', content: expect.objectContaining({ text: 'first second' }),+ })]);+ ownerScopeState.current = false;+ expect(getSessionThinkingSnapshots(SESSION)).toEqual([]);+ ownerScopeState.current = true;+ expect(getSessionThinkingSnapshots(SESSION)).toEqual([]);+ });+it('uses the final event timestamp instead of delayed write time', async () => {const finishedAt = Date.parse('2026-06-20T09:10:00.000Z');const delayedWriteTime = Date.parse('2026-06-20T09:10:04.000Z');diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 09181ee967..680ab44c9e 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -22,6 +22,7 @@ import {type WebContents,} from 'electron';import { resolveVibrancyConfig } from './vibrancyConfig';+import { getSessionThinkingSnapshots, getHistoryToolName } from './messagePersistBroadcaster';import { applyVibrancyToSecondaryWindows } from './secondary-windows';import {rememberResolvedAppTheme,@@ -480,6 +481,7 @@ import {import {getUpdateRelaunchControllers,hasInFlightRemoteInvokes,+ setHistoryToolNameReader,pushSessionActivityToController,setSessionsSubscribedListener,} from './device-link/dispatch';@@ -8247,7 +8249,10 @@ app.on('ready', async () => {// 首登轻量数据迁移(mToc)的确认弹窗 IPC —— 必须先于 registerLocalDbIpc 注册,// 保证 beforeEnsureReady 推送 confirm 态时 renderer 已能 invoke 确认通道。registerLegacyMigrationIpc();+ setHistoryToolNameReader(getHistoryToolName);registerLocalDbIpc({+ isSessionTurnPendingCompletion,+ readHistoryLiveMessages: getSessionThinkingSnapshots,resolveContextWindow: (session) => resolveSessionContextWindow(getActiveCatalog(), session),requestWorktreeRecycle,cancelSessionOperations: cancelIOSSimulatorSessionOperations,diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.tsindex 0654a72309..79dd8558a1 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts@@ -120,6 +120,34 @@ describe('negotiated mobile tool projection', () => {});});+describe('history detail interest', () => {+ it('sends full thinking only to expanded/legacy peers and coalesces folded summaries', async () => {+ vi.useFakeTimers();+ try {+ const client = mkClient();+ __testing.setActiveClient(client as never);+ for (const peer of ['folded', 'expanded', 'legacy']) subscriptions.subscribe(peer, ['session:s1']);+ for (const peer of ['folded', 'expanded']) subscriptions.updateHistoryView(peer, 's1', 'work');+ subscriptions.setHistoryExpanded('expanded', 's1', ['work']);+ const push = (stage: string) => ({ sessionId: 's1', event: { type: 'thinking', data: { stage, blockId: 'b', text: 'private detail' } } });+ __testing.forwardPush('maker:event', push('start'));+ for (let n = 0; n < 100; n++) __testing.forwardPush('maker:event', push('delta'));+ expect(client.sendPush.mock.calls.filter((call) => call[0] === 'folded')).toHaveLength(0);+ expect(client.sendPush.mock.calls.filter((call) => call[0] === 'expanded' && call[1] === 'maker:event')).toHaveLength(101);+ expect(client.sendPush.mock.calls.filter((call) => call[0] === 'legacy')).toHaveLength(101);+ await vi.advanceTimersByTimeAsync(500);+ const folded = client.sendPush.mock.calls.filter((call) => call[0] === 'folded');+ expect(folded).toEqual([['folded', 'maker:history-view-changed', { sessionId: 's1' }]]);+ for (let n = 0; n < 100; n++) __testing.forwardPush('maker:event', push('delta'));+ await vi.advanceTimersByTimeAsync(500);+ expect(client.sendPush.mock.calls.filter((call) => call[0] === 'folded')).toHaveLength(1);+ } finally {+ __testing.reset();+ vi.useRealTimers();+ }+ });+});+describe('[14] sendInvokeResultSafe — 结果超限兜底', () => {it('消息页首发抛 PAYLOAD_TOO_LARGE → 先压缩超大消息内容并重发 ok:true,不冒泡', () => {const sendInvokeResult = vi.fn().mockImplementationOnce(() => {diff --git a/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts b/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.tsnew file mode 100644index 0000000000..2dcd0ca495--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts@@ -0,0 +1,31 @@+import { afterEach, describe, expect, it } from 'vitest';+import { isDeferredHistoryPush, deferredToolBoundary } from '../historyViewPush';+import * as subscriptions from '../subscriptions';+afterEach(() => subscriptions.__testing.reset());+describe('per-controller deferred history', () => {+ it('separates collapsed, expanded and legacy peers and refuses late intent after unsubscribe', () => {+ for (const peer of ['closed', 'open', 'old']) subscriptions.subscribe(peer, ['session:s']);+ for (const peer of ['closed', 'open']) subscriptions.updateHistoryView(peer, 's', 'w');+ subscriptions.setHistoryExpanded('open', 's', ['w']);+ expect(subscriptions.projectsHistoryDetails('closed', 's')).toBe(true);+ expect(subscriptions.projectsHistoryDetails('open', 's')).toBe(false);+ expect(subscriptions.projectsHistoryDetails('old', 's')).toBe(false);+ subscriptions.unsubscribe('closed', ['session:s']);+ subscriptions.updateHistoryView('closed', 's', 'w');+ subscriptions.setHistoryExpanded('closed', 's', ['w']);+ expect(subscriptions.hasHistoryView('closed', 's')).toBe(false);+ });+ it('defers thinking/tool bodies but retains prose, interactions, errors and artifacts', () => {+ const push = (type: string, data: unknown) => ({ sessionId: 's', event: { type, data } });+ const names = () => 'Read';+ expect(isDeferredHistoryPush('maker:event', push('thinking', { stage: 'delta', text: 'large' }), names)).toBe(true);+ expect(isDeferredHistoryPush('maker:event', push('text', { text: 'answer' }), names)).toBe(false);+ expect(isDeferredHistoryPush('maker:event', push('tool_use', { toolName: 'AskUserQuestion' }), names)).toBe(false);+ expect(isDeferredHistoryPush('maker:event', push('tool_result_full', { toolUseId: 't', fullText: 'error', isError: true }), names)).toBe(false);+ expect(isDeferredHistoryPush('maker:event', push('tool_result_full', { toolUseId: 't', fullText: 'cindy-media://result.png' }), names)).toBe(false);+ const start = push('tool_use', { toolUseId: 't', toolName: 'Read', input: 'x'.repeat(100000) });+ expect(isDeferredHistoryPush('maker:event', start, names)).toBe(true);+ expect(deferredToolBoundary(start)).toEqual(push('tool_use', { toolUseId: 't', toolName: 'Read', input: null }));+ expect(JSON.stringify(start).length).toBeGreaterThan(100000);+ });+});diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex c35f926aac..0a890379c7 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -67,6 +67,7 @@ import {} from '@cindy/model-providers/branding';import { app } from 'electron';import type { DeviceLinkClient } from '@cindy/device-link';+import { isDeferredHistoryPush, deferredToolBoundary } from './historyViewPush';import { createLogger } from '../logger';import { projectMobileMessagePage, projectMobileToolPush } from './mobileToolProjection';import { normalizeSessionProviderId } from '../maker-host/session-provider-store.js';@@ -108,6 +109,9 @@ const pushFailures = createPushFailureLog((summary) => log.warn('push delivery ffunction reportPushFailure(dst: string, channel: string, error: unknown): void {pushFailures.record(shortId(dst), channel, error instanceof DeviceLinkError ? error.code : 'UNKNOWN');}+let readHistoryToolName = (_sessionId: string, _toolUseId: string): string => '';+export function setHistoryToolNameReader(read: typeof readHistoryToolName): void { readHistoryToolName = read; }+/*** 老版本 mobile 只认识 #527 之前已发布的 logo kind。新 mark 可由同版本客户端按@@ -1550,6 +1554,7 @@ function scheduleSessionActivityRetry(dst: string, stage: SessionActivityStage):}function clearSessionActivityStage(dst: string): void {+ clearHistoryNotices(dst);const stage = sessionActivityStages.get(dst);if (!stage) return;if (stage.retryTimer) clearTimeout(stage.retryTimer);@@ -1558,6 +1563,7 @@ function clearSessionActivityStage(dst: string): void {function clearAllSessionActivityStages(): void {pushFailures.flush();+ for (const dst of historyNoticeStages.keys()) clearHistoryNotices(dst);for (const dst of [...sessionActivityStages.keys()]) clearSessionActivityStage(dst);for (const dst of [...sessionPatchStages.keys()]) clearSessionPatchStage(dst);}@@ -1581,6 +1587,26 @@ export function pushSessionActivityToController(* 按 topic 把一条本机广播转发给订阅了它的控制端。listener 注册后每条 tap 都过这里* (live 读 registry,topic 变化即时生效)。topic 算不出(无 session 标识)→ 丢弃。*/+const historyNoticeStages = new Map<string, Map<string, { ownerStamp?: PushOwnerStamp; timer: ReturnType<typeof setTimeout> }>>();+function stageHistoryNotice(dst: string, sessionId: string, ownerStamp?: PushOwnerStamp): void {+ const pending = historyNoticeStages.get(dst) ?? new Map();+ if (pending.has(sessionId)) return;+ if (pending.size >= 100) return;+ const 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);+ }+ }, 500);+ pending.set(sessionId, { timer, ownerStamp });+ historyNoticeStages.set(dst, pending);+}+function clearHistoryNotices(dst: string): void {+ for (const item of historyNoticeStages.get(dst)?.values() ?? []) clearTimeout(item.timer);+ historyNoticeStages.delete(dst);+}+function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerStamp): void {if (!activeClient) return;const topic = topicForPush(channel, payload);@@ -1651,10 +1677,14 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt}return mobilePayload;};+ const historySessionId = readPushSessionId(remotePayload);+ const deferred = historySessionId !== null && isDeferredHistoryPush(channel, remotePayload,+ (id) => readHistoryToolName(historySessionId, id));const offlineTargets = subscriptions.getKnownControllersForTopic(topic).filter((dst) => !liveTargets.includes(dst));for (const dst of offlineTargets) {+ if (deferred && historySessionId && subscriptions.hasHistoryView(dst, historySessionId)) continue;if (OFFLINE_QUEUEABLE_PUSH_CHANNELS.has(channel)) {offlinePushQueue.enqueue(dst, {channel,@@ -1665,7 +1695,18 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt}}for (const dst of liveTargets) {- const targetPayload = payloadFor(dst);+ let targetPayload = payloadFor(dst);+ if (deferred && historySessionId && subscriptions.hasHistoryView(dst, historySessionId)) {+ const 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) {+ const boundary = channel === MAKER_PUSH.EVENT ? deferredToolBoundary(remotePayload) : null;+ if (boundary === null) continue;+ targetPayload = boundary;+ }+ }const willBatch = batchEligibleSessionId !== null && batchTargets!.has(dst)&& estimateMakerEventBytes(targetPayload) < MAKER_EVENT_BATCH_MAX_BYTES;// 跨 channel 保序(review 两轮):**不入批**的帧必须排在该会话已暂存的事件@@ -2581,6 +2622,16 @@ function sanitizeMessageInvokeResult(result: InvokeResultPayload,channel: string | undefined,): InvokeResultPayload {+ if (result.ok && (channel === 'local-db:messages:view' || channel === 'local-db:messages:work-details')) {+ const page = result.result as { items?: Array<{ type: string; messages?: unknown[] }>; messages?: unknown[] };+ const sanitize = (message: unknown) => message && typeof message === 'object' && !Array.isArray(message)+ ? stripRecoveryCheckpointFromMessage(message as Record<string, unknown>) : message;+ return { ok: true, result: { ...page,+ ...(page.messages ? { messages: page.messages.map(sanitize) } : {}),+ ...(page.items ? { items: page.items.map((item) => item.messages+ ? { ...item, messages: item.messages.map(sanitize) } : item) } : {}),+ } };+ }if (!channel || !REMOTE_MESSAGE_CHANNELS.has(channel)) return result;if (!result.ok || !Array.isArray(result.result)) return result;let changed = false;@@ -2905,6 +2956,23 @@ function compactInvokeResultForDeviceLink(frame: { dst: string; requestId: string },args?: unknown[],): InvokeResultPayload | null {+ if (result.ok && (channel === 'local-db:messages:view' || channel === 'local-db:messages:work-details')+ && result.result && typeof result.result === 'object') {+ const page = result.result as Record<string, unknown>;+ const mapPage = (map: (row: unknown) => unknown): InvokeResultPayload => ({ ok: true, result: {+ ...page,+ ...(Array.isArray(page.messages) ? { messages: page.messages.map(map) } : {}),+ ...(Array.isArray(page.items) ? { items: page.items.map((item) => {+ const value = item as Record<string, unknown>;+ return value.type === 'messages' && Array.isArray(value.messages)+ ? { ...value, messages: value.messages.map(map) } : item;+ }) } : {}),+ } });+ const compact = mapPage(compactRemoteMessageForDeviceLink);+ if (fitsInvokeResultFrame(frame, compact)) return compact;+ const placeholder = mapPage((row) => forceCompactRemoteMessageContent(compactRemoteMessageForDeviceLink(row)));+ return fitsInvokeResultFrame(frame, placeholder) ? placeholder : null;+ }if (!channel || !REMOTE_MESSAGE_CHANNELS.has(channel)) return null;if (!result.ok || !Array.isArray(result.result)) return null;const compactMessages = result.result.map(compactRemoteMessageForDeviceLink);diff --git a/apps/desktop/src/main/device-link/historyViewPush.ts b/apps/desktop/src/main/device-link/historyViewPush.tsnew file mode 100644index 0000000000..5e9e0b7b28--- /dev/null+++ b/apps/desktop/src/main/device-link/historyViewPush.ts@@ -0,0 +1,38 @@+import { isHistoryDetailTool, hasVisibleHistoryResult } from '@cindy/maker-shared/message-window';+function record(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;+}+/** Conservative classification: interactions, errors and reference-bearing results stay live. */+export function isDeferredHistoryPush(channel: string, payload: unknown, toolName: (id: string) => string): boolean {+ const push = record(payload);+ if (!push) return false;+ if (channel === 'local-db:messages:created') {+ const row = record(push.message);+ if (!row) return false;+ if (row.role === 'thinking') return true;+ const content = record(row.content);+ if (row.role === 'tool_use') return isHistoryDetailTool(String(content?.toolName ?? ''));+ if (row.role !== 'tool_result' || hasVisibleHistoryResult(row.content)) return false;+ return typeof row.toolUseId === 'string' && isHistoryDetailTool(toolName(row.toolUseId));+ }+ if (channel !== 'maker:event') return false;+ const event = record(push.event);+ const data = record(event?.data);+ if (!event || !data || data.isError === true) return false;+ if (event.type === 'thinking') return true;+ if (event.type === 'tool_use') return isHistoryDetailTool(String(data.toolName ?? ''));+ if (event.type !== 'tool_result' && event.type !== 'tool_result_full') return false;+ if ([push.resolvedContent, data.summary, data.fullText].some(hasVisibleHistoryResult)) return false;+ const ids = typeof data.toolUseId === 'string' ? [data.toolUseId] : data.toolUseIds;+ return Array.isArray(ids) && ids.length > 0 && ids.every((id) => typeof id === 'string' && isHistoryDetailTool(toolName(id)));+}++/** Retain tool-start boundaries so a controller can finish the preceding assistant text. */+export function deferredToolBoundary(payload: unknown): unknown | null {+ const push = record(payload);+ const event = record(push?.event);+ const data = record(event?.data);+ return push && event?.type === 'tool_use' && data+ ? { ...push, event: { ...event, data: { toolUseId: data.toolUseId, toolName: data.toolName, input: null } } }+ : null;+}diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.tsindex 772e9e7189..29240038dd 100644--- a/apps/desktop/src/main/device-link/subscriptions.ts+++ b/apps/desktop/src/main/device-link/subscriptions.ts@@ -48,6 +48,35 @@ 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, { liveKey: string | null; expanded: Set<string> }>>();++export function updateHistoryView(deviceId: string, sessionId: string, liveKey: string | null): void {+ if (!controllerHasTopic(deviceId, `session:${sessionId}`)) return;+ const views = historyViewsByController.get(deviceId) ?? new Map();+ const view = views.get(sessionId) ?? { liveKey: null, expanded: new Set<string>() };+ view.liveKey = liveKey;+ views.set(sessionId, view);+ historyViewsByController.set(deviceId, views);+}++export function setHistoryExpanded(deviceId: string, sessionId: string, keys: readonly string[]): void {+ // Do not recreate detail intent after an explicit session unsubscribe.+ if (!controllerHasTopic(deviceId, `session:${sessionId}`)) return;+ const views = historyViewsByController.get(deviceId) ?? new Map();+ const view = views.get(sessionId) ?? { liveKey: null, expanded: new Set<string>() };+ view.expanded = new Set(keys);+ views.set(sessionId, view);+ historyViewsByController.set(deviceId, views);+}++export function hasHistoryView(deviceId: string, sessionId: string): boolean {+ return historyViewsByController.get(deviceId)?.has(sessionId) === true;+}++export function projectsHistoryDetails(deviceId: string, sessionId: string): boolean {+ const view = historyViewsByController.get(deviceId)?.get(sessionId);+ return !!view && (!view.liveKey || !view.expanded.has(view.liveKey));+}/*** topic 生命周期监听(fs-watch 档消费:订阅驱动被控端文件 watch 启停)。@@ -162,6 +191,10 @@ export function controllerHasTopic(deviceId: string, topic: string): boolean {/** 取消订阅指定 topics;该控制端 topic 清空后整条移除。空 topics 为 no-op。 */export function unsubscribe(deviceId: string, topics: readonly string[]): void {+ for (const topic of topics) {+ if (topic.startsWith('session:')) historyViewsByController.get(deviceId)?.delete(topic.slice(8));+ }+ if (historyViewsByController.get(deviceId)?.size === 0) historyViewsByController.delete(deviceId);const e = registry.get(deviceId);const remembered = rememberedTopicsByController.get(deviceId);if (!e && !remembered) return;@@ -191,6 +224,7 @@ export function clearController(deviceId: string): boolean {/** 显式撤销/账号边界使用:释放 active topics,并删除断线恢复状态。 */export function forgetKnownController(deviceId: string): void {+ historyViewsByController.delete(deviceId);clearController(deviceId);knownControllerIds.delete(deviceId);rememberedTopicsByController.delete(deviceId);@@ -199,6 +233,7 @@ export function forgetKnownController(deviceId: string): void {/** 清空所有订阅(登出 / 关被控 / 退出)。 */export function clearAll(): void {+ historyViewsByController.clear();const held = new Set<StoredTopic>();for (const e of registry.values()) for (const t of e.topics) held.add(t);registry.clear();@@ -290,6 +325,7 @@ export function getUpdateRelaunchControllers(): ActiveController[] {export const __testing = {reset(): void {+ historyViewsByController.clear();registry.clear();knownControllerIds.clear();rememberedTopicsByController.clear();diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.tsnew file mode 100644index 0000000000..3885039be6--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it, vi } from 'vitest';+import { createHistoryViewReader } from '../historyViewReader';+import type { HistoryMessageSource } from '@cindy/maker-shared/message-window';+function row(n: number, role = 'thinking'): HistoryMessageSource {+ return { id: String(n), clientId: `c${n}`, rowid: n, role, content: 'body '.repeat(200), createdAt: new Date(1700000000000 + n).toISOString() };+}+function reader(source: HistoryMessageSource[]) {+ const list = vi.fn(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 anchor = async (_sid: string, id: string) => {+ const found = source.find((r) => r.id === id);+ if (!found) throw new Error('History range changed');+ return found;+ };+ return { list, api: createHistoryViewReader({ list, anchor, running: () => false }) };+}+describe('host history view', () => {+ it('paginates visible items across a long hidden run without splitting or sending its bodies', async () => {+ const source = [row(0, 'user'), ...Array.from({ length: 600 }, (_, i) => row(i + 1)), row(601, 'assistant')];+ const { api, list } = reader(source);+ const page = await api.page('s');+ expect(page.items.map((item) => item.type)).toEqual(['messages', 'work', 'messages']);+ expect(page.hasMore).toBe(false);+ expect(list).toHaveBeenCalledTimes(7);+ expect(JSON.stringify(page).length).toBeLessThan(JSON.stringify(source).length / 100);+ const work = page.items[1];+ if (work.type !== 'work') throw new Error('missing summary');+ const received: string[] = [];+ let after: string | undefined;+ do {+ const details = await api.details('s', work.summary, after);+ received.push(...details.messages.map((item) => item.id));+ after = details.nextCursor ?? undefined;+ } while (after);+ expect(received).toEqual(source.slice(1, -1).map((item) => item.id));+ });+ it('walks multiple visible pages without losing or duplicating source ranges', async () => {+ const source = Array.from({ length: 45 }, (_, turn) => [row(turn * 3, 'user'), row(turn * 3 + 1), row(turn * 3 + 2, 'assistant')]).flat();+ const { api } = reader(source);+ const seen: string[] = [];+ let before: string | undefined;+ do {+ const page = await api.page('s', before);+ expect(page.items.length).toBeLessThanOrEqual(20);+ for (const item of page.items) {+ if (item.type === 'messages') seen.push(...item.messages.map((message) => message.id));+ else seen.push(...(await api.details('s', item.summary)).messages.map((message) => message.id));+ }+ before = page.nextCursor ?? undefined;+ } while (before);+ expect(seen.sort((a, b) => Number(a) - Number(b))).toEqual(source.map((message) => message.id));+ });++ it('recovers every in-flight block and automatically continues across their byte boundary', async () => {+ const stored = [row(0, 'user')];+ const live = [1, 2].map((n) => ({ ...row(n), id: `history-live:c${n}`, content: 'x'.repeat(200000) }));+ const base = reader(stored);+ const api = createHistoryViewReader({ list: base.list, running: () => true, live: () => live,+ anchor: async (_sid: string, id: string) => {+ const found = [...stored, ...live].find((message) => message.id === id);+ if (!found) throw new Error('not found');+ return found;+ },+ });+ const page = await api.page('s');+ const work = page.items.find((item) => item.type === 'work');+ if (work?.type !== 'work') throw new Error('missing work');+ const first = await api.details('s', work.summary);+ expect(first.messages.map((message) => message.clientId)).toEqual(['c1']);+ expect(first.hasMore).toBe(true);+ const second = await api.details('s', work.summary, first.nextCursor!);+ expect(second.messages.map((message) => message.clientId)).toEqual(['c2']);+ expect(second.hasMore).toBe(false);+ });++ it('rejects same-millisecond backwards ranges and detail cursors beyond the upper rowid', async () => {+ const source = [row(1), row(2), row(3)].map((r) => ({ ...r, createdAt: row(0).createdAt }));+ const { api } = reader(source);+ await expect(api.details('s', { key: 'w', firstMessageId: '2', lastMessageId: '1' })).rejects.toThrow('Invalid history range');+ await expect(api.details('s', { key: 'w', firstMessageId: '1', lastMessageId: '2' }, '3')).rejects.toThrow('Invalid detail cursor');+ expect((await api.details('s', { key: 'w', firstMessageId: '1', lastMessageId: '2' })).messages.map((r) => r.id)).toEqual(['1', '2']);+ });+ it('does not publish a snapshot when clear invalidates rows during scanning', async () => {+ const source = [row(0, 'user'), row(1), row(2, 'assistant')];+ const { api, list } = reader(source);+ const implementation = list.getMockImplementation()!;+ list.mockImplementationOnce(async (...args) => { const result = await implementation(...args); source.length = 0; return result; });+ await expect(api.page('s')).rejects.toThrow('History range changed');+ });+ it.each([1000, 200000])('rejects details cleared or rewound during a batch before returning (%i bytes)', async (size) => {+ for (const keep of [0, 1]) {+ const source = [row(1), row(2), row(3)].map((message) => ({ ...message, content: 'x'.repeat(size) }));+ const { api, list } = reader(source);+ const implementation = list.getMockImplementation()!;+ list.mockImplementationOnce(async (...args) => {+ const result = await implementation(...args);+ source.splice(keep);+ return result;+ });+ await expect(api.details('s', { key: 'w', firstMessageId: '1', lastMessageId: '3' }))+ .rejects.toThrow('History range changed');+ }+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts b/apps/desktop/src/main/localDb/ipc/historyViewReader.tsnew file mode 100644index 0000000000..61cfb896be--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts@@ -0,0 +1,135 @@+import {+ HISTORY_VIEW_PAGE_BYTES, HISTORY_VIEW_PAGE_ITEMS, HISTORY_DETAIL_PAGE_BYTES,+ projectHistoryView, type HistoryMessageSource, type HistoryViewItem,+ type HistoryViewPage, type HistoryDetailPage, type HistoryWorkReference,+} from '@cindy/maker-shared/message-window';++interface ReadOptions { limit: number; before?: string; after?: string }+export interface HistoryViewReaderDependencies<T extends HistoryMessageSource> {+ list(sessionId: string, opts: ReadOptions, skipImport: boolean): Promise<T[]>;+ /** Must reject anchors outside this session, cleared history or rewound history. */+ anchor(sessionId: string, id: string): Promise<T>;+ running(sessionId: string): boolean;+ live?(sessionId: string): T[];+}++function compareRows(a: HistoryMessageSource, b: HistoryMessageSource): number {+ return Date.parse(a.createdAt) - Date.parse(b.createdAt) || (a.rowid ?? 0) - (b.rowid ?? 0);+}++function firstId<T extends HistoryMessageSource>(item: HistoryViewItem<T>): string {+ return item.type === 'work' ? item.summary.firstMessageId : item.messages[0].id;+}++export function createHistoryViewReader<T extends HistoryMessageSource>(deps: HistoryViewReaderDependencies<T>) {+ return {+ async page(sessionId: string, before?: string): Promise<HistoryViewPage<T>> {+ const beforeAnchor = before ? await deps.anchor(sessionId, before) : undefined;+ let cursor = beforeAnchor?.id.startsWith('history-live:') ? undefined : beforeAnchor?.id;+ const chunks: T[][] = [];+ let raw: T[] = [];+ let exhausted = false;+ let items: HistoryViewItem<T>[] = [];+ // Scan locally until the *visible* page fills. The oldest open group is+ // withheld until a boundary is known, so a long run is not split per DB batch.+ for (let scan = 0; ; scan++) {+ const rows = await deps.list(sessionId, { limit: 100, ...(cursor ? { before: cursor } : {}) }, scan > 0);+ if (rows.length === 0) { exhausted = true; break; }+ const next = rows[rows.length - 1].id;+ if (next === cursor) throw new Error('History cursor did not advance');+ cursor = next;+ chunks.push(rows.slice().reverse());+ exhausted = rows.length < 100;+ if (!exhausted && !rows.some((row) => row.role === 'user' || row.role === 'system')) continue;+ raw = chunks.slice().reverse().flat();+ const live = !before ? (deps.live?.(sessionId) ?? []).filter((row) => !raw.some((stored) => stored.clientId === row.clientId)) : [];+ const boundary = exhausted ? 0 : raw.findIndex((row) => row.role === 'user' || row.role === 'system');+ items = boundary < 0 ? [] : projectHistoryView([...raw.slice(boundary), ...live], !before && deps.running(sessionId));+ if (exhausted || items.length > HISTORY_VIEW_PAGE_ITEMS) break;+ }+ raw = chunks.slice().reverse().flat();+ const live = !before ? (deps.live?.(sessionId) ?? []).filter((row) => !raw.some((stored) => stored.clientId === row.clientId)) : [];+ const boundary = exhausted ? 0 : raw.findIndex((row) => row.role === 'user' || row.role === 'system');+ items = boundary < 0 ? [] : projectHistoryView([...raw.slice(boundary), ...live], !before && deps.running(sessionId));+ const selected: HistoryViewItem<T>[] = [];+ let bytes = 1024;+ for (let index = items.length - 1; index >= 0; index--) {+ const size = Buffer.byteLength(JSON.stringify(items[index]), 'utf8');+ if (selected.length > 0 && (selected.length >= HISTORY_VIEW_PAGE_ITEMS || bytes + size > HISTORY_VIEW_PAGE_BYTES)) break;+ selected.unshift(items[index]);+ bytes += size;+ }+ // A clear/rewind during the scan invalidates the whole snapshot, including+ // already-read rows. Never publish a prefix from the previous history epoch.+ if (raw.length) await Promise.all([deps.anchor(sessionId, raw[0].id), deps.anchor(sessionId, raw[raw.length - 1].id)]);+ const hasMore = !exhausted || selected.length < items.length;+ return { version: 1, items: selected, hasMore,+ nextCursor: hasMore && selected.length ? firstId(selected[0]) : null };+ },++ async details(sessionId: string, ref: HistoryWorkReference, after?: string): Promise<HistoryDetailPage<T>> {+ const finalize = async (page: HistoryDetailPage<T>): Promise<HistoryDetailPage<T>> => {+ // Like the summary scan, every detail exit must reject a clear/rewind+ // that happened while an earlier DB batch was already collected.+ const ids = new Set([ref.firstMessageId, ref.lastMessageId, ...(ref.liveMessageIds ?? [])]);+ await Promise.all([...ids].map((id) => deps.anchor(sessionId, id)));+ return page;+ };+ if (ref.liveMessageIds?.length) {+ const live = await Promise.all(ref.liveMessageIds.map((id) => deps.anchor(sessionId, id)));+ const liveCursor = after ? ref.liveMessageIds.indexOf(after) : -1;+ const stored = liveCursor >= 0 || !ref.firstStoredMessageId || !ref.lastStoredMessageId+ ? { version: 1 as const, messages: [] as T[], hasMore: false, nextCursor: null }+ : await this.details(sessionId, { key: ref.key, firstMessageId: ref.firstStoredMessageId, lastMessageId: ref.lastStoredMessageId }, after);+ if (stored.hasMore) return finalize(stored);+ const collected = [...stored.messages];+ let bytes = Buffer.byteLength(JSON.stringify(collected), 'utf8') + 1024;+ let cursor = stored.messages.at(-1)?.id ?? after ?? ref.lastStoredMessageId;+ for (let index = liveCursor + 1; index < live.length; index++) {+ const row = live[index];+ if (collected.some((storedRow) => storedRow.clientId === row.clientId)) continue;+ const size = Buffer.byteLength(JSON.stringify(row), 'utf8');+ if (collected.length > 0 && bytes + size > HISTORY_DETAIL_PAGE_BYTES) {+ return finalize({ version: 1, messages: collected, hasMore: true, nextCursor: cursor ?? null });+ }+ collected.push(row);+ bytes += size;+ cursor = ref.liveMessageIds[index];+ }+ return finalize({ version: 1, messages: collected, hasMore: false, nextCursor: null });+ }+ const first = await deps.anchor(sessionId, ref.firstMessageId);+ const last = await deps.anchor(sessionId, ref.lastMessageId);+ if (compareRows(first, last) > 0) throw new Error('Invalid history range');+ let cursor = after;+ const collected: T[] = [];+ let bytes = 1024;+ if (!after) {+ collected.push(first);+ bytes += Buffer.byteLength(JSON.stringify(first), 'utf8');+ cursor = first.id;+ } else {+ const anchor = await deps.anchor(sessionId, after);+ if (compareRows(anchor, first) < 0 || compareRows(anchor, last) > 0) throw new Error('Invalid detail cursor');+ }+ if (cursor === last.id) return finalize({ version: 1, messages: collected, nextCursor: null, hasMore: false });+ for (;;) {+ const rows = (await deps.list(sessionId, { limit: 100, after: cursor }, true)).slice().reverse();+ if (rows.length === 0) throw new Error('History range changed');+ for (const row of rows) {+ if (compareRows(row, last) > 0) throw new Error('History range changed');+ const size = Buffer.byteLength(JSON.stringify(row), 'utf8');+ if (collected.length > 0 && bytes + size > HISTORY_DETAIL_PAGE_BYTES) {+ return finalize({ version: 1, messages: collected, nextCursor: cursor ?? null, hasMore: true });+ }+ if (row.id === cursor) throw new Error('History detail cursor did not advance');+ collected.push(row);+ bytes += size;+ cursor = row.id;+ if (cursor === last.id) return finalize({ version: 1, messages: collected, nextCursor: null, hasMore: false });+ if (Date.parse(row.createdAt) > Date.parse(last.createdAt)) throw new Error('History range changed');+ }+ }+ },+ };+}diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex d9a748ebc8..0d18953f58 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -44,7 +44,8 @@ import {} from '../../cindy-media/ledger';import { importExternalCodexMessagesForSession } from '../../maker-host/codex-local-sessions';import { importExternalClaudeCodeMessagesForSession } from '../../maker-host/claude-local-sessions';-import { isDeviceLinkInvoke } from '../../device-link/invoke-context';+import { getDeviceLinkInvokeContext, isDeviceLinkInvoke } from '../../device-link/invoke-context';+import { updateHistoryView, setHistoryExpanded } from '../../device-link/subscriptions';import { onMessageCreated as onChatMessageCreatedForEmbedding } from '../../embedders/chat-history-embedder';import { recomputePrRefsForSession, recordPrRefsForMessage } from '../../git-context/prRefsStore';import {@@ -65,6 +66,8 @@ import { capReferenceMessageRows } from './history.js';import { maybeUpgradeCodexHistoryOversizedError } from '../codexHistoryOversizedUpgrade';import type { Message, MessageRole, AgentMeta } from '../../../renderer/lib/ccAgent.types';import { scheduleBotRemoteResourceChangedForSession } from '../../maker-ipc/botRemoteResourceInvalidation';+import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer';+import { createHistoryViewReader } from './historyViewReader';const log = createLogger('localDb/messages');@@ -235,8 +238,7 @@ const VALID_ROLES: ReadonlySet<MessageRole> = new Set(['thinking',] as const);-export function registerMessageIpc(): void {- ipcMain.handle('local-db:messages:list', async (_e, sessionId: unknown, opts: unknown) => {+export async function readMessagesList(sessionId: unknown, opts: unknown, skipImport = false) {const sid = requireString(sessionId, 'sessionId');const limit = clampLimit((opts as { limit?: number } | undefined)?.limit);const before = (opts as { before?: string } | undefined)?.before;@@ -247,7 +249,7 @@ export function registerMessageIpc(): void {// 外部历史导入(Codex rollout / Claude transcript):device-link 隧道调用// 只在首页请求跑(分页跳过,#318 性能语义;首页判定 = 无任何分页游标),// 覆盖「被控端从未本机打开该会话」的导入缺口。- await runMessagesListImportSideEffects(+ if (!skipImport) await runMessagesListImportSideEffects(sid,{},{@@ -343,6 +345,71 @@ export function registerMessageIpc(): void {});}return listed;+}++export function registerMessageIpc(+ readRunning: (sessionId: string) => boolean = () => false,+ readLive: (sessionId: string) => Message[] = () => [],+): void {+ ipcMain.handle('local-db:messages:list', (_e, sessionId: unknown, opts: unknown) =>+ readMessagesList(sessionId, opts));++ const historyView = createHistoryViewReader({+ list: readMessagesList,+ running: readRunning,+ live: readLive,+ anchor: async (sessionId, id) => {+ const db = getDbClient().drizzle;+ const [session] = await db.select({ clearedAt: sessions.clearedAt }).from(sessions)+ .where(eq(sessions.id, sessionId)).limit(1);+ if (!session) throwIpcError('NOT_FOUND', 'History is unavailable');+ if (id.startsWith('history-live:')) {+ const live = readLive(sessionId).find((row) => row.id === id);+ if (live && (session.clearedAt === null || Date.parse(live.createdAt) > session.clearedAt)) return live;+ }+ const [row] = await db.select({ ...getMessageSelectFields(), rowid: messageRowid }).from(messages)+ .where(and(eq(messages.sessionId, sessionId),+ id.startsWith('history-live:') ? eq(messages.clientId, id.slice('history-live:'.length)) : eq(messages.id, id),+ isNull(messages.rewindAt),+ session.clearedAt !== null ? gt(messages.createdAt, session.clearedAt) : undefined)).limit(1);+ if (!row) throwIpcError('NOT_FOUND', 'History range changed');+ return messageToCamelWithRowid(row);+ },+ });+ ipcMain.handle('local-db:messages:view', async (event, sessionId: unknown, opts: unknown) => {+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);+ const sid = requireString(sessionId, 'sessionId');+ const before = (opts as { before?: unknown } | null)?.before;+ const page = await historyView.page(sid, before == null ? undefined : requireString(before, 'before'));+ const controller = getDeviceLinkInvokeContext()?.controllerDeviceId;+ if (controller && before == null) {+ const live = page.items.find((item) => item.type === 'work' && item.summary.isStreaming);+ updateHistoryView(controller, sid, live?.key ?? null);+ }+ return page;+ });+ ipcMain.handle('local-db:messages:view-intent', (event, sessionId: unknown, refs: unknown) => {+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);+ const sid = requireString(sessionId, 'sessionId');+ if (!Array.isArray(refs) || refs.length > 100) throwIpcError('INVALID_PARAMS', 'Invalid expanded work groups');+ const keys = refs.map((ref) => requireString(ref?.key, 'key'));+ const controller = getDeviceLinkInvokeContext()?.controllerDeviceId;+ if (controller) setHistoryExpanded(controller, sid, keys);+ });+ ipcMain.handle('local-db:messages:work-details', async (event, sessionId: unknown, ref: unknown, opts: unknown) => {+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);+ const sid = requireString(sessionId, 'sessionId');+ const value = ref as { key?: unknown; firstMessageId?: unknown; lastMessageId?: unknown; firstStoredMessageId?: unknown; lastStoredMessageId?: unknown; liveMessageIds?: unknown } | null;+ const after = (opts as { after?: unknown } | null)?.after;+ if (value?.liveMessageIds != null && (!Array.isArray(value.liveMessageIds) || value.liveMessageIds.length > 100)) throwIpcError('INVALID_PARAMS', 'Invalid live work range');+ return historyView.details(sid, {+ key: requireString(value?.key, 'key'),+ firstMessageId: requireString(value?.firstMessageId, 'firstMessageId'),+ lastMessageId: requireString(value?.lastMessageId, 'lastMessageId'),+ ...(value?.firstStoredMessageId == null ? {} : { firstStoredMessageId: requireString(value.firstStoredMessageId, 'firstStoredMessageId') }),+ ...(value?.lastStoredMessageId == null ? {} : { lastStoredMessageId: requireString(value.lastStoredMessageId, 'lastStoredMessageId') }),+ ...(Array.isArray(value?.liveMessageIds) ? { liveMessageIds: value.liveMessageIds.map((id) => requireString(id, 'liveMessageId')) } : {}),+ }, after == null ? undefined : requireString(after, 'after'));});ipcMain.handle(diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.tsindex c09f6476d7..8a685e00f3 100644--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts@@ -77,6 +77,8 @@ function startMediaRefCompensationReconcile(}export interface RegisterLocalDbIpcOpts {+ isSessionTurnPendingCompletion?: (sessionId: string) => boolean;+ readHistoryLiveMessages?: (sessionId: string) => import('../../../renderer/lib/ccAgent.types').Message[];resolveContextWindow?: RegisterSessionIpcOpts['resolveContextWindow'];/** Current stable app-session owner. False makes queued/in-flight work stale. */isOwnerCurrent?: (userId: string) => boolean;@@ -254,7 +256,7 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {resolveContextWindow: opts.resolveContextWindow,closeIdleSessionForMove: opts.closeIdleSessionForMove,});- registerMessageIpc();+ registerMessageIpc(opts.isSessionTurnPendingCompletion, opts.readHistoryLiveMessages);registerRemoteHistoryIpc();registerBotIpc();registerRoutinesIpc();diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex e98b287f9c..d028b04160 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -66,7 +66,7 @@ import {import { normalizeSubagentObservation } from '@cindy/maker-shared/subagent-observation';import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';import { getSessionProvider } from './maker-host/session-provider-store.js';-import type { AgentMeta } from '../renderer/lib/ccAgent.types';+import type { AgentMeta, Message } from '../renderer/lib/ccAgent.types';import { parseToolLoopErrorDetails, type ToolLoopErrorDetails } from '@cindy/maker-core';const log = createLogger('messagePersistBroadcaster');@@ -82,6 +82,18 @@ interface AssistantBlock {}const assistantBlocks = new Map<string, AssistantBlock>();+// In-flight thinking is not in SQLite until final. Keep one recoverable snapshot+// so expanding midway does not depend on deltas a collapsed controller never received.+const historyThinkingBlocks = new Map<string, Map<string, Message>>();+const historyThinkingOwners = new Map<string, OwnerScope>();+export function getSessionThinkingSnapshots(sessionId: string): Message[] {+ if (!isOwnerScopeCurrent(historyThinkingOwners.get(sessionId) ?? null)) {+ historyThinkingBlocks.delete(sessionId);+ historyThinkingOwners.delete(sessionId);+ return [];+ }+ return [...(historyThinkingBlocks.get(sessionId)?.values() ?? [])];+}/** Read the in-flight block without flushing or changing its persistence identity. */export function getSessionTextSnapshot(sessionId: string) {@@ -149,6 +161,8 @@ export function noteSessionClearBoundary(sessionId: string, clearedAt: string |if (!Number.isFinite(parsed)) return;const current = clearBoundaryBySession.get(sessionId);if (current === undefined || parsed > current) {+ historyThinkingBlocks.delete(sessionId);+ historyThinkingOwners.delete(sessionId);clearBoundaryBySession.set(sessionId, parsed);sealedAssistantLateFinalBySession.delete(sessionId);// A cleared transcript must not be revived by a late terminal update from an@@ -522,9 +536,14 @@ function enqueueVisibleDbMessage(label: string,sessionId: string,body: CreateDbMessageBody,+ onPersisted?: () => void,): void {const stamped = withAgentKindStamp(sessionId, body);- enqueueWrite(label, (ownerScope) => createVisibleDbMessage(sessionId, stamped, ownerScope));+ enqueueWrite(label, async (ownerScope) => {+ const result = await createVisibleDbMessage(sessionId, stamped, ownerScope);+ onPersisted?.();+ return result;+ });}/**@@ -646,6 +665,10 @@ const codexPlanRowByTurnToolUseId = new Map<>();const toolUseInfoBySession = new Map<string, Map<string, { toolName: string; input: unknown }>>();+export function getHistoryToolName(sessionId: string, toolUseId: string): string {+ return toolUseInfoBySession.get(sessionId)?.get(toolUseId)?.toolName ?? '';+}+const updatableToolUsePersistIdBySession = new Map<string, Map<string, string>>();/*** Agent/Task terminal events are live-only, while the originating tool_use is durable.@@ -1311,16 +1334,43 @@ export function prepareSyntheticToolEventForBroadcast(*/export function onThinkingEvent(sessionId: string,- data: { stage?: unknown; blockId?: unknown; text?: unknown; durationMs?: unknown },+ data: { stage?: unknown; blockId?: unknown; text?: unknown; durationMs?: unknown; startedAt?: unknown },agentMeta: AgentMeta | null,): void {const blockId = typeof data.blockId === 'string' ? data.blockId : '';if (!blockId) return;+ const receivedAt = Date.now();const meta = agentMeta ?? lastAgentMetaBySession.get(sessionId) ?? null;noteAssistantTranscriptUuid(sessionId, meta);+ getSessionThinkingSnapshots(sessionId);+ const blocks = historyThinkingBlocks.get(sessionId) ?? new Map<string, Message>();+ const previous = blocks.get(blockId);+ if (data.stage === 'start' || data.stage === 'delta' || data.stage === 'final') {+ const previousText = (previous?.content as { text?: string } | undefined)?.text ?? '';+ const text = typeof data.text === 'string' ? data.text : '';+ blocks.set(blockId, {+ id: `history-live:${blockId}`, clientId: blockId, sessionId, role: 'thinking', toolUseId: null,+ agentMeta: meta,+ createdAt: previous?.createdAt ?? new Date(typeof data.startedAt === 'number' ? data.startedAt : receivedAt).toISOString(),+ content: { kind: 'thinking', text: data.stage === 'delta' ? previousText + text : text,+ durationMs: typeof data.durationMs === 'number' ? data.durationMs : 0 },+ });+ historyThinkingBlocks.set(sessionId, blocks);+ historyThinkingOwners.set(sessionId, captureOwnerScope());+ }+ const finalSnapshot = blocks.get(blockId);+ const releaseSnapshot = () => {+ if (blocks.get(blockId) !== finalSnapshot) return;+ blocks.delete(blockId);+ if (blocks.size === 0 && historyThinkingBlocks.get(sessionId) === blocks) {+ historyThinkingBlocks.delete(sessionId);+ historyThinkingOwners.delete(sessionId);+ }+ };+if (data.stage === 'final') {- const finishedAt = Date.now();+ const finishedAt = receivedAt;const text = typeof data.text === 'string' ? data.text : '';const durationMs = typeof data.durationMs === 'number' ? data.durationMs : 0;enqueueVisibleDbMessage(`thinking:${sessionId}:${blockId}`, sessionId, {@@ -1329,10 +1379,11 @@ export function onThinkingEvent(content: { kind: 'thinking', text, durationMs, isRedacted: false, finishedAt },agentMeta: meta,createdAt: finishedAt,- });+ }, releaseSnapshot);notePersistedMessage(sessionId, 'thinking', blockId);} else if (data.stage === 'redacted') {- const finishedAt = Date.now();+ releaseSnapshot();+ const finishedAt = receivedAt;enqueueVisibleDbMessage(`thinking_redacted:${sessionId}:${blockId}`, sessionId, {clientId: blockId,role: 'thinking',@@ -1785,6 +1836,8 @@ export function flushOrphanToolResults(sessionId: string, agentMeta: AgentMeta |* + knownToolUseIds + lastAgentMeta。必须在 flushOrphanToolResults 之后调用。*/export function resetTurnPersistState(sessionId: string): void {+ historyThinkingBlocks.delete(sessionId);+ historyThinkingOwners.delete(sessionId);toolResultIdByToolUseId.delete(sessionId);pendingFullTextByToolUseId.delete(sessionId);toolResultContentByClientId.delete(sessionId);@@ -2393,6 +2446,8 @@ export function clearCodexPlanRowsForSession(sessionId: string): void {}export function clearSessionPersistState(sessionId: string): void {+ historyThinkingBlocks.delete(sessionId);+ historyThinkingOwners.delete(sessionId);clearCodexPlanRowsForSession(sessionId);assistantBlocks.delete(sessionId);sealedAssistantLateFinalBySession.delete(sessionId);diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.tsindex cc4fb78550..5142becbe7 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts@@ -48,7 +48,8 @@ vi.mock('@/lib/composerDraftStore', () => ({plainTextToTiptapDoc: (s: string) => ({ type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }] }),}));-import { makerChatStore } from '@/lib/makerChatStore';+import { makerChatStore, getRemoteHistoryView } from '@/lib/makerChatStore';+import { projectHistoryView } from '@cindy/maker-shared/message-window';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';// ─── 忠实的被控端内存替身(单一真相源)───────────────────────────────────────────@@ -77,6 +78,7 @@ function makeFakeHost(deviceId: string, deviceName: string) {const sessionsMeta = new Map<string, Record<string, unknown>>();const messages = new Map<string, Message[]>();let pushCb: ((p: RemotePush) => void) | null = null;+ let historyViewEnabled = false;function meta(sid: string): Record<string, unknown> {return {@@ -88,6 +90,13 @@ function makeFakeHost(deviceId: string, deviceName: string) {const invoke = vi.fn(async (_d: string, channel: string, args: unknown[]) => {switch (channel) {+ case 'local-db:messages:view':+ return historyViewEnabled ? { version: 1, items: projectHistoryView(messages.get(args[0] as string) ?? [], false), hasMore: false, nextCursor: null } : null;+ case 'local-db:messages:work-details': {+ const rows = messages.get(args[0] as string) ?? [];+ const ref = args[1] as { firstMessageId: string; lastMessageId: string };+ return { version: 1, messages: rows.slice(rows.findIndex((row) => row.id === ref.firstMessageId), rows.findIndex((row) => row.id === ref.lastMessageId) + 1), hasMore: false, nextCursor: null };+ }case 'local-db:messages:list': {const sid = args[0] as string;const opts = (args[1] ?? {}) as { limit?: number };@@ -115,6 +124,7 @@ function makeFakeHost(deviceId: string, deviceName: string) {return {deviceId,deviceName,+ enableHistoryView: () => { historyViewEnabled = true; },invoke,/** 注册控制端 onRemotePush 回调(被控端经此向控制端转发广播)。 */registerPush(cb: (p: RemotePush) => void): () => void {@@ -203,6 +213,29 @@ afterEach(() => {});describe('device-link controller mirror — end-to-end scenarios', () => {+ it('reads visible history first and fetches a collapsed work range only after expansion', async () => {+ const s = sid();+ host.enableHistoryView();+ const history = [dbMessage(s, 'u', 'question', '2026-06-15T00:00:00.000Z', 'user'),+ { ...dbMessage(s, 'thought', '', '2026-06-15T00:00:01.000Z', 'thinking'), content: { kind: 'thinking', text: 'hidden body', durationMs: 500, isRedacted: false } },+ dbMessage(s, 'answer', 'answer', '2026-06-15T00:00:02.000Z')];+ host.seedSession(s, {}, history);+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);+ makerChatStore.ensureInitialMessages(s);+ await flush();+ await flush();+ expect(host.invoke).not.toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.clientId)).toEqual(['client-u', 'client-answer']);+ const view = getRemoteHistoryView(s)!;+ const group = view.getSnapshot().items.find((item) => item.type === 'work')!;+ expect(view.getSnapshot().details.size).toBe(0);+ view.setExpanded(group.key, true);+ await flush();+ expect(view.getSnapshot().details.get(group.key)?.messages[0].content).toBe('hidden body');+ expect(makerChatStore.getSnapshot(s).messages.some((row) => row.clientId === 'client-thought')).toBe(true);+ view.setActive(false);+ });+it('完整镜像回路:开会话见历史 → live push 追加 → 丢帧 reconcile heal → 设置变更镜像', async () => {const s = sid();// 被控端已有 1 条历史 + 注册到远程项目(getSessionDeviceId 命中 → 传输层走隧道)。diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex ee33239103..e2c7a36254 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -1440,7 +1440,7 @@ describe('远程交互接线不变式', () => {it('F5: loadAroundMessage 经 aroundMessagesFor 路由(远程隧道,不查控制端空库)', () => {const src = read('lib/makerChatStore.ts');- expect(src).toContain('aroundMessagesFor(sessionId, messageId, opts)');+ expect(src).toContain('aroundMessagesFor(sessionId, messageId, view?.getSnapshot().ready ? { radius: 0 } : opts)');});it('F7: dispatch handleSubscriptionFrame 拒绝 legacy "*"(只 link-open 可订全量)', () => {diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 5b5361ea87..d3d81317c0 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -28,6 +28,8 @@ import {type CSSProperties,type ReactNode,} from 'react';+import { renderHistoryView } from '@cindy/maker-shared/message-window';+import { getRemoteHistoryView, type HistoryChatMessage } from '@/lib/makerChatStore';import { createPortal } from 'react-dom';import { GitFork } from 'lucide-react';import { SelectionQuoteButton } from './SelectionQuoteButton';@@ -2477,6 +2479,12 @@ export function MessageStream({onInlinePlanVisibilityChange,}: MessageStreamProps) {const { i18n, t } = useTranslation();+ const historyView = sessionId ? getRemoteHistoryView(sessionId) : undefined;+ const historySnapshot = useSyncExternalStore(+ historyView?.subscribe ?? (() => () => undefined),+ historyView?.getSnapshot ?? (() => null),+ historyView?.getSnapshot ?? (() => null),+ );// 右上角 chip 栈插槽 —— PrevMessageJumpChip 通过 portal 挂到这里,// 与 DiffPanelToggle 在同一栈中各占一行。Provider 不存在时返回 null,// 渲染处会兜底跳过(典型场景:其他视图直接用 MessageStream 但不需要栈)。@@ -2723,12 +2731,42 @@ export function MessageStream({botSessionId: simplifiedBotConversation ? sessionId : undefined,markdownImageTargetCache: markdownImageTargetCacheRef.current,});+ if (historyView && historySnapshot?.ready) {+ const results = new Map(built.singleResultMap);+ const liveMessages: HistoryChatMessage[] = messages.map((row) => ({ ...row,+ id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',+ }));+ const items = renderHistoryView<HistoryChatMessage, RenderItem>({+ view: historyView, snapshot: historySnapshot, liveMessages, streaming: isSessionStreaming,+ isLive: (row) => row.isStreaming === true,+ build: (rows) => {+ const chunk = buildRenderItems([...rows], taskUpdates, ghostCardSnapshot, {+ historyWindowIncomplete: true, workingDir,+ markdownImageTargetCache: markdownImageTargetCacheRef.current,+ });+ for (const [key, value] of chunk.singleResultMap) results.set(key, value);+ return chunk.items;+ },+ work: (summary, details, deferred) => ({ type: 'work_group', key: summary.key,+ children: details.filter((item): item is WorkChildItem => item.type === 'message'+ || item.type === 'tool_segment' || item.type === 'agent_task'),+ deferred, isStreaming: summary.isStreaming, startedAtMs: summary.startedAtMs,+ durationMs: Math.max(0, summary.endedAtMs - summary.startedAtMs),+ }),+ });+ const keys = new Set<string>();+ const unique = items.filter((item) => { if (keys.has(item.key)) return false; keys.add(item.key); return true; });+ return { items: reuseGeneratedFilesRenderItems(unique, generatedFilesItemCacheRef.current), singleResultMap: results };+ }return {items: reuseGeneratedFilesRenderItems(built.items, generatedFilesItemCacheRef.current),singleResultMap: built.singleResultMap,};}, [messages,+ historyView,+ historySnapshot,+ isSessionStreaming,taskUpdates,ghostCardSnapshot,historyLoaded,@@ -2757,13 +2795,13 @@ export function MessageStream({// isSessionStreaming 翻转(每 turn 一次)与 items 变化时重算,O(n) 单扫描。const allRenderItems = useMemo(() => {const grouped = insertForkOriginItem(- groupWorkRuns(ungroupedRenderItems, isSessionStreaming),+ historySnapshot?.ready ? ungroupedRenderItems : groupWorkRuns(ungroupedRenderItems, isSessionStreaming),forkOrigin,);return simplifiedBotConversation? simplifyBotRenderItems(grouped, isSessionStreaming): grouped;- }, [ungroupedRenderItems, isSessionStreaming, forkOrigin, simplifiedBotConversation]);+ }, [ungroupedRenderItems, isSessionStreaming, forkOrigin, simplifiedBotConversation, historySnapshot?.ready]);const botMessageTimeGroups = useMemo(() => {if (!simplifiedBotConversation) return new Map<string, number>();return collectBotMessageTimeGroups(@@ -5570,6 +5608,7 @@ export function MessageStream({isStreaming={item.isStreaming}startedAtMs={item.startedAtMs}childItems={childItems}+ deferred={item.deferred}/></div>);diff --git a/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx b/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsxindex f2a3a0db23..2078c74f8a 100644--- a/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx+++ b/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx@@ -103,6 +103,7 @@ export function collectLiveWorkActivities(}export interface WorkGroupBlockProps {+ deferred?: import('@cindy/maker-shared/message-window').DeferredHistoryWork;/** Stable persistence key:动作段 `work:<clientId>`,外层 `work:summary-<clientId>`. */blockId: string;/** Wall-clock span of the run; undefined when timestamps are unavailable. */@@ -268,6 +269,7 @@ function ExpandedWorkGroupChild({}export function WorkGroupBlock({+ deferred,blockId,durationMs,isStreaming = false,@@ -275,7 +277,8 @@ export function WorkGroupBlock({childItems,}: WorkGroupBlockProps) {const { t } = useTranslation();- const { expanded, setExpanded } = useExpandedBlockMemory(blockId);+ const { expanded: rememberedExpanded, setExpanded } = useExpandedBlockMemory(blockId);+ const expanded = deferred?.expanded ?? rememberedExpanded;const [elapsedMs, setElapsedMs] = useState(0);useEffect(() => {@@ -310,12 +313,12 @@ export function WorkGroupBlock({);// 运行中预览已经等于全部内容时,折叠/展开是视觉空操作 — 组头不提供交互。const canToggle =- !isStreaming+ !!deferred || !isStreaming|| hasBeyondPreviewChild|| recentActivities.length > MAX_LIVE_WORK_ACTIVITIES;const effectiveExpanded = expanded && canToggle;const isLivePreviewVisible =- isStreaming && !effectiveExpanded && liveActivities.length > 0;+ !deferred && isStreaming && !effectiveExpanded && liveActivities.length > 0;// 完成态只计算一次完整摘要;运行态保持折叠时走上面的反向 latest-five// 热路径,用户主动展开后才投影全部历史。const activityProjection = useMemo(@@ -329,10 +332,11 @@ export function WorkGroupBlock({// 外层完成态组展开成文字 + 内层动作组;内层动作组与运行态组复用本组件,// 展开后直接渲染 thinking /工具行,不再多套一层子卡摘要。const onToggle = useCallback(() => {+ if (deferred) { deferred.toggle(); return; }setExpanded((v) => !v);- }, [setExpanded]);+ }, [deferred, setExpanded]);- if (childItems.length === 0) return null;+ if (childItems.length === 0 && !deferred) return null;// durationMs === 0(同毫秒时间戳的极短 run)也显示时长 — formatDuration// 自带最小 1s 钳制;只有时间戳缺失(undefined)才退化为无时长文案。@@ -448,6 +452,12 @@ export function WorkGroupBlock({/></Fragment>))}+ {deferred?.loading && <Spinner size={14} />}+ {deferred?.failed && (+ <button type="button" onClick={deferred.retry} className="text-muted-foreground hover:text-foreground text-sm">+ {t('chat.errorBanner.retry')}+ </button>+ )}</div></Collapse></div>diff --git a/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts b/apps/desktop/src/renderer/components/chat/messageWorkGroups.tsindex 3e43c68cbd..6bceed317a 100644--- a/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts+++ b/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts@@ -92,6 +92,7 @@ interface WorkGroupRenderItem {type: 'work_group';key: string;children: WorkGroupChildItem[];+ deferred?: import('@cindy/maker-shared/message-window').DeferredHistoryWork;durationMs?: number;/** 当前是否是仍在执行的尾部动作段。完成态时间线始终 false。 */isStreaming: boolean;diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 659a22d89e..17df03e842 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -21,6 +21,7 @@* - User-initiated stopSession (NOT called on session switch anymore)*/+import { HistoryViewController, type HistoryViewPage, type HistoryDetailPage } from '@cindy/maker-shared/message-window';import type { CindyRegion } from '@cindy/maker-shared/brand-identity';import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';import {@@ -3424,6 +3425,8 @@ function _purgeSession(sessionId: string): void {cancelRemoteOptimisticSendsForSessionPurge(sessionId);clearWakeBridgeReconcileTimer(sessionId);cancelIdlePlanDiscovery(sessionId);+ getRemoteHistoryView(sessionId)?.setActive(false);+ remoteHistoryViews.delete(sessionId);sessions.delete(sessionId);localSentUserMessageIds.delete(sessionId);pendingLocalRetryIntents.delete(sessionId);@@ -3903,6 +3906,7 @@ function resolveGatewayRecoveryProviderId(}function enterView(sessionId: string): () => void {+ getRemoteHistoryView(sessionId)?.setActive(true);_activeViewSessions.set(sessionId, (_activeViewSessions.get(sessionId) ?? 0) + 1);_lastViewedAt.delete(sessionId);_ensureDemoteTimer();@@ -4006,6 +4010,7 @@ function leaveView(sessionId: string): void {return;}_activeViewSessions.delete(sessionId);+ getRemoteHistoryView(sessionId)?.setActive(false);cancelIdlePlanDiscovery(sessionId);_lastViewedAt.set(sessionId, Date.now());if (_pendingErrorClearOnLeave.has(sessionId)) {@@ -8433,6 +8438,10 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {// stall 看门狗信号:只用重会话流刷新 lastInboundEventAt。列表级轻量 activity/patch// 可能仍在持续抵达,但 maker:event 重 topic 已经断流;若这里也刷新会掩盖卡死。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();+ }switch (push.channel) {case 'maker:event':handleMakerEventRaw(push.payload, remoteIngress);@@ -10442,6 +10451,7 @@ function bumpMessagesEpoch(sessionId: string): void {* bumpMessagesEpoch。*/function invalidateMessageHistoryWindow(sessionId: string): void {+ getRemoteHistoryView(sessionId)?.reset();bumpMessagesEpoch(sessionId);resetSessionAutomaticHistoryLoadCompletion(sessionId);}@@ -10625,6 +10635,52 @@ function releaseCacheHydrationAfterFailure(sessionId: string): void {_cacheHydrateStarted.delete(sessionId);}+export type HistoryChatMessage = ChatMessage & { id: string; createdAt: string };+const remoteHistoryViews = new Map<string, HistoryViewController<HistoryChatMessage>>();+export function getRemoteHistoryView(sessionId: string) { return remoteHistoryViews.get(sessionId); }+function createRemoteHistoryView(sessionId: string) {+ const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);+ if (!deviceId) return undefined;+ const existing = remoteHistoryViews.get(sessionId);+ if (existing) return existing;+ const owner = getDataOwnerGeneration();+ const mapRows = (rows: Message[]): HistoryChatMessage[] => mapServerMessages(rows).map((row) => ({+ ...row, id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',+ }));+ const call = async <T,>(channel: string, args: unknown[]): Promise<T> => {+ const value = await window.electronAPI.deviceLink.invoke(deviceId, channel, args);+ if (!isDataOwnerGenerationCurrent(owner) || remoteProjectsStore.getSessionDeviceId(sessionId) !== deviceId) throw new Error('History source changed');+ return value as T;+ };+ const view = new HistoryViewController<HistoryChatMessage>({+ page: async (before) => {+ const page = await call<HistoryViewPage<Message>>('local-db:messages:view', [sessionId, { before }]);+ if (page == null) throw new Error('[CHANNEL_NOT_ALLOWED] History view is unavailable');+ return { ...page, items: page.items.map((item) => item.type === 'work' ? item : { ...item, messages: mapRows(item.messages) }) };+ },+ details: async (ref, after) => {+ const page = await call<HistoryDetailPage<Message>>('local-db:messages:work-details', [sessionId, ref, { after }]);+ return { ...page, messages: mapRows(page.messages) };+ },+ expanded: (refs) => call<void>('local-db:messages:view-intent', [sessionId, refs]),+ });+ remoteHistoryViews.set(sessionId, view);+ view.subscribe(() => {+ if (remoteHistoryViews.get(sessionId) !== view || !sessions.has(sessionId)) return;+ const snapshot = view.getSnapshot();+ if (!snapshot.ready) return;+ const available = snapshot.items.flatMap((item) => item.type === 'messages' ? item.messages : []);+ for (const detail of snapshot.details.values()) available.push(...detail.messages);+ setState(sessionId, (state) => ({ ...state, historyLoaded: true,+ messages: mergeMessages(available, state.messages, { addOnly: true }),+ hasMoreMessages: snapshot.hasMore, isLoadingMore: snapshot.loading,+ oldestMessageId: snapshot.nextCursor,+ historyWindowHasIsland: false,+ }));+ });+ return view;+}+function ensureInitialMessages(sessionId: string): void {const state = getOrCreateState(sessionId);requestInputProjection(sessionId);@@ -10749,8 +10805,24 @@ function ensureInitialMessages(sessionId: string): void {}});- listMessagesFor(sessionId)+ (async () => {+ const view = createRemoteHistoryView(sessionId);+ if (view) {+ await view.refresh();+ const snapshot = view.getSnapshot();+ if (!snapshot.error && snapshot.ready) {+ releaseHistoryFetchIfCurrent(sessionId, historyFetchToken);+ void reconcilePendingInteractions(sessionId);+ return null;+ }+ if (!/CHANNEL_NOT_ALLOWED|not registered|No handler/i.test(String(snapshot.error))) throw snapshot.error;+ view.setActive(false);+ remoteHistoryViews.delete(sessionId);+ }+ return listMessagesFor(sessionId);+ })().then(async (existing) => {+ if (existing === null) return;if (!isCurrentHistoryFetch(sessionId,@@ -11071,6 +11143,7 @@ function cancelIdlePlanDiscovery(sessionId: string): void {}function scheduleIdlePlanDiscoveryIfNeeded(sessionId: string): void {+ if (getRemoteHistoryView(sessionId)) return;if (!_activeViewSessions.has(sessionId)) return;const state = sessions.get(sessionId);if (!state?.historyLoaded || state.isLoadingMore || !state.hasMoreMessages) return;@@ -11089,6 +11162,7 @@ function scheduleIdlePlanDiscoveryIfNeeded(sessionId: string): void {}function loadOneOlderPageForPlanDiscovery(sessionId: string): Promise<boolean> {+ if (getRemoteHistoryView(sessionId)) return Promise.resolve(false);if (!_activeViewSessions.has(sessionId)) return Promise.resolve(false);const state = sessions.get(sessionId);if (!state?.historyLoaded || state.isLoadingMore || !state.hasMoreMessages) {@@ -11400,6 +11474,11 @@ const _remoteReconcileInFlight = new Map<>();function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean }): Promise<boolean> {+ const view = getRemoteHistoryView(sessionId);+ if (view?.getSnapshot().ready) return Promise.all([view.refresh(), reconcilePendingInteractions(sessionId)]).then(() => {+ if (view.getSnapshot().error) throw view.getSnapshot().error;+ return true;+ });// 返回完成 promise 供调用方需要时等待;既有调用方均按 fire-and-forget 使用。if (!sessionId || !isRemoteSession(sessionId)) return Promise.resolve(false);const inFlight = _remoteReconcileInFlight.get(sessionId);@@ -11712,6 +11791,11 @@ function loadOlderMessages(automatic = false,maxPages = MAX_LOAD_OLDER_PAGES,): Promise<boolean> {+ const view = getRemoteHistoryView(sessionId);+ if (view?.getSnapshot().ready) return view.refresh(true).then(() => {+ if (view.getSnapshot().error) throw view.getSnapshot().error;+ return true;+ });const state = getOrCreateState(sessionId);if (state.isLoadingMore || !state.hasMoreMessages) return Promise.resolve(false);@@ -12290,7 +12374,12 @@ async function loadAroundMessage(// around 行会被当成新代际 merge 回窗口。const epochAtStart = _messagesEpoch.get(sessionId) ?? 0;// 按来源路由:远程会话经隧道 local-db:messages:around(直连本机会查控制端空库,跳转必失败)。- const rows = await aroundMessagesFor(sessionId, messageId, opts);+ const view = getRemoteHistoryView(sessionId);+ const rows = await aroundMessagesFor(sessionId, messageId, view?.getSnapshot().ready ? { radius: 0 } : opts);+ if (view?.getSnapshot().ready) {+ const target = rows.find((row) => row.id === messageId);+ return target ? view.locate(target.clientId, target.createdAt) : null;+ }if (rows.length === 0) return null;const mapped = mapServerMessages(rows);@@ -12355,7 +12444,12 @@ async function loadAroundMessageClientId(): Promise<ChatMessage | null> {// 同 loadAroundMessage:epoch 在 around 请求之前快照,覆盖该请求自身的竞态窗口。const epochAtStart = _messagesEpoch.get(sessionId) ?? 0;- const rows = await aroundMessagesByClientIdFor(sessionId, clientId, opts);+ const view = getRemoteHistoryView(sessionId);+ const rows = await aroundMessagesByClientIdFor(sessionId, clientId, view?.getSnapshot().ready ? { radius: 0 } : opts);+ if (view?.getSnapshot().ready) {+ const target = rows.find((row) => row.clientId === clientId);+ return target ? view.locate(clientId, target.createdAt) : null;+ }if (rows.length === 0) return null;const mapped = mapServerMessages(rows);diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 82b27d9e3e..1e139033a4 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -109,6 +109,8 @@ import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';import { shouldClearOperationErrorAfterSync, type SessionOperationError } from '@/session/sessionSyncErrorRecovery';import { createTransientTopicSubscriptionCoordinator } from '@/device-link/transientTopicSubscription';import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';+import { findRemoteHistoryView, useRemoteHistoryView } from '@/session/remoteHistoryView';+import { renderHistoryView } from '@cindy/maker-shared/message-window';import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';import { InteractionPanel, type MobilePlanViewerState } from '@/session/InteractionPanel';@@ -488,6 +490,8 @@ import {} from '@/session/historyWindowGap';import {insertMobileForkOriginItem,+ buildMobileMessageRenderItems,+ type MobileWorkChildItem,type MobileMessageRenderItem,} from '@/session/messageRenderModel';import { reconcileMobileMessageRenderItems } from '@/session/messageRenderReconcile';@@ -961,6 +965,7 @@ export default function SessionScreen() {}return () => {messageScreenFocusedRef.current = false;+ findRemoteHistoryView(deviceId, sessionId)?.setActive(false);const authority = messageAuthorityRef.current;messageAuthorityRef.current = null;if (authority) {@@ -974,6 +979,7 @@ export default function SessionScreen() {const active = nextState === 'active';messageAppActiveRef.current = active;if (!active) {+ findRemoteHistoryView(deviceId, sessionId)?.setActive(false);const authority = messageAuthorityRef.current;messageAuthorityRef.current = null;if (authority) {@@ -983,6 +989,7 @@ export default function SessionScreen() {}if (!messageScreenFocusedRef.current || messageAuthorityRef.current) return;messageAuthorityRef.current = remoteSessionStore.enterSessionMessageDetail(sessionId);+ findRemoteHistoryView(deviceId, sessionId)?.setActive(true);setMessageReloadRevision((value) => value + 1);});return () => subscription.remove();@@ -1006,8 +1013,26 @@ export default function SessionScreen() {const revokedDevices = useRevokedDevices();const unresponsiveDevices = useUnresponsiveDevices();const maker = useMobileMakerTransport(deviceId);+ const historyView = useRemoteHistoryView(deviceId, sessionId, maker,+ () => messageScreenFocusedRef.current && messageAppActiveRef.current);+ useEffect(() => {+ if (messageScreenFocusedRef.current && messageAppActiveRef.current) historyView.view.setActive(true);+ }, [connectionEpoch, messageReloadRevision, historyView.view]);const sessions = useRemoteSessions();- const messages = useSessionMessages(sessionId, deviceId);+ useEffect(() => {+ if (messageReloadRevision > 0) historyView.view.reset();+ }, [messageReloadRevision, historyView.view]);+ const rawMessages = useSessionMessages(sessionId, deviceId);+ const messages = useMemo(() => {+ if (!historyView.snapshot.ready) return rawMessages;+ const available = historyView.snapshot.items.flatMap((item) => item.type === 'messages' ? item.messages : []);+ for (const detail of historyView.snapshot.details.values()) available.push(...detail.messages);+ const byId = new Map(available.map((row) => [row.clientId, row]));+ for (const row of rawMessages) {+ if (row.agentMeta?.isStreaming === true) byId.set(row.clientId, row);+ }+ return [...byId.values()].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || (a.rowid ?? 0) - (b.rowid ?? 0));+ }, [rawMessages, historyView.snapshot]);const messageStructureToken = remoteSessionStore.getSessionMessageStructureToken(sessionId);const messageStructureChangedIndexes = remoteSessionStore.getSessionMessageStructureChangedIndexes(sessionId);@@ -2102,7 +2127,7 @@ export default function SessionScreen() {remoteSessionStore.subscribe,() => remoteSessionStore.getSessionLiveActivity(sessionId)?.attention === true,);- const hasRenderedMessages = messages.length > 0;+ const hasRenderedMessages = historyView.snapshot.ready ? historyView.snapshot.items.length > 0 : messages.length > 0;useRemoteResourceSession(deviceId, deviceName, sessionId,currentSession?.id === sessionId && hasRenderedMessages&& readAckSyncedKey === `${sessionId}:${connectionEpoch}`@@ -2309,7 +2334,7 @@ export default function SessionScreen() {const syncingWhileEmpty = shouldSuppressEmptyMessageState({loading,showSyncingShell,- messageCount: messages.length,+ messageCount: historyView.snapshot.ready ? historyView.snapshot.items.length : messages.length,hasSyncedThisOpen: lastSyncedAt !== null,remoteUnavailable: !!remoteUnavailableReason,});@@ -3321,13 +3346,23 @@ export default function SessionScreen() {const isCurrent = () => !syncRun.isStale() && messageAuthorityCurrent();const pushRefresh = notificationResponse !== null&& syncedNotificationResponseRef.current !== notificationResponse;+ let usedHistoryView = false;const messageRead = syncSessionMessageWindow({readMetadata: () => retryRead(fetchSessionMetadata),isReopen,storedSession: storedSessionAtStart,- eager: !isReopen || pushRefresh,+ eager: !isReopen || pushRefresh || historyView.snapshot.ready,isWindowSynced: (sessionMeta) => remoteSessionStore.isSessionMessageWindowSynced(sessionId, sessionMeta),- readLatest: () => retryRead(() => listMessagesWithPayloadRetry(+ readLatest: async () => {+ if (options.replaceMessages && historyView.view.getSnapshot().ready) historyView.view.reset();+ await historyView.view.refresh();+ const viewState = historyView.view.getSnapshot();+ if (!viewState.error && viewState.ready) {+ usedHistoryView = true;+ return { messages: [], limit: 20, reducedByPayloadTooLarge: false };+ }+ if (!/CHANNEL_NOT_ALLOWED|not registered|No handler/i.test(String(viewState.error))) throw viewState.error;+ return retryRead(() => listMessagesWithPayloadRetry((limit) => runSessionMessagesSnapshotSingleFlight(snapshotScope,limit,@@ -3335,9 +3370,11 @@ export default function SessionScreen() {() => maker.listMessages(sessionId, { limit }),),isReopen ? REOPEN_MESSAGE_WINDOW_LIMITS : undefined,- )),+ ));+ },isCurrent,commitMessages: (history) => {+ if (usedHistoryView) { messageWindowReconciledRef.current = true; return; }const historyPage: RemoteMessage[] = Array.isArray(history.messages) ? history.messages : [];const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);if (options.replaceMessages) {@@ -3353,7 +3390,7 @@ export default function SessionScreen() {setHasOlderMessages(moreBeyondWindow);},commit: (sessionMeta, history) => {- if (history !== null) {+ if (history !== null && !usedHistoryView) {remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);if (pushRefresh) syncedNotificationResponseRef.current = notificationResponse;}@@ -4120,8 +4157,8 @@ export default function SessionScreen() {const projectedMessages = projectedMessageWindow.projected;const projectedMessageStructureChangedIndexes = projectedMessageWindow.changedIndexes;const oldestLoadedMessageCursor = useMemo(- () => oldestMessageCursor(latestMessagesRef.current),- [messageStructureToken],+ () => historyView.snapshot.ready ? historyView.snapshot.nextCursor : oldestMessageCursor(latestMessagesRef.current),+ [messageStructureToken, historyView.snapshot],);const previousRenderItemsRef = useRef<{sessionId: string;@@ -4145,12 +4182,25 @@ export default function SessionScreen() {prefixCache: streamingRenderPrefixRef,taskUpdates,});+ const historyItems = historyView.snapshot.ready ? renderHistoryView({+ view: historyView.view, snapshot: historyView.snapshot, liveMessages: projectedMessages,+ isLive: (row) => row.agentMeta?.isStreaming === true,+ streaming: isMessageListStreaming,+ build: (rows, streaming) => buildMobileMessageRenderItems(rows, { isSessionStreaming: streaming, sessionId }, taskUpdates),+ work: (summary, details, deferred): MobileMessageRenderItem => ({+ type: 'work_group', key: summary.key, deferred,+ isStreaming: summary.isStreaming, startedAtMs: summary.startedAtMs,+ durationMs: Math.max(0, summary.endedAtMs - summary.startedAtMs),+ children: details.flatMap((item): MobileWorkChildItem[] => item.type === 'work_group' ? item.children+ : ['message', 'thinking', 'tool_group', 'agent_task', 'todo'].includes(item.type) ? [item as MobileWorkChildItem] : []),+ }),+ }) : builtWindow.items;let items = insertMobileForkOriginItem(// 孤儿 agent_task 兜底用 maker status 驱动的权威 turn 边界 gate,与 store 的// turn-start 清理同源闭环——渲染开启时 map 必已清过 stale。不用 isSessionStreaming// (含本地 sending / canStopQueue,发送→status 间隙会闪现残留),也不用// remoteSessionRunning(activity 推送 / 活跃快照会先置 true,重连场景渲染先于清理)。- builtWindow.items,+ historyItems,forkOrigin,);if (errorTailClientId) {@@ -4162,10 +4212,10 @@ export default function SessionScreen() {? previousRenderItemsRef.current: null;const previous = previousRenderState?.items ?? [];- const committedPrefix = forkOrigin || errorTailClientId+ const committedPrefix = historyView.snapshot.ready || forkOrigin || errorTailClientId? null: builtWindow.prefix;- const stablePrefixItemCount = forkOrigin || errorTailClientId+ const stablePrefixItemCount = historyView.snapshot.ready || forkOrigin || errorTailClientId? 0: committedMobileStreamingPrefixItemCount(builtWindow,@@ -4185,12 +4235,12 @@ export default function SessionScreen() {stablePrefixItemCount,};},- [errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, projectedMessages, projectedMessageStructureChangedIndexes, sessionId, taskUpdates],+ [historyView.snapshot, historyView.view, errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, projectedMessages, projectedMessageStructureChangedIndexes, sessionId, taskUpdates],);const renderItems = renderWindow.items;const renderItemsStructureKey = useMemo(() => ({}),- [errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, sessionId, taskUpdates],+ [historyView.snapshot, errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, sessionId, taskUpdates],);// Reconciliation must only use committed rows. Unlike the prefix cache above, a speculative// render-item baseline could leak rows from an abandoned render and destabilize tail memoization.@@ -4210,7 +4260,7 @@ export default function SessionScreen() {}, [renderItems, renderWindow.prefix, sessionId]);// 后台静默刷新:仅在首次加载、还没有任何内容(messages 为空)时显示"正在同步";已有内容// (重开已看过的会话,messages 还在内存)时后台对账一律静默,不再弹同步提示打扰用户。- const showSyncingIndicator = loading && messages.length === 0;+ const showSyncingIndicator = loading && !hasRenderedMessages;const diffCount = renderWindow.diffCount;const searchHits = useMemo(() => searchOpen && searchQuery.trim()@@ -4263,9 +4313,9 @@ export default function SessionScreen() {};const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);void withTransientRemoteRetry(() =>- maker.aroundMessagesByClientId(sessionId, routeFocusClientId, { radius: 60 }),+ maker.aroundMessagesByClientId(sessionId, routeFocusClientId, { radius: historyView.snapshot.ready ? 0 : 60 }),)- .then((list) => {+ .then(async (list) => {if (cancelled|| !remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)@@ -4273,6 +4323,12 @@ export default function SessionScreen() {releasePendingRouteFocusLookup();return;}+ if (historyView.view.getSnapshot().ready) {+ const target = list.find((row) => row.clientId === routeFocusClientId);+ const found = target ? await historyView.view.locate(target.clientId, target.createdAt) : null;+ if (!found && !cancelled) setError(t('session.screen.locateMessageNotFound'));+ return;+ }remoteSessionStore.mergeMessages(sessionId,Array.isArray(list) ? list : [],@@ -4444,6 +4500,12 @@ export default function SessionScreen() {const loadEarlierMessages = useCallback(async () => {if (isScheduleDetail) return;+ if (historyView.snapshot.ready) {+ await historyView.view.refresh(true);+ const error = historyView.view.getSnapshot().error;+ setHistoryError(error ? formatRemoteError(error) : null);+ return;+ }if (!deviceId || !sessionId || loadingEarlier || historyRequestInFlightRef.current !== null || !hasOlderMessages) return;const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);if (!remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) return;@@ -4486,7 +4548,7 @@ export default function SessionScreen() {setLoadingEarlier(false);}}- }, [abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);+ }, [historyView.snapshot.ready, historyView.view, abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);const loadToolInput = useCallback(async (ref: MobileToolInputProjection,@@ -4553,6 +4615,7 @@ export default function SessionScreen() {// 完成前就基于旧缓存快照动手 —— 而空洞 key 在请求前已记为已考察,那一处从此不再重试// (#1210 review)。readAckSyncedKey 正是「本会话在当前连接代完成过整窗同步」这个判据的// 既有单一来源(见它的声明处),这里直接复用。+ if (historyView.snapshot.ready) return;if (readAckSyncedKey !== `${sessionId}:${connectionEpoch}`) return;// 与「加载更早」互斥:两者都按 before 游标翻页,同时跑只会让窗口反复 merge、白拉页。// 飞行判定只挡**同一会话**,别的会话残留的那一轮不连坐(见 backfillInFlightRun)。@@ -9109,7 +9172,7 @@ export default function SessionScreen() {topOverlayHeight={topOverlayHeight}busyAction={messageActionBusy?.kind ?? null}busyClientId={messageActionBusy?.clientId ?? null}- canLoadEarlier={hasOlderMessages && messages.length > 0 && !isScheduleDetail}+ canLoadEarlier={(historyView.snapshot.ready ? historyView.snapshot.hasMore : hasOlderMessages && messages.length > 0) && !isScheduleDetail}emptyTestID="session.messageList.empty"focusedItemKey={focusedMessageItemKey ?? null}focusedRequestKey={focusedMessageRequestKey}@@ -9123,7 +9186,7 @@ export default function SessionScreen() {items={messageListItems}itemsStructureKey={messageListStructureKey}pendingSend={pendingSendActions}- loadingEarlier={loadingEarlier}+ loadingEarlier={historyView.snapshot.ready ? historyView.snapshot.loading : loadingEarlier}loadEarlierProgressKey={oldestLoadedMessageCursor}onCopyMessageLink={copyMessageLink}onAddMessageToComposer={canUseComposer ? addMessageToComposer : undefined}@@ -9337,7 +9400,7 @@ export default function SessionScreen() {紧接着消息落屏时这条又要重排一次。等有内容了再显示活动条。判据必须带 messageCount:syncingWhileEmpty 只要 loading 就为真,而收口后还会再来几轮 load(实测日志),只看它会让已有消息的会话反复熄灭活动条。 */}- {showComposerActivity && !(syncingWhileEmpty && messages.length === 0) ? (+ {showComposerActivity && !(syncingWhileEmpty && !hasRenderedMessages) ? (<Viewstyle={[styles.composerActivityFrame,diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.tsindex e870b6fc25..1761ec964b 100644--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts@@ -35,6 +35,9 @@ describe('mobile maker transport', () => {'local-db:sessions:ack-interrupted','maker:regenerate-title','local-db:messages:list',+ 'local-db:messages:view',+ 'local-db:messages:work-details',+ 'local-db:messages:view-intent','local-db:messages:around','local-db:messages:around-client-id','maker:send',diff --git a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.tsindex 1387b9eb11..542fccf0c9 100644--- a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts@@ -26,7 +26,7 @@ describe('mobile session header desktop-first surface', () => {expect(source).toContain("if (!session) return syncing ? i18n.t('session.screen.syncingSession') : null;\n if (syncing) return i18n.t('session.screen.syncing');");// 后台静默刷新:同步提示由 showSyncingIndicator gate —— 仅首次加载、还没有任何内容时显示,// 已有 messages(重开已看过的会话)时后台对账静默,不再弹"正在同步"。- expect(source).toContain('const showSyncingIndicator = loading && messages.length === 0;');+ expect(source).toContain('const showSyncingIndicator = loading && !hasRenderedMessages;');expect(source).toContain("if (queuePaused) return i18n.t('session.screen.queuePausedNotice');\n return null;");expect(source).toContain('attention ? (');});diff --git a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.tsindex 45fc9d8bfb..27e09ba1a6 100644--- a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts+++ b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts@@ -84,7 +84,7 @@ describe('任务消息内存治理页面接线', () => {it('schedule 关闭翻历史入口,页面工作租约覆盖发送与附件状态', () => {expect(screen).toContain('if (isScheduleDetail) return;');expect(screen).toContain('hasOlderMessages && !isScheduleDetail');- expect(screen).toContain('canLoadEarlier={hasOlderMessages && messages.length > 0 && !isScheduleDetail}');+ expect(screen).toContain('canLoadEarlier={(historyView.snapshot.ready ? historyView.snapshot.hasMore : hasOlderMessages && messages.length > 0) && !isScheduleDetail}');expect(screen).toContain('remoteSessionStore.acquireSessionMessageWork(sessionId, pageHasMessageWork)');expect(screen).toContain('remoteSessionStore.acquireSessionMessageWork(item.sessionId, true)');expect(screen).toContain('remoteSessionStore.acquireSessionMessageWork(sessionId, true)');diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.tsindex 5830095558..3cf040e5f3 100644--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts@@ -79,6 +79,7 @@ function fixture(reopen = false) {};const bindings = {deviceId: 'd1', deviceName: 'test', sessionId: 's1',+ historyView: { snapshot: { ready: false }, view: { refresh: async () => undefined, getSnapshot: (): { ready: boolean; error: Error | null } => ({ ready: false, error: new Error('[CHANNEL_NOT_ALLOWED] legacy host') }) } },remoteSessionStore: store, maker, shouldBlockSessionSync: () => false,readAckEpochRef: { current: 1 }, readAckGateGenRef: { current: 1 },sessionSubscriptionIdentityRef: { current: JSON.stringify(['d1', 's1', 1]) },@@ -124,6 +125,17 @@ function fixture(reopen = false) {}describe('production session recovery callbacks', () => {+ it('accepts a history view without certifying sparse rows as a complete raw window', async () => {+ const f = fixture();+ f.bindings.historyView.view.getSnapshot = () => ({ ready: true, error: null });+ await f.sync();+ expect(f.maker.listMessages).not.toHaveBeenCalled();+ expect(f.store.setMessages).not.toHaveBeenCalled();+ expect(f.store.setLatestMessageWindow).not.toHaveBeenCalled();+ expect(f.store.markSessionMessagesSynced).not.toHaveBeenCalled();+ expect(f.state.synced).not.toBeNull();+ });+it('routes the visible history retry to pagination rather than full sync', () => {const screen = source.getFullText().replace(/\r\n/g, '\n');expect(screen).toContain('const bannerError = connectionRecoveryError ?? historyError;');diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex b8df60a8d2..8c68a40eeb 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -1,4 +1,5 @@import Constants from 'expo-constants';+import { findRemoteHistoryView } from '@/session/remoteHistoryView';import { createBackgroundConnection } from './backgroundConnection';import { createRecoveryDiagnostics, settleMeasuredSnapshot, type RecoveryPhase } from './recoveryDiagnostics';import { confirmTrackedSubscription, SubscriptionAcknowledgements } from './subscriptionAcknowledgements';@@ -1383,7 +1384,14 @@ export function routeFrame(env: Envelope, handlers: {);return;}+ const historySessionId = (push.payload as { sessionId?: unknown } | null)?.sessionId;+ const historyView = typeof historySessionId === 'string' ? findRemoteHistoryView(env.src, historySessionId) : undefined;+ if (push.channel === 'maker:history-view-changed') {+ historyView?.invalidate();+ return;+ }remoteSessionStore.applyRemotePush(env.src, push.channel, push.payload);+ if (historyView?.getSnapshot().ready && (push.channel === 'local-db:messages:created' || push.channel === 'maker:status-changed')) historyView.invalidate();}/** provider revision 后并行重拉所有 agent 的能力;旧代或异常结果都不触碰当前页面。 */@@ -1500,8 +1508,8 @@ async function rebuildSessionSnapshot(}return false;};- const [history, pending, projection, goal] = await Promise.all([- measured('history', runSessionMessagesSnapshotSingleFlight(+ const historyView = findRemoteHistoryView(deviceId, sessionId);+ const readRawHistory = () => runSessionMessagesSnapshotSingleFlight(snapshotScope,RECONNECT_MESSAGE_WINDOW_LIMIT,messageAuthorityAtRequestStart@@ -1518,7 +1526,20 @@ async function rebuildSessionSnapshot([sessionId, { limit: RECONNECT_MESSAGE_WINDOW_LIMIT }],sendOpts,),- ), applyHistory),+ );+ const readHistory = async () => {+ if (historyView) {+ if (!historyView.isActive()) return false;+ await historyView.refresh();+ const snapshot = historyView.getSnapshot();+ if (!snapshot.error && snapshot.ready) return isCurrent() && historyView.isActive()+ && findRemoteHistoryView(deviceId, sessionId) === historyView;+ if (!/CHANNEL_NOT_ALLOWED|not registered|No handler/i.test(String(snapshot.error))) throw snapshot.error;+ }+ return applyHistory(await readRawHistory());+ };+ const [history, pending, projection, goal] = await Promise.all([+ measured('history', readHistory(), (applied) => applied),measured('pending', runSessionPendingInteractionsSnapshotSingleFlight(snapshotScope,pendingSnapshotAtRequestStart,diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex 5668ed6e9f..34764cc611 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -21,6 +21,7 @@ import {MOBILE_REMOTE_INVOKE_CHANNELS,} from '@cindy/maker-shared/device-link-contract';import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';+import type { HistoryViewPage, HistoryDetailPage, HistoryWorkSummary } from '@cindy/maker-shared/message-window';import type {MobileGoalLimitsInput,MobileGoalStatusPayload,@@ -415,6 +416,9 @@ export interface MobileMakerTransport {*/regenerateSessionTitle(sessionId: string): Promise<{ title: string | null }>;listMessages(sessionId: string, opts?: MessageListOptions): Promise<RemoteMessage[]>;+ readHistoryView(sessionId: string, before?: string): Promise<HistoryViewPage<RemoteMessage>>;+ readWorkDetails(sessionId: string, ref: HistoryWorkSummary, after?: string): Promise<HistoryDetailPage<RemoteMessage>>;+ setHistoryExpanded(sessionId: string, refs: readonly HistoryWorkSummary[]): Promise<void>;aroundMessages(sessionId: string, messageId: string, opts?: MessageAroundOptions): Promise<RemoteMessage[]>;aroundMessagesByClientId(sessionId: string, clientId: string, opts?: MessageAroundOptions): Promise<RemoteMessage[]>;send(@@ -681,6 +685,9 @@ export function createMobileMakerTransport({ackInterruptedTurn: (sessionId) => call('local-db:sessions:ack-interrupted', [sessionId]),regenerateSessionTitle: (sessionId) => call('maker:regenerate-title', [{ sessionId }]),listMessages: (sessionId, opts) => call('local-db:messages:list', [sessionId, opts]),+ readHistoryView: (sessionId, before) => call('local-db:messages:view', [sessionId, { before }]),+ readWorkDetails: (sessionId, ref, after) => call('local-db:messages:work-details', [sessionId, ref, { after }]),+ setHistoryExpanded: (sessionId, refs) => call('local-db:messages:view-intent', [sessionId, refs]),aroundMessages: (sessionId, messageId, opts) =>call('local-db:messages:around', [sessionId, messageId, opts]),aroundMessagesByClientId: (sessionId, clientId, opts) =>diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 8bf841d559..5a827bb913 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -4102,7 +4102,8 @@ function WorkGroupCard({);const header = presentation.header;const isStreaming = item.isStreaming === true;- const [expanded, toggleExpanded] = useFoldableExpandedState(item.key, false);+ const [rememberedExpanded, toggleExpanded] = useFoldableExpandedState(item.key, false);+ const expanded = item.deferred?.expanded ?? rememberedExpanded;const layout = useMemo(() => buildMessageHierarchyLayout({screenWidth: actions.screenWidth,summaryCount: header.summaryCount,@@ -4143,7 +4144,7 @@ function WorkGroupCard({presentation.title,explorationSummary,].filter(Boolean).join(' · ');- const onToggle = toggleExpanded;+ const onToggle = item.deferred?.toggle ?? toggleExpanded;return (<FoldablePanelchevronPosition={header.chevronPosition}@@ -4165,6 +4166,12 @@ function WorkGroupCard({{expanded ? (<Rail layout={layout}><View style={styles.workGroupStack}>+ {item.deferred?.loading && <CompactActivityIndicator color={colors.textTertiary} size={header.iconSize} />}+ {item.deferred?.failed && (+ <Pressable onPress={item.deferred.retry} accessibilityRole="button">+ <Text style={{ color: colors.textSecondary }}>{t('message.renderer.retryPreview')}</Text>+ </Pressable>+ )}{item.children.map((child) => {if (child.type === 'thinking') {return <ExpandedWorkThinkingRow key={child.key} item={child} />;diff --git a/apps/mobile/src/session/remoteHistoryView.ts b/apps/mobile/src/session/remoteHistoryView.tsnew file mode 100644index 0000000000..a906b5296c--- /dev/null+++ b/apps/mobile/src/session/remoteHistoryView.ts@@ -0,0 +1,33 @@+import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';+import { HistoryViewController } from '@cindy/maker-shared/message-window';+import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';+import type { RemoteMessage } from './types';++const views = new Map<string, HistoryViewController<RemoteMessage>>();+const keyFor = (deviceId: string, sessionId: string) => JSON.stringify([deviceId, sessionId]);++export function findRemoteHistoryView(deviceId: string, sessionId: string) {+ return views.get(keyFor(deviceId, sessionId));+}++export function useRemoteHistoryView(deviceId: string | null | undefined, sessionId: string, maker: MobileMakerTransport, isActive: () => boolean) {+ const activeRef = useRef(isActive);+ activeRef.current = isActive;+ const view = useMemo(() => new HistoryViewController<RemoteMessage>({+ page: (before) => maker.readHistoryView(sessionId, before),+ details: (ref, after) => maker.readWorkDetails(sessionId, ref, after),+ expanded: (refs) => maker.setHistoryExpanded(sessionId, refs),+ }), [maker, sessionId]);+ const snapshot = useSyncExternalStore(view.subscribe, view.getSnapshot, view.getSnapshot);+ useEffect(() => {+ if (!deviceId) return;+ const key = keyFor(deviceId, sessionId);+ views.set(key, view);+ view.setActive(activeRef.current());+ return () => {+ if (views.get(key) === view) views.delete(key);+ view.setActive(false);+ };+ }, [deviceId, sessionId, view]);+ return { view, snapshot };+}diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex a10dc97dfc..bf3fde1f21 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -264,6 +264,10 @@ const CORE_INVOKE_CHANNELS: readonly string[] = ['local-db:conversations:search',DL_HISTORY_MESSAGES_CHANNEL,'local-db:messages:list',+ // Read-only visible history and recoverable work ranges; same session authorization as list.+ 'local-db:messages:view',+ 'local-db:messages:work-details',+ 'local-db:messages:view-intent',// 会话内搜索跳转定位(loadAroundMessage):只读,与 messages:list 同安全级。'local-db:messages:around',// 以 message clientId 定位上下文,供移动端轻量跳转 / fork 来源定位;只读,与 messages:around 同安全级。@@ -573,6 +577,7 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set(['maker:bot-direct-message:changed',// maker-ipc MAKER_PUSH'maker:event',+ 'maker:history-view-changed',// 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/device-link/src/client.ts b/packages/device-link/src/client.tsindex 34f71ebf37..8e2a452a95 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -4414,6 +4414,9 @@ const UNLINKED_LEGACY_INVOKE_CHANNELS = new Set(['local-db:sessions:get','local-db:history:messages','local-db:messages:list',+ 'local-db:messages:view',+ 'local-db:messages:work-details',+ 'local-db:messages:view-intent','local-db:messages:around','local-db:messages:around-client-id','local-db:messages:estimatedSessionValue',diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.tsnew file mode 100644index 0000000000..6ce4b27bb9--- /dev/null+++ b/packages/maker-shared/src/__tests__/historyView.test.ts@@ -0,0 +1,145 @@+import { describe, expect, it } from 'vitest';+import { projectHistoryView } from '../historyViewProjection.js';+import { readHistoryWorkDetails, type HistoryMessageSource } from '../historyView.js';++function row(id: number, role: string, content: unknown): HistoryMessageSource {+ return { id: String(id), clientId: `c${id}`, role, content,+ createdAt: new Date(1_700_000_000_000 + id * 1000).toISOString() };+}++describe('history reading projection', () => {+ it('reaches the preceding visible conversation without transmitting hundreds of hidden bodies', () => {+ const rows = [row(0, 'user', 'Inspect this problem')];+ for (let id = 1; id <= 600; id++) rows.push(row(id, 'thinking', 'detail '.repeat(1000)));+ rows.push(row(601, 'assistant', 'The result'));+ const projected = projectHistoryView(rows, false);+ expect(projected.map((item) => item.type)).toEqual(['messages', 'work', 'messages']);+ expect(projected[1]).toMatchObject({ summary: {+ firstMessageId: '1', lastMessageId: '600', messageCount: 600,+ } });+ expect(JSON.stringify(projected).length).toBeLessThan(JSON.stringify(rows).length / 100);+ expect(rows[1].content).toBe('detail '.repeat(1000));+ });++ it('keeps delivery prose, interaction tools and reference-bearing results outside summaries', () => {+ const rows = [row(0, 'user', 'Work'), row(1, 'thinking', 'reasoning'),+ row(2, 'assistant', '# Deliverable\nA useful result'),+ { ...row(3, 'tool_use', { toolName: 'AskUserQuestion', input: {} }), toolUseId: 'ask' },+ { ...row(4, 'tool_use', { toolName: 'Read', input: {} }), toolUseId: 'media' },+ { ...row(5, 'tool_result', 'cindy-media://blobs/example.png'), toolUseId: 'media' },+ row(6, 'assistant', 'Done')];+ const projected = projectHistoryView(rows, false);+ const visible = projected.flatMap((item) => item.type === 'messages' ? item.messages : []);+ expect(visible.map((item) => item.id)).toEqual(['0', '2', '3', '4', '5', '6']);+ });++ it('keeps sealed history completed when a new active tail arrives before its user row', () => {+ const rows = [row(0, 'thinking', 'old'),+ { ...row(1, 'assistant', 'Done'), agentMeta: { turnCompleted: true } },+ row(2, 'thinking', 'new')];+ expect(projectHistoryView(rows, true).filter((item) => item.type === 'work')+ .map((item) => item.summary.isStreaming)).toEqual([false, true]);+ });+});++describe('automatic process detail reading', () => {+ it('automatically reads all pages without a user pagination action', async () => {+ const cursors: Array<string | null> = [];+ const received: string[] = [];+ await readHistoryWorkDetails({+ isCurrent: () => true,+ readPage: async (cursor) => {+ cursors.push(cursor);+ const index = cursor === null ? 1 : 2;+ return { version: 1, messages: [row(index, 'thinking', 'detail')],+ hasMore: index === 1, nextCursor: index === 1 ? '1' : null };+ },+ onPage: (rows) => received.push(...rows.map((item) => item.id)),+ });+ expect(cursors).toEqual([null, '1']);+ expect(received).toEqual(['1', '2']);+ });++ it('does not publish a late page after collapse or invalidation', async () => {+ let current = true;+ const received: unknown[] = [];+ await readHistoryWorkDetails({+ isCurrent: () => current,+ readPage: async () => {+ current = false;+ return { version: 1, messages: [row(1, 'thinking', 'late')], hasMore: false, nextCursor: null };+ },+ onPage: (rows) => received.push(rows),+ });+ expect(received).toEqual([]);+ });+});++import { HistoryViewController } from '../historyViewController.js';+import { renderHistoryView } from '../historyViewRender.js';+import type { HistoryViewPage } from '../historyView.js';++describe('shared history view lifecycle', () => {+ it('reloads an edited prefix when new rows arrive in the same revision', async () => {+ let rows = [row(1, 'thinking', 'old'), row(2, 'thinking', 'tail')];+ const cursors: Array<string | undefined> = [];+ const view = new HistoryViewController<HistoryMessageSource>({+ page: async () => ({ version: 1, items: projectHistoryView(rows, false), hasMore: false, nextCursor: null }),+ details: async (_summary, after) => {+ cursors.push(after);+ return { version: 1, messages: rows.filter((item) => !after || Number(item.id) > Number(after)), hasMore: false, nextCursor: null };+ },+ expanded: async () => undefined,+ });+ await view.refresh();+ const key = view.getSnapshot().items[0].key;+ view.setExpanded(key, true);+ await new Promise((done) => setTimeout(done, 0));+ rows = [row(1, 'thinking', 'corrected'), rows[1], row(3, 'thinking', 'appended')];+ await view.refresh();+ await new Promise((done) => setTimeout(done, 0));+ expect(cursors).toEqual([undefined, undefined]);+ expect(view.getSnapshot().details.get(key)?.messages.map((item) => item.content))+ .toEqual(['corrected', 'tail', 'appended']);+ await view.refresh();+ expect(cursors).toHaveLength(2);+ });++ it('keeps an in-flight first read valid across repeated activation and releases collapsed intent', async () => {+ let resolve!: (page: HistoryViewPage<HistoryMessageSource>) => void;+ const intents: string[][] = [];+ const view = new HistoryViewController<HistoryMessageSource>({+ page: () => new Promise((done) => { resolve = done; }),+ details: async () => ({ version: 1, messages: [row(1, 'thinking', 'body')], hasMore: false, nextCursor: null }),+ expanded: async (refs) => { intents.push(refs.map((ref) => ref.key)); },+ });+ const pending = view.refresh();+ view.setActive(true);+ view.setActive(true);+ const items = projectHistoryView([row(1, 'thinking', 'body')], true);+ resolve({ version: 1, items, hasMore: false, nextCursor: null });+ await pending;+ expect(view.getSnapshot().ready).toBe(true);+ view.setExpanded(items[0].key, true);+ await new Promise((done) => setTimeout(done, 0));+ expect(view.getSnapshot().details.get(items[0].key)?.complete).toBe(true);+ view.setExpanded(items[0].key, false);+ await new Promise((done) => setTimeout(done, 0));+ expect(intents.at(-1)).toEqual([]);+ });++ it('does not revive durable messages removed by rewind through the live overlay', async () => {+ const view = new HistoryViewController<HistoryMessageSource>({+ page: async () => ({ version: 1, items: projectHistoryView([row(1, 'user', 'kept')], false), hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => undefined,+ });+ await view.refresh();+ const rendered = renderHistoryView({+ view, snapshot: view.getSnapshot(), liveMessages: [row(2, 'assistant', 'rewound')], streaming: false,+ build: (rows) => rows.map((item) => item.clientId), work: () => 'work',+ isLive: () => false,+ });+ expect(rendered).toEqual(['c1']);+ });+});diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.tsindex 3865bee700..ebf2538ab7 100644--- a/packages/maker-shared/src/deviceLinkContract.ts+++ b/packages/maker-shared/src/deviceLinkContract.ts@@ -277,6 +277,9 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = [// 同一 handler;老被控端 CHANNEL_NOT_ALLOWED → 手机端展示失败提示,不阻塞手动改名)。'maker:regenerate-title','local-db:messages:list',+ 'local-db:messages:view',+ 'local-db:messages:work-details',+ 'local-db:messages:view-intent','local-db:messages:around','local-db:messages:around-client-id','maker:send',diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.tsnew file mode 100644index 0000000000..d32c41844b--- /dev/null+++ b/packages/maker-shared/src/historyView.ts@@ -0,0 +1,87 @@+/** 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;+export const HISTORY_VIEW_PAGE_BYTES = 256 * 1024;+export const HISTORY_DETAIL_PAGE_BYTES = 256 * 1024;++export interface HistoryMessageSource {+ id: string;+ clientId: string;+ role: string;+ content: unknown;+ createdAt: string;+ rowid?: number;+ toolUseId?: string | null;+ agentMeta?: object | null;+}++/** Both endpoints are real host message IDs, inclusive, in host database order. */+export interface HistoryWorkReference {+ key: string;+ firstMessageId: string;+ lastMessageId: string;+ /** Stored upper bound when the range ends in a recoverable in-flight block. */+ firstStoredMessageId?: string;+ lastStoredMessageId?: string;+ liveMessageIds?: string[];+}++export interface HistoryWorkSummary extends HistoryWorkReference {+ startedAtMs: number;+ endedAtMs: number;+ isStreaming: boolean;+ messageCount: number;+ toolCount: number;+ /** Changes when the source range or its persisted contents change. */+ revision: string;+}++/** Controller-local actions; never serialized into the host reading protocol. */+export interface DeferredHistoryWork {+ expanded: boolean;+ loading: boolean;+ failed: boolean;+ toggle(): void;+ retry(): void;+}++export type HistoryViewItem<TMessage extends HistoryMessageSource> =+ | { type: 'messages'; key: string; messages: TMessage[] }+ | { type: 'work'; key: string; summary: HistoryWorkSummary };++export interface HistoryViewPage<TMessage extends HistoryMessageSource> {+ version: typeof HISTORY_VIEW_VERSION;+ /** Chronological; the cursor advances independently of the rendered item count. */+ items: HistoryViewItem<TMessage>[];+ nextCursor: string | null;+ hasMore: boolean;+}++export interface HistoryDetailPage<TMessage extends HistoryMessageSource> {+ version: typeof HISTORY_VIEW_VERSION;+ messages: TMessage[];+ nextCursor: string | null;+ hasMore: boolean;+}++/** Shared by all controllers. A page boundary is never a user-facing "load more" step. */+export async function readHistoryWorkDetails<TMessage extends HistoryMessageSource>(options: {+ readPage(cursor: string | null): Promise<HistoryDetailPage<TMessage>>;+ initialCursor?: string | null;+ isCurrent(): boolean;+ onPage(messages: readonly TMessage[]): void;+}): Promise<void> {+ let cursor: string | null = options.initialCursor ?? null;+ const seen = new Set<string>();+ while (options.isCurrent()) {+ const page = await options.readPage(cursor);+ if (!options.isCurrent()) return;+ options.onPage(page.messages);+ if (!page.hasMore) return;+ if (!page.nextCursor || seen.has(page.nextCursor)) {+ throw new Error('History detail cursor did not advance');+ }+ seen.add(page.nextCursor);+ cursor = page.nextCursor;+ }+}diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.tsnew file mode 100644index 0000000000..814690e82f--- /dev/null+++ b/packages/maker-shared/src/historyViewController.ts@@ -0,0 +1,238 @@+import {+ readHistoryWorkDetails, type HistoryDetailPage, type HistoryMessageSource,+ type HistoryViewItem, type HistoryViewPage, type HistoryWorkSummary,+} from './historyView.js';++export interface HistoryWorkDetailState<T extends HistoryMessageSource> {+ messages: readonly T[];+ revision: string;+ lastMessageId: string;+ loading: boolean;+ complete: boolean;+ error: unknown | null;+}++export interface HistoryViewSnapshot<T extends HistoryMessageSource> {+ items: readonly HistoryViewItem<T>[];+ details: ReadonlyMap<string, HistoryWorkDetailState<T>>;+ expanded: ReadonlySet<string>;+ nextCursor: string | null;+ hasMore: boolean;+ loading: boolean;+ ready: boolean;+ error: unknown | null;+}++export interface HistoryViewTransport<T extends HistoryMessageSource> {+ page(before?: string): Promise<HistoryViewPage<T>>;+ details(summary: HistoryWorkSummary, after?: string): Promise<HistoryDetailPage<T>>;+ /** Full replacement of this view's intent; empty releases detail streaming. */+ expanded(summaries: readonly HistoryWorkSummary[]): Promise<void>;+}++/**+ * Shared reading state for native and desktop controllers. Raw message stores never+ * receive synthetic rows or a false promise that deferred source ranges are loaded.+ */+export class HistoryViewController<T extends HistoryMessageSource> {+ private state: HistoryViewSnapshot<T> = {+ items: [], details: new Map(), expanded: new Set(), nextCursor: null,+ hasMore: false, loading: false, ready: false, error: null,+ };+ private listeners = new Set<() => void>();+ private generation = 0;+ private detailRuns = new Map<string, object>();+ private intentQueue: Promise<void> = Promise.resolve();+ private active = true;+ private pagePromise: Promise<void> | null = null;+ private refreshTimer: ReturnType<typeof setTimeout> | null = null;++ constructor(private readonly transport: HistoryViewTransport<T>) {}+ isActive = (): boolean => this.active;+ getSnapshot = (): HistoryViewSnapshot<T> => this.state;+ subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ };+ private publish(patch: Partial<HistoryViewSnapshot<T>>): void {+ this.state = { ...this.state, ...patch };+ for (const listener of this.listeners) listener();+ }++ refresh(older = false): Promise<void> {+ if (this.pagePromise) return this.pagePromise;+ const promise = this.readPage(older);+ this.pagePromise = promise;+ void promise.finally(() => { if (this.pagePromise === promise) this.pagePromise = null; });+ return promise;+ }++ /** Coalesce activity notices; full assistant streaming continues on its existing path. */+ invalidate(): void {+ if (!this.active || this.refreshTimer) return;+ this.refreshTimer = setTimeout(() => {+ this.refreshTimer = null;+ if (this.pagePromise) {+ void this.pagePromise.then(() => this.invalidate());+ } else void this.refresh();+ }, 500);+ }++ private async readPage(older: boolean): Promise<void> {+ if (!this.active || this.state.loading || (older && !this.state.hasMore)) return;+ const generation = this.generation;+ const before = older ? this.state.nextCursor ?? undefined : undefined;+ this.publish({ loading: true, error: null });+ try {+ const page = await this.transport.page(before);+ if (page == null) throw new Error('[CHANNEL_NOT_ALLOWED] History view is unavailable');+ if (!this.active || generation !== this.generation) return;+ let items = page.items;+ if (older) {+ const keys = new Set(items.map((item) => item.key));+ items = [...items, ...this.state.items.filter((item) => !keys.has(item.key))];+ } else if (page.hasMore && this.state.items.length) {+ const boundary = this.state.items.findIndex((item) => item.key === page.items[0]?.key);+ // Only retain a prefix with a proven overlap. Reset/rewind cannot leave an island.+ if (boundary > 0) items = [...this.state.items.slice(0, boundary), ...items];+ }+ const retainedPrefix = !older && items.length > page.items.length;+ this.publish({ items, ready: true, loading: false,+ hasMore: retainedPrefix ? this.state.hasMore : page.hasMore,+ nextCursor: retainedPrefix ? this.state.nextCursor : page.nextCursor });+ for (const item of items) {+ if (item.type === 'work' && this.state.expanded.has(item.key)) void this.loadDetails(item.summary);+ }+ this.sendIntent();+ } catch (error) {+ if (generation === this.generation && this.active) this.publish({ loading: false, error });+ }+ }++ setExpanded(key: string, expanded: boolean): void {+ const next = new Set(this.state.expanded);+ if (expanded) next.add(key); else next.delete(key);+ if (!expanded) this.detailRuns.delete(key);+ this.publish({ expanded: next });+ this.sendIntent();+ const item = this.state.items.find((value) => value.key === key);+ if (expanded && item?.type === 'work') void this.loadDetails(item.summary);+ }++ private sendIntent(): void {+ // Serialize replacement intents: a late expand ACK can never win over collapse.+ const generation = this.generation;+ this.intentQueue = this.intentQueue.catch(() => undefined).then(async () => {+ if (generation !== this.generation) return;+ if (!this.state.ready) return;+ const summaries = this.active ? this.state.items.flatMap((item) =>+ item.type === 'work' && this.state.expanded.has(item.key) ? [item.summary] : []) : [];+ await this.transport.expanded(summaries);+ }).catch(() => {+ // Detail interest is advisory; a transient ACK failure must not poison a successful page.+ if (this.active && generation === this.generation) this.invalidate();+ });+ }++ async loadDetails(summary: HistoryWorkSummary): Promise<void> {+ if (!this.active || !this.state.expanded.has(summary.key) || this.detailRuns.has(summary.key)) return;+ const existing = this.state.details.get(summary.key);+ if (existing?.complete && existing.revision === summary.revision) return;+ const token = {};+ const generation = this.generation;+ this.detailRuns.set(summary.key, token);+ const current = () => this.active && generation === this.generation+ && this.detailRuns.get(summary.key) === token && this.state.expanded.has(summary.key);+ // A changed revision may include late edits anywhere in the range, even+ // when its endpoint also advances. Keep the old display while rereading.+ let collected: T[] = [];+ const update = (patch: Partial<HistoryWorkDetailState<T>>) => {+ const details = new Map(this.state.details);+ details.set(summary.key, { messages: collected.length ? collected : (existing?.messages ?? []), revision: summary.revision,+ lastMessageId: summary.lastMessageId, loading: true, complete: false, error: null, ...patch });+ this.publish({ details });+ };+ update({});+ try {+ await readHistoryWorkDetails({+ readPage: (cursor) => this.transport.details(summary, cursor ?? undefined),+ isCurrent: current,+ onPage: (rows) => {+ const incoming = new Set(rows.map((row) => row.clientId));+ collected = [...collected.filter((row) => !incoming.has(row.clientId)), ...rows];+ update({});+ },+ });+ if (current()) update({ loading: false, complete: true });+ } catch (error) {+ if (current()) update({ loading: false, error });+ } finally {+ if (this.detailRuns.get(summary.key) === token) {+ const stillCurrent = current();+ this.detailRuns.delete(summary.key);+ const latest = this.state.items.find((item) => item.key === summary.key);+ if (stillCurrent && latest?.type === 'work' && latest.summary.revision !== summary.revision) void this.loadDetails(latest.summary);+ }+ }+ }++ /** Locate by visible pages; only the work range containing the target is opened. */+ async locate(clientId: string, createdAt: string): Promise<T | null> {+ const generation = this.generation;+ const targetMs = Date.parse(createdAt);+ const tried = new Set<string>();+ while (this.active && generation === this.generation) {+ for (const item of this.state.items) {+ if (item.type === 'messages') {+ const found = item.messages.find((row) => row.clientId === clientId);+ if (found) return found;+ } else if (!tried.has(item.key) && targetMs >= item.summary.startedAtMs && targetMs <= item.summary.endedAtMs) {+ tried.add(item.key);+ this.setExpanded(item.key, true);+ // setExpanded starts a read synchronously; wait for its published completion.+ await new Promise<void>((resolve) => {+ const done = () => !this.active || generation !== this.generation+ || !this.state.expanded.has(item.key) || !this.state.details.get(item.key)?.loading;+ if (done()) { resolve(); return; }+ const unsubscribe = this.subscribe(() => { if (done()) { unsubscribe(); resolve(); } });+ });+ const detail = this.state.details.get(item.key);+ if (detail?.error) throw detail.error;+ const found = detail?.messages.find((row) => row.clientId === clientId);+ if (found) return found;+ }+ }+ if (!this.state.hasMore) return null;+ await this.refresh(true);+ if (this.state.error) throw this.state.error;+ }+ return null;+ }++ /** View blur/background and source resets invalidate all outstanding reads. */+ setActive(active: boolean): void {+ if (active === this.active) { if (active && !this.state.ready) void this.refresh(); return; }+ if (this.refreshTimer) clearTimeout(this.refreshTimer);+ this.refreshTimer = null;+ this.active = active;+ this.generation++;+ this.detailRuns.clear();+ this.publish({ loading: false });+ this.sendIntent();+ if (active) {+ if (this.pagePromise) void this.pagePromise.then(() => this.refresh());+ else void this.refresh();+ }+ }+ reset(): void {+ this.generation++;+ this.detailRuns.clear();+ this.publish({ items: [], details: new Map(), expanded: new Set(), ready: false,+ nextCursor: null, hasMore: false, loading: false, error: null });+ this.sendIntent();+ if (this.active) {+ if (this.pagePromise) void this.pagePromise.then(() => this.refresh());+ else void this.refresh();+ }+ }+}diff --git a/packages/maker-shared/src/historyViewProjection.ts b/packages/maker-shared/src/historyViewProjection.tsnew file mode 100644index 0000000000..debc66afbb--- /dev/null+++ b/packages/maker-shared/src/historyViewProjection.ts@@ -0,0 +1,119 @@+import { groupWorkRuns } from './workRunGrouping.js';+import { isAgentPlanToolName, isDeliveryProseText } from './messageRender.js';+import { isAgentTaskToolName } from './agentTask.js';+import { extractPayloadToolResultMedia } from './payloadSummary.js';+import { isOrcaCommunicationTool, messageContentToPreview, parseMessageToolUse } from './messageNormalize.js';+import type { HistoryMessageSource, HistoryViewItem, HistoryWorkSummary } from './historyView.js';++type SourceItem<T extends HistoryMessageSource> = {+ type: 'source';+ row: T;+ activity: boolean;+ archivable: boolean;+};+type GroupItem = { type: 'group'; summary: HistoryWorkSummary };++/** 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)+ && !isOrcaCommunicationTool(name)+ && !['AskUserQuestion', 'ExitPlanMode', 'Workflow', 'Edit', 'Write', 'MultiEdit', 'edit', 'write'].includes(name)+ && !/(?:^|:|__)(?:create_worker|create_workers|send_to_worker|ghost_call)$/.test(name);+}++export function hasVisibleHistoryResult(content: unknown): boolean {+ const text = messageContentToPreview(content);+ return extractPayloadToolResultMedia(text).length > 0+ || /xdt_card_id|xdt_anchor_card_id|cindy-media:|xdt-file:/.test(text);+}++/**+ * Uses the same turn/seal/delivery boundaries as both renderers. Unknown cards and+ * reference-bearing results stay as source rows, so platform presentation keeps+ * ownership of their rendering. Only contiguous, recoverable work ranges fold.+ */+export function projectHistoryView<T extends HistoryMessageSource>(+ rows: readonly T[],+ streaming: boolean,+): HistoryViewItem<T>[] {+ const names = new Map<string, string>();+ const visibleResults = new Set<string>();+ for (const row of rows) {+ if (row.role === 'tool_use') {+ const tool = parseMessageToolUse(row);+ if (tool.toolUseId) names.set(tool.toolUseId, tool.toolName);+ }+ if (row.role === 'tool_result' && row.toolUseId && hasVisibleHistoryResult(row.content)) {+ visibleResults.add(row.toolUseId);+ }+ }+ const source: SourceItem<T>[] = rows.map((row) => {+ const meta = row.agentMeta as Record<string, unknown> | null | undefined;+ const tool = row.role === 'tool_use' ? parseMessageToolUse(row) : null;+ const toolId = tool?.toolUseId ?? row.toolUseId;+ const toolName = tool?.toolName ?? (toolId ? names.get(toolId) : undefined);+ const activity = row.role === 'thinking' || (+ (row.role === 'tool_use' || row.role === 'tool_result')+ && isHistoryDetailTool(toolName ?? '')+ && !(toolId && visibleResults.has(toolId))+ );+ const plainAssistant = row.role === 'assistant' && typeof row.content === 'string'+ && !meta?.botCollaboration && !meta?.botDirectMessage+ && !meta?.systemCardType && !meta?.goalCompletion && !meta?.goalNotice && !meta?.reviewRun;+ return { type: 'source', row, activity, archivable: activity || (+ plainAssistant && !isDeliveryProseText(row.content as string)+ ) };+ });+ type Item = SourceItem<T> | GroupItem;+ const timestamp = (item: Item | undefined): number | null => {+ if (!item) return null;+ const ms = item.type === 'group' ? item.summary.startedAtMs : Date.parse(item.row.createdAt);+ return Number.isFinite(ms) ? ms : null;+ };+ const group = (run: SourceItem<T>[], active: boolean, boundary: number | null): GroupItem => {+ const first = run[0].row;+ const last = run[run.length - 1].row;+ const anchor = run.find((item) => item.activity)?.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);+ }+ return { type: 'group', summary: {+ key: `work-${anchor.clientId || anchor.id}`,+ firstMessageId: first.id, lastMessageId: last.id,+ ...(run.some((item) => item.row.id.startsWith('history-live:')) ? {+ firstStoredMessageId: run.find((item) => !item.row.id.startsWith('history-live:'))?.row.id,+ lastStoredMessageId: [...run].reverse().find((item) => !item.row.id.startsWith('history-live:'))?.row.id,+ liveMessageIds: run.filter((item) => item.row.id.startsWith('history-live:')).map((item) => item.row.id),+ } : {}),+ startedAtMs: Number.isFinite(startedAtMs) ? startedAtMs : 0,+ endedAtMs: Number.isFinite(endedAtMs) ? endedAtMs : 0,+ messageCount: run.length,+ toolCount: run.filter((item) => item.row.role === 'tool_use').length,+ isStreaming: active,+ revision: `${last.id}:${run.length}:${hash >>> 0}`,+ } };+ };+ const grouped = groupWorkRuns<Item, SourceItem<T>>(source, streaming, {+ isUserBoundary: (item) => item.type === 'source' && item.row.role === 'user',+ isAnswer: (item) => item.type === 'source' && item.row.role === 'assistant'+ && typeof item.row.content === 'string' && !!item.row.content.trim(),+ isSealedAnswer: (item) => item.type === 'source'+ && (item.row.agentMeta as Record<string, unknown> | null)?.turnCompleted === true,+ isCompactBoundary: (item) => item.type === 'source' && item.row.role === 'system',+ isActivity: (item): item is SourceItem<T> => item.type === 'source' && item.activity,+ isArchivable: (item): item is SourceItem<T> => item.type === 'source' && item.archivable,+ startTimestamp: timestamp,+ endTimestamp: timestamp,+ boundaryTimestamp: timestamp,+ userBoundaryEnd: (item, previous) => timestamp(item) ?? previous,+ createGroup: (run, _next, active, boundary) => group(run, active, boundary),+ createCompletedGroup: (run, _next, boundary) => group(run, false, boundary),+ });+ return grouped.map((item): HistoryViewItem<T> => item.type === 'group'+ ? { type: 'work', key: item.summary.key, summary: item.summary }+ : { type: 'messages', key: item.row.clientId || item.row.id, messages: [item.row] });+}diff --git a/packages/maker-shared/src/historyViewRender.ts b/packages/maker-shared/src/historyViewRender.tsnew file mode 100644index 0000000000..2d047aa8c2--- /dev/null+++ b/packages/maker-shared/src/historyViewRender.ts@@ -0,0 +1,52 @@+import type { HistoryMessageSource, HistoryWorkSummary, DeferredHistoryWork } from './historyView.js';+import type { HistoryViewController, HistoryViewSnapshot } from './historyViewController.js';++/** Keep source chunks separated by deferred ranges; a renderer cannot group across a hole. */+export function renderHistoryView<T extends HistoryMessageSource, TItem>(options: {+ view: HistoryViewController<T>;+ snapshot: HistoryViewSnapshot<T>;+ liveMessages: readonly T[];+ build(messages: readonly T[], streaming: boolean): TItem[];+ work(summary: HistoryWorkSummary, details: TItem[], deferred: DeferredHistoryWork): TItem;+ streaming: boolean;+ isLive?(message: T): boolean;+}): TItem[] {+ const { snapshot, view } = options;+ const liveById = new Map(options.liveMessages.filter((row) => options.isLive?.(row)).map((row) => [row.clientId, row]));+ const seen = new Set<string>();+ const out: TItem[] = [];+ let source: T[] = [];+ let endMs = 0;+ const flush = (streaming: boolean) => {+ if (source.length) out.push(...options.build(source, streaming));+ source = [];+ };+ for (const item of snapshot.items) {+ if (item.type === 'messages') {+ for (const row of item.messages) {+ source.push(liveById.get(row.clientId) ?? row);+ seen.add(row.clientId);+ endMs = Math.max(endMs, Date.parse(row.createdAt));+ }+ } else {+ flush(false);+ const state = snapshot.details.get(item.key);+ const expanded = snapshot.expanded.has(item.key);+ out.push(options.work(item.summary,+ expanded && state ? options.build(state.messages.map((row) => liveById.get(row.clientId) ?? row), item.summary.isStreaming) : [], {+ expanded, loading: state?.loading ?? expanded, failed: !!state?.error,+ toggle: () => view.setExpanded(item.key, !expanded),+ retry: () => { void view.loadDetails(item.summary); },+ }));+ endMs = Math.max(endMs, item.summary.endedAtMs);+ }+ }+ // In-flight assistant/user rows arrive ahead of the next durable view snapshot.+ // Work bodies belong exclusively to the expanded group's detail state.+ for (const row of options.liveMessages) {+ if (options.isLive?.(row) && !seen.has(row.clientId) && (row.role === 'assistant' || row.role === 'user')+ && Date.parse(row.createdAt) >= endMs) source.push(row);+ }+ flush(options.streaming);+ return out;+}diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.tsindex 5d7552a6a8..42726ba10b 100644--- a/packages/maker-shared/src/messageRender.ts+++ b/packages/maker-shared/src/messageRender.ts@@ -209,6 +209,7 @@ export interface MessageRenderWorkGroupItem<type: 'work_group';key: string;children: MessageRenderWorkChildItem<TMessage>[];+ deferred?: import('./historyView.js').DeferredHistoryWork;durationMs?: number;/** True only for the trailing activity run in an active turn. */isStreaming?: boolean;diff --git a/packages/maker-shared/src/messageWindow.ts b/packages/maker-shared/src/messageWindow.tsindex 1868de76a3..dad7598c6c 100644--- a/packages/maker-shared/src/messageWindow.ts+++ b/packages/maker-shared/src/messageWindow.ts@@ -1,3 +1,8 @@+export * from './historyView.js';+export { projectHistoryView, isHistoryDetailTool, hasVisibleHistoryResult } from './historyViewProjection.js';+export * from './historyViewController.js';+export { renderHistoryView } from './historyViewRender.js';+export interface MessageScrollMetrics {contentHeight: number;offsetY: number;