Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote): 保持缓存消息连续显示并减少重复渲染与订阅
Dash64730e0dca6b
diff --git a/apps/desktop/src/renderer/__tests__/historyRenderBranch.test.ts b/apps/desktop/src/renderer/__tests__/historyRenderBranch.test.tsnew file mode 100644index 0000000000..7267919425--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/historyRenderBranch.test.ts@@ -0,0 +1,46 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { expect, it, vi } from 'vitest';++// Execute the production memo, leaving renderer builders at the test boundary.+// A ready remote view must not parse the unused full raw transcript first.+const source = ts.createSourceFile('MessageStream.tsx', readFileSync(resolve(process.cwd(),+ 'src/renderer/components/chat/MessageStream.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let callback: ts.Expression | undefined;+function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name)+ && node.name.elements.some(element => element.name.getText(source) === 'ungroupedRenderItems')+ && node.initializer && ts.isCallExpression(node.initializer)) callback = node.initializer.arguments[0];+ ts.forEachChild(node, visit);+}+visit(source);+if (!callback) throw new Error('Missing production history projection');+const code = ts.transpileModule(`return (${callback.getText(source)})();`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+}).outputText;++it.each([false, true])('builds only the displayed history source (ready=%s)', ready => {+ const rawItems = [{ key: 'raw' }];+ const historyItems = [{ key: 'history' }];+ const buildRaw = vi.fn(() => ({ items: rawItems, singleResultMap: new Map() }));+ const buildChunk = vi.fn(() => ({ items: historyItems, singleResultMap: new Map([['tool', 'result']]) }));+ const buildHistory = vi.fn(({ build }: { build: (rows: unknown[]) => unknown }) => build([]));+ const bindings = {+ streamProjection: (_rows: unknown, _dependencies: unknown, build: () => unknown) => build(),+ buildCachedRenderItems: buildRaw, buildRenderItems: buildChunk, renderHistoryView: buildHistory,+ getDataOwnerGeneration: () => 1, displayMessages: [], taskUpdates: new Map(), ghostCardSnapshot: {},+ historyLoaded: true, hasMoreMessages: false, historyWindowHasIsland: false, turnChangeSets: [], workingDir: '/',+ simplifiedBotConversation: false, sessionId: 's', cindyMakeSessionId: null, cindyMakeCompletionInComposer: false,+ subagentRunStatuses: new Map(), historyView: {}, historySnapshot: { ready }, historyLiveMessages: [],+ isSessionStreaming: false, handoff: {}, markdownImageTargetCacheRef: { current: new Map() },+ generatedFilesItemCacheRef: { current: new Map() }, groupWorkRuns: (items: unknown) => items,+ reuseGeneratedFilesRenderItems: (items: unknown) => items,+ };+ const result = new Function(...Object.keys(bindings), code)(...Object.values(bindings));+ expect(result.items).toEqual(ready ? historyItems : rawItems);+ expect(buildRaw).toHaveBeenCalledTimes(ready ? 0 : 1);+ expect(buildHistory).toHaveBeenCalledTimes(ready ? 1 : 0);+ expect(buildChunk).toHaveBeenCalledTimes(ready ? 1 : 0);+ if (ready) expect(result.singleResultMap.get('tool')).toBe('result');+});diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.tsindex e16dee3e64..5e30490375 100644--- a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts@@ -53,6 +53,43 @@ function fixture() {}describe('desktop remote history uses the shared live-to-history handoff', () => {+ it('lets a newer empty page retire a list receipt before the raw deletion push arrives', async () => {+ const { view, render, setSource } = fixture();+ const readReceipt = nextHistoryCacheReceipt();+ const received = { ...row('reply'), cacheReceipt: nextHistoryCacheReceipt() };+ view.setActive(false);+ await view.restoreCachedView(async () => ({ ...view.getSnapshot(), ready: true, readReceipt }));+ expect(render([received]).text).toContain('visible answer');+ setSource([]);+ view.setActive(true);+ await view.refresh();+ expect(render([received]).items).toEqual([]);+ view.setActive(false);+ expect(render([received]).items).toEqual([]);+ expect(render([received]).state.tail.size).toBe(0);+ });++ // Unit: reproduce the list-receipt/history timestamp disagreement through the+ // Desktop renderer; the already received answer must never disappear on entry.+ it('keeps a received answer whose timestamp is earlier than the cached page tail', async () => {+ const { view, render, setSource } = fixture();+ const later = row('user');+ const readReceipt = nextHistoryCacheReceipt();+ const received = { ...row('reply'), cacheReceipt: nextHistoryCacheReceipt() };+ view.setActive(false);+ await view.restoreCachedView(async () => ({ items: projectHistoryView([later], false), details: new Map(),+ expanded: new Set(), nextCursor: null, hasMore: false, loading: false, ready: true, error: null, readReceipt }));+ expect(render([received]).text).toContain('visible answer');+ setSource([received, later]);+ view.setActive(true);+ await view.refresh();+ const result = render([received]);+ expect(result.items.filter(item => item.type === 'message').map(item => item.message.clientId))+ .toEqual(['reply', 'user']);+ expect(result.state.tail.size).toBe(0);+ view.setActive(false);+ });+// Same-ID body updates must survive cache restore and yield to a later Host read.it('renders a later list receipt instead of the old cached body', async () => {const { view, render, setSource } = fixture();diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 37ac9c242a..dc0b01479a 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -3105,41 +3105,9 @@ export function MessageStream({// parsed image targets without retaining state beyond the session mount.const markdownImageTargetCacheRef = useRef<MarkdownImageTargetCache>(new Map());const { items: ungroupedRenderItems, singleResultMap } = useMemo(() => {- const built = streamProjection(- displayMessages,- [- getDataOwnerGeneration(),- taskUpdates,- ghostCardSnapshot,- ghostCardSnapshot.version,- historyLoaded,- hasMoreMessages,- historyWindowHasIsland,- turnChangeSets,- workingDir,- simplifiedBotConversation,- sessionId,- cindyMakeSessionId,- cindyMakeCompletionInComposer,- subagentRunStatuses,- historyView,- ],- () =>- buildCachedRenderItems(displayMessages, taskUpdates, ghostCardSnapshot, {- historyWindowIncomplete:- !historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,- turnChangeSets,- workingDir,- botSessionId: simplifiedBotConversation ? sessionId : undefined,- markdownImageTargetCache: markdownImageTargetCacheRef.current,- cindyMakeSessionId,- cindyMakeCompletionInComposer,- subagentRunStatuses,- }),- !simplifiedBotConversation && !historyView,- );if (historyView && historySnapshot?.ready) {- const results = new Map(built.singleResultMap);+ // Build only the displayed projection; the raw fallback is lazy below.+ const results = new Map<string, string>();const items = renderHistoryView<HistoryChatMessage, RenderItem>({view: historyView,snapshot: historySnapshot,@@ -3207,6 +3175,39 @@ export function MessageStream({singleResultMap: results,};}+ const built = streamProjection(+ displayMessages,+ [+ getDataOwnerGeneration(),+ taskUpdates,+ ghostCardSnapshot,+ ghostCardSnapshot.version,+ historyLoaded,+ hasMoreMessages,+ historyWindowHasIsland,+ turnChangeSets,+ workingDir,+ simplifiedBotConversation,+ sessionId,+ cindyMakeSessionId,+ cindyMakeCompletionInComposer,+ subagentRunStatuses,+ historyView,+ ],+ () =>+ buildCachedRenderItems(displayMessages, taskUpdates, ghostCardSnapshot, {+ historyWindowIncomplete:+ !historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,+ turnChangeSets,+ workingDir,+ botSessionId: simplifiedBotConversation ? sessionId : undefined,+ markdownImageTargetCache: markdownImageTargetCacheRef.current,+ cindyMakeSessionId,+ cindyMakeCompletionInComposer,+ subagentRunStatuses,+ }),+ !simplifiedBotConversation && !historyView,+ );return {items: reuseGeneratedFilesRenderItems(built.items, generatedFilesItemCacheRef.current),singleResultMap: built.singleResultMap,diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 0372905f82..d2e039dd83 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -11702,6 +11702,9 @@ function createRemoteHistoryView(sessionId: string) {return value as T;};const view = new HistoryViewController<HistoryChatMessage>({+ diagnostic: (event) => log.debug('history view changed', {+ hostRef: deviceId?.slice(0, 8) ?? 'local', sessionRef: sessionId.slice(0, 8), ...event,+ }),page: async (before) => {const writer = deviceId ? remoteHistoryCacheWriter(deviceId, sessionId) : undefined;// Remote reads ask for Host-projected running lines; a local view already holds live rows.diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex f6aa5a9429..d76af68e69 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -4738,7 +4738,10 @@ function SessionScreenContent() {const streamingRenderPrefixRef = useRef<MobileStreamingRenderPrefixCache | null>(null);const renderWindow = useMemo(() => {- const builtWindow = buildMobileStreamingRenderWindow({+ // A ready history view owns the displayed sequence. Avoid normalizing the+ // unused raw transcript first, and retire its prefix before any fallback.+ if (historyView.snapshot.ready) streamingRenderPrefixRef.current = null;+ const builtWindow = historyView.snapshot.ready ? null : buildMobileStreamingRenderWindow({cacheKey: i18nInstance.language,messages: projectedMessages,messageStructureChangedIndexes: projectedMessageStructureChangedIndexes,@@ -4754,11 +4757,11 @@ function SessionScreenContent() {prefixCache: streamingRenderPrefixRef,taskUpdates,});- const historyItems = historyView.snapshot.ready ? buildMobileHistoryRenderItems({+ const historyItems = builtWindow ? builtWindow.items : buildMobileHistoryRenderItems({view: historyView.view, snapshot: historyView.snapshot, messages: projectedMessages,streaming: isMessageListStreaming, sessionId, sessionSource: currentSession?.source, taskUpdates,pendingHandoff: handoff.pending, staleTail: handoff.tail, localUserClientIds,- }) : builtWindow.items;+ });let items = insertMobileForkOriginItem(// 孤儿 agent_task 兜底用 maker status 驱动的权威 turn 边界 gate,与 store 的// turn-start 清理同源闭环——渲染开启时 map 必已清过 stale。不用 isSessionStreaming@@ -4776,10 +4779,10 @@ function SessionScreenContent() {? previousRenderItemsRef.current: null;const previous = previousRenderState?.items ?? [];- const committedPrefix = historyView.snapshot.ready || forkOrigin || errorTailClientId+ const committedPrefix = !builtWindow || forkOrigin || errorTailClientId? null: builtWindow.prefix;- const stablePrefixItemCount = historyView.snapshot.ready || forkOrigin || errorTailClientId+ const stablePrefixItemCount = !builtWindow || forkOrigin || errorTailClientId? 0: committedMobileStreamingPrefixItemCount(builtWindow,@@ -4791,7 +4794,7 @@ function SessionScreenContent() {stablePrefixItemCount,);return {- diffCount: errorTailClientId+ diffCount: !builtWindow || errorTailClientId? countMobileRenderItemDiffs(reconciled): builtWindow.diffCount,items: reconciled,diff --git a/apps/mobile/src/__tests__/historyRenderBranch.test.ts b/apps/mobile/src/__tests__/historyRenderBranch.test.tsnew file mode 100644index 0000000000..eec2691a61--- /dev/null+++ b/apps/mobile/src/__tests__/historyRenderBranch.test.ts@@ -0,0 +1,45 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { expect, it, vi } from 'vitest';++// Execute the screen's real memo body with render builders as the boundary.+// Native mounting/timers are irrelevant to whether unused raw history is parsed.+const source = ts.createSourceFile('session.tsx', readFileSync(resolve(process.cwd(),+ 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let callback: ts.Expression | undefined;+function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'renderWindow'+ && node.initializer && ts.isCallExpression(node.initializer)) callback = node.initializer.arguments[0];+ ts.forEachChild(node, visit);+}+visit(source);+if (!callback) throw new Error('Missing production render window');+const code = ts.transpileModule(`return (${callback.getText(source)})();`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+}).outputText;++it.each([false, true])('builds only the displayed history source (ready=%s)', ready => {+ const rawItems = [{ key: 'raw' }];+ const historyItems = [{ key: 'history' }];+ const buildRaw = vi.fn(() => ({ items: rawItems, prefix: null, diffCount: 2 }));+ const buildHistory = vi.fn(() => historyItems);+ const prefixCache = { current: {} as unknown };+ const bindings = {+ buildMobileStreamingRenderWindow: buildRaw, buildMobileHistoryRenderItems: buildHistory,+ i18nInstance: { language: 'en' }, projectedMessages: [], projectedMessageStructureChangedIndexes: [],+ renderMessageStructureToken: {}, inputProjection: {}, optimisticUsers: [], isMessageListStreaming: false,+ makerTurnRunning: false, sessionId: 's', currentSession: {}, streamingRenderPrefixRef: prefixCache,+ taskUpdates: new Map(), historyView: { snapshot: { ready }, view: {} }, handoff: {}, localUserClientIds: new Set(),+ insertMobileForkOriginItem: (items: unknown) => items, forkOrigin: null, errorTailClientId: null,+ previousRenderItemsRef: { current: null }, committedMobileStreamingPrefixItemCount: () => 0,+ reconcileMobileMessageRenderItems: (_previous: unknown, items: unknown) => items,+ countMobileRenderItemDiffs: () => 7,+ };+ const result = new Function(...Object.keys(bindings), code)(...Object.values(bindings));+ expect(result.items).toBe(ready ? historyItems : rawItems);+ expect(result.diffCount).toBe(ready ? 7 : 2);+ expect(buildRaw).toHaveBeenCalledTimes(ready ? 0 : 1);+ expect(buildHistory).toHaveBeenCalledTimes(ready ? 1 : 0);+ if (ready) expect(prefixCache.current).toBeNull();+});diff --git a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.tsindex d26a19c703..a29da2bef6 100644--- a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts+++ b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts@@ -13,6 +13,73 @@ const row = (id: string, streaming = false): RemoteMessage => ({const createHandoff = () => new HistoryViewHandoff<RemoteMessage>((row) => row.agentMeta?.isStreaming === true);describe('mobile history handoff', () => {+ // A later authoritative read can omit a removed row entirely. Its list receipt+ // must retire even if a separate raw-store deletion push has not arrived yet.+ it('retires a received body after a newer empty page, including reentry', async () => {+ const readReceipt = nextHistoryCacheReceipt();+ const received = { ...row('answer'), cacheReceipt: nextHistoryCacheReceipt() };+ let hasMore = true;+ const view = new HistoryViewController<RemoteMessage>({+ refreshOnResume: false,+ page: async () => ({ version: 1,+ items: hasMore ? projectHistoryView([{ ...row('user'), createdAt: '2026-09-08T00:00:03Z' }], false) : [],+ hasMore, nextCursor: hasMore ? 'older' : null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }), expanded: async () => undefined,+ });+ view.setActive(false);+ await view.restoreCachedView(async () => ({ ...view.getSnapshot(), ready: true, readReceipt }));+ const handoff = createHandoff();+ const render = () => {+ const snapshot = view.getSnapshot();+ const state = handoff.reconcile(snapshot, [received]);+ return { state, items: buildMobileHistoryRenderItems({ view, snapshot, messages: state.messages,+ staleTail: state.tail, pendingHandoff: state.pending, streaming: true, sessionId: 's' }) };+ };+ expect(render().state.tail.has('answer')).toBe(true);+ view.setActive(true);+ await view.refresh();+ // A latest-page window cannot prove an absent older row was deleted.+ expect(render().state.tail.has('answer')).toBe(true);+ hasMore = false;+ await view.refresh();+ for (const active of [true, false, true]) {+ view.setActive(active);+ const result = render();+ expect(result.state.tail.size).toBe(0);+ expect(result.items.filter(item => item.type === 'message')).toEqual([]);+ }+ view.setActive(false);+ });++ // #6293 orders received bodies by local receipt, not Host timestamps. The+ // renderer must honor that decision too when a late row predates the page tail.+ it.each([true, false])('keeps a received earlier-timestamp answer through cached/fresh history (stale=%s)', async (stale) => {+ const later = { ...row('user'), createdAt: '2026-09-08T00:00:03Z' };+ const readReceipt = nextHistoryCacheReceipt();+ const received = { ...row('answer'), cacheReceipt: nextHistoryCacheReceipt() };+ const view = new HistoryViewController<RemoteMessage>({+ page: async () => ({ version: 1, items: projectHistoryView([received, later], false), hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }), expanded: async () => undefined,+ });+ view.setActive(false);+ await view.restoreCachedView(async () => ({ items: projectHistoryView([later], false), details: new Map(),+ expanded: new Set(), nextCursor: null, hasMore: false, loading: false, ready: true, error: null, readReceipt }));+ const handoff = createHandoff();+ const render = () => {+ const snapshot = { ...view.getSnapshot(), stale };+ const state = handoff.reconcile(snapshot, [received]);+ return buildMobileHistoryRenderItems({ view, snapshot, messages: state.messages, staleTail: state.tail,+ pendingHandoff: state.pending, streaming: false, sessionId: 's' })+ .filter(item => item.type === 'message').map(item => item.message.source.clientId);+ };+ expect(render()).toEqual(['answer', 'user']);+ view.setActive(true);+ await view.refresh();+ expect(render()).toEqual(['answer', 'user']);+ expect(handoff.reconcile(view.getSnapshot(), [received]).tail.size).toBe(0);+ view.setActive(false);+ });+// Regression: an updated list body has the same ID/time as the cached page. The// old tail-only rule hid it. Unit: real handoff + renderer, no network or timers.it('shows a newer received body in place until a page read after that push takes over', async () => {diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex afe35b46cf..1c0a45ec38 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -2213,6 +2213,9 @@ export function MessageRenderer({const debugFlags = Number(isDragSample) | (Number(isMomentumScrollingRef.current) << 1)| (Number(readingOlderRef.current) << 2) | (Number(nearBottomRef.current) << 3);if (mobileDebugEnabled() && sampleScrollDebug(debugFlags, isFinalDragSample)) mobileDebugLog('debug', 'scroll', 'list scroll', {+ hostRef: remoteDeviceId?.slice(0, 8), sessionRef: scrollResetKey?.slice(0, 8),+ itemCount: itemsForStructureRef.current.length, initialAnchorDone: initialAnchorDoneRef.current,+ reopening: reopeningAnchorRef.current !== null,...metrics, dragging: isDragSample, momentum: isMomentumScrollingRef.current,readingOlder: readingOlderRef.current, nearBottom: nearBottomRef.current,});@@ -2301,6 +2304,8 @@ export function MessageRenderer({getCurrentHistoryTopOffsetAdjustment,revealPositionedHistory,readingPosition,+ remoteDeviceId,+ scrollResetKey,attemptAutoLoadEarlier,bottomOverlayHeight,handoffHistoryPrependToUser,diff --git a/apps/mobile/src/session/remoteHistoryViews.ts b/apps/mobile/src/session/remoteHistoryViews.tsindex 59cf133b18..c7a4f5e51d 100644--- a/apps/mobile/src/session/remoteHistoryViews.ts+++ b/apps/mobile/src/session/remoteHistoryViews.ts@@ -4,6 +4,7 @@ import type { RemoteMessage } from './types';import { clearHistoryDisk, historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from './remoteHistoryDiskCache';import { getRecentTasks, recentTaskKey, subscribeRecentTasks } from './recentTasks';import { clearMessageReadingPositions } from './messageReadingPosition';+import { mobileDebugLog } from '@/debug/mobileDebugLog';// Data and resident message lists share the same five-task retention policy.type Reader = Pick<MobileMakerTransport, 'readHistoryView' | 'readWorkDetails' | 'setHistoryExpanded'>;@@ -53,6 +54,9 @@ export function getRemoteHistoryView(deviceId: string, sessionId: string, readerpage: (before) => entry.reader.readHistoryView(sessionId, before),details: (ref, after) => entry.reader.readWorkDetails(sessionId, ref, after),expanded: (refs) => entry.reader.setHistoryExpanded(sessionId, refs),+ diagnostic: (event) => mobileDebugLog('debug', 'recovery', 'history view changed', {+ hostRef: deviceId.slice(0, 8), sessionRef: sessionId.slice(0, 8), ...event,+ }),}) };return entry;}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 3394aad557..8aa3878174 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -179,6 +179,17 @@ raw store 中晚于画面末尾的普通用户/助手行接在其后显示,当前运行期的新推送可接管恢复的旧画面,成功的权威读取接管旧标记。桌面延迟恢复的磁盘行只覆盖有可比较且更早标记的同 ID 行,不覆盖无标记的实时正文。标记不作为主机消息修订号,不改变网络协议或扩展流式订阅范围。+渲染端同样以接收标记为准:缺失于历史页、但已证明晚于读取收到的正文不能再因消息时间戳+早于页尾被过滤掉;按时间插入缺失行,保留权威页内部顺序,后续读取仍可接管,删除与+rewind 继续遵守现有作废屏障。若较新的权威读取确认整段历史为空,即使 raw 删除推送+尚未抵达也结束旧接收标记的临时显示;不能把分页窗口中的缺失当成删除。离开页面变为+stale 时不能再用消息时间戳复活已被接收顺序判定为旧的正文。+历史画面已就绪时,两端只构建实际展示的历史序列,不额外解析随后会丢弃的 raw 渲染结果。+详情展开意图沿用串行队列,同一控制器只发送尚未发出的最新替换状态;不取消在途请求,+不跨控制器合并旧主机释放,也不记忆成功结果来跳过重连后的重新订阅。+本地 `history view changed` 调试记录使用设备/任务短引用与缓存、最新页、旧页、详情、降级、+重置来源及行数;手机滚动采样携带相同短引用和可见列表项数,区分数据替换与布局重测,+不记录正文、不扩展遥测上传。`messages:list` / `messages:view` 的 options 可选携带 `messageBodies: { version: 1, known }`,known 是消息 ID 与主机提供的 SHA-256 正文指纹对。支持的主机在授权、净化之后返回diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.tsindex 57da07eeac..bc360b52d1 100644--- a/packages/maker-shared/src/__tests__/historyView.test.ts+++ b/packages/maker-shared/src/__tests__/historyView.test.ts@@ -183,6 +183,28 @@ const ungroupedStructure = {};describe('shared history view lifecycle', () => {+ it('reports count-only cache/page transitions even when the diagnostic sink throws', async () => {+ const cachedItems = projectHistoryView([row(0, 'user', 'private cached body')], false);+ const freshItems = projectHistoryView([row(0, 'user', 'private cached body'), row(1, 'assistant', 'private answer')], false);+ const diagnostic = vi.fn(() => { throw new Error('diagnostic unavailable'); });+ const view = new HistoryViewController<HistoryMessageSource>({+ refreshOnResume: false, diagnostic,+ page: async () => ({ version: 1, items: freshItems, hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => undefined,+ });+ await view.restoreCachedView(async () => ({ ...view.getSnapshot(), items: cachedItems, ready: true }));+ await view.refresh();+ expect(view.getSnapshot()).toMatchObject({ ready: true, error: null, items: freshItems });+ expect(diagnostic.mock.calls).toEqual([+ [{ source: 'cache', previousItemCount: 0, itemCount: 1, messageCount: 1,+ detailMessageCount: 0, ready: true, stale: true }],+ [{ source: 'latest', previousItemCount: 1, itemCount: 2, messageCount: 2,+ detailMessageCount: 0, ready: true, stale: false }],+ ]);+ view.setActive(false);+ });+// Unit: Mobile's session coordinator owns resume reads. Previously activation// issued a pre-ACK page even when the coordinated batch would read after ACK.it('preserves cached content on managed resume and still reconciles changes during a read', async () => {@@ -448,6 +470,74 @@ describe('shared history view lifecycle', () => {expect(intents.at(-1)).toEqual([]);});+ // Unit: a delayed ACK used to queue one identical final replacement per+ // refresh/toggle. Only unsent intents may coalesce; reconnect must resend.+ it.each([false, true])('coalesces queued interest behind a slow ACK (rejected=%s)', async (rejected) => {+ const items = projectHistoryView([row(1, 'thinking', 'body')], true);+ const queue = { tail: Promise.resolve() };+ let settle!: () => void;+ const expanded = vi.fn(async (_refs: readonly { key: string }[]): Promise<void> => undefined);+ const view = new HistoryViewController<HistoryMessageSource>({+ refreshOnResume: false,+ page: async () => ({ version: 1, items, hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }), expanded,+ }, queue);+ await view.refresh();+ await queue.tail;+ expanded.mockClear();+ expanded.mockImplementationOnce(() => new Promise<void>((resolve, reject) => {+ settle = () => rejected ? reject(new Error('ACK timeout')) : resolve();+ }));+ view.setExpanded(items[0].key, true);+ // Wait for dispatch, not the deliberately blocked network promise.+ await Promise.resolve();+ await Promise.resolve();+ expect(expanded).toHaveBeenCalledTimes(1);+ for (let index = 0; index < 3; index++) {+ view.setExpanded(items[0].key, false);+ await view.refresh();+ view.setExpanded(items[0].key, true);+ }+ view.setExpanded(items[0].key, false);+ settle();+ await queue.tail;+ expect(expanded.mock.calls.map(([refs]) => refs.map(ref => ref.key))).toEqual([[items[0].key], []]);+ // Successful identical intents cannot be cached across connection epochs.+ view.setNetworkAvailable(false);+ view.setNetworkAvailable(true);+ await view.refresh();+ await queue.tail;+ expect(expanded).toHaveBeenCalledTimes(3);+ view.setActive(false);+ await queue.tail;+ });++ it('keeps an old Host release ordered before a replacement controller subscription', async () => {+ const items = projectHistoryView([row(1, 'thinking', 'body')], true);+ let release!: () => void;+ const queue = { tail: new Promise<void>(resolve => { release = resolve; }) };+ const sent: string[] = [];+ const create = (host: string) => new HistoryViewController<HistoryMessageSource>({+ refreshOnResume: false,+ page: async () => ({ version: 1, items, hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),+ expanded: async refs => { sent.push(`${host}:${refs.length}`); },+ }, queue);+ const oldView = create('old');+ await oldView.refresh();+ oldView.setExpanded(items[0].key, true);+ oldView.setActive(false);+ const nextView = create('next');+ await nextView.refresh();+ nextView.setExpanded(items[0].key, true);+ release();+ await queue.tail;+ expect(sent).toEqual(['old:0', 'next:1']);+ nextView.setActive(false);+ await queue.tail;+ expect(sent.at(-1)).toBe('next:0');+ });+it.each([false, true])('releases old detail interest when reset before a replacement page is ready (inactive=%s)', async (inactive) => {const items = projectHistoryView([row(1, 'thinking', 'body')], true);let first = true;diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.tsindex 42a7a2873b..23c2646317 100644--- a/packages/maker-shared/src/historyViewController.ts+++ b/packages/maker-shared/src/historyViewController.ts@@ -38,6 +38,18 @@ export interface HistoryViewTransport<T extends HistoryMessageSource> {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>;+ /** Local diagnostics only: counts and lifecycle, never message bodies. */+ diagnostic?(event: HistoryViewDiagnostic): void;+}++export interface HistoryViewDiagnostic {+ source: 'cache' | 'latest' | 'older' | 'details' | 'fallback' | 'reset';+ previousItemCount: number;+ itemCount: number;+ messageCount: number;+ detailMessageCount: number;+ ready: boolean;+ stale: boolean;}/**@@ -59,6 +71,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {private pagePromise: Promise<void> | null = null;private pageOlder = false;private pageGeneration = 0;+ private intentVersion = 0;private refreshTimer: ReturnType<typeof setTimeout> | null = null;constructor(@@ -88,8 +101,18 @@ export class HistoryViewController<T extends HistoryMessageSource> {this.listeners.add(listener);return () => this.listeners.delete(listener);};- private publish(patch: Partial<HistoryViewSnapshot<T>>): void {+ private publish(patch: Partial<HistoryViewSnapshot<T>>, source?: HistoryViewDiagnostic['source']): void {+ const previousItemCount = this.state.items.length;this.state = { ...this.state, ...patch };+ if (source && this.transport.diagnostic) {+ try {+ this.transport.diagnostic({ source, previousItemCount, itemCount: this.state.items.length,+ messageCount: historyViewLeaves(this.state.items).reduce((count, item) =>+ count + (item.type === 'messages' ? item.messages.length : 0), 0),+ detailMessageCount: [...this.state.details.values()].reduce((count, detail) => count + detail.messages.length, 0),+ ready: this.state.ready, stale: this.state.stale === true });+ } catch { /* Diagnostics must not interrupt cache restoration or remote reads. */ }+ }for (const listener of this.listeners) listener();}@@ -99,7 +122,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {const generation = this.cacheGeneration;const cached = await read().catch(() => null);if (!cached || this.state.ready || isHistoryViewUnavailable(this.state.error) || generation !== this.cacheGeneration) return;- this.publish({ ...cached, loading: this.state.loading, error: this.state.error, stale: true });+ this.publish({ ...cached, loading: this.state.loading, error: this.state.error, stale: true }, 'cache');}refresh(older = false, fresh = false): Promise<void> {@@ -186,7 +209,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {&& items.every((item, index) => item === this.state.items[index]) ? this.state.items : items;this.publish({ items: stableItems, ready: true, loading: false,...(older ? {} : { stale: false, readReceipt }),- hasMore: retained.hasMore, nextCursor: retained.nextCursor });+ hasMore: retained.hasMore, nextCursor: retained.nextCursor }, older ? 'older' : 'latest');for (const summary of historyWorkSummaries(items)) {if (this.state.expanded.has(summary.key)) void this.loadDetails(summary);}@@ -202,7 +225,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {if (this.refreshTimer) clearTimeout(this.refreshTimer);this.refreshTimer = null;this.publish({ items: [], details: new Map(), expanded: new Set(), ready: false,- nextCursor: null, hasMore: false, loading: false, error });+ nextCursor: null, hasMore: false, loading: false, error }, 'fallback');} else this.publish({ loading: false, error });}}@@ -223,14 +246,18 @@ export class HistoryViewController<T extends HistoryMessageSource> {if (!this.networkAvailable) return;// Serialize replacement intents: a late expand ACK can never win over collapse.const generation = this.generation;+ const version = ++this.intentVersion;this.intentQueue.tail = this.intentQueue.tail.catch(() => undefined).then(async () => {- if (generation !== this.generation || !this.networkAvailable) return;+ // Each replacement carries the latest state. Skip superseded *unsent*+ // requests, but still resend after page reads/reconnects. Keep this token+ // controller-local: a replacement Host must not cancel the old Host's release.+ if (version !== this.intentVersion || generation !== this.generation || !this.networkAvailable) return;// Empty replacement intents must release old interest even before a reset view is ready.const summaries = this.active ? historyWorkSummaries(this.state.items).filter((item) => this.state.expanded.has(item.key)) : [];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();+ if (this.active && version === this.intentVersion && generation === this.generation) this.invalidate();});}@@ -263,7 +290,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {: collected.length ? collected : (existing?.messages ?? []);details.set(summary.key, { messages, revision: summary.revision,lastMessageId: summary.lastMessageId, loading: true, complete: false, error: null, ...patch });- this.publish({ details });+ this.publish({ details }, settled ? 'details' : undefined);};update({});token.promise = (async () => {@@ -364,7 +391,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {this.cacheGeneration++;this.detailRuns.clear();this.publish({ items: [], details: new Map(), expanded: new Set(), ready: false,- nextCursor: null, hasMore: false, loading: false, error: null, stale: false, readReceipt: undefined });+ nextCursor: null, hasMore: false, loading: false, error: null, stale: false, readReceipt: undefined }, 'reset');this.sendIntent();if (this.active) void this.refresh();}diff --git a/packages/maker-shared/src/historyViewHandoff.ts b/packages/maker-shared/src/historyViewHandoff.tsindex 6a4aed0b95..46d72b5ab5 100644--- a/packages/maker-shared/src/historyViewHandoff.ts+++ b/packages/maker-shared/src/historyViewHandoff.ts@@ -1,4 +1,4 @@-import { historyViewLeaves, historyWorkSummaries, historyCacheReceiptFollows, type HistoryMessageSource } from './historyView.js';+import { historyViewLeaves, historyWorkSummaries, historyCacheReceiptFollows, isHistoryCacheReceipt, type HistoryMessageSource } from './historyView.js';import type { HistoryViewSnapshot } from './historyViewController.js';/** Live content may be newer, but its provisional timestamp must not replace known history order. */@@ -62,11 +62,17 @@ export class HistoryViewHandoff<T extends HistoryMessageSource> {const known = history.get(row.clientId);history.set(row.clientId, known ? liveContentWithHistoryOrder(row, known) : row);}- // A row leaves the tail once history covers it or the raw store drops it (delete/rewind).+ // An authoritative empty history retires older receipts even if the raw+ // deletion push lags behind it. A nonempty paged window cannot prove an+ // absent older row was deleted; keep the existing coverage/removal rule.+ const cleared = !snapshot.stale && !snapshot.hasMore && snapshot.items.length === 0;const rawById = new Map(raw.map(row => [row.clientId, row]));for (const id of this.tail) {const row = rawById.get(id);- if (!row || (history.has(id) && !receivedAfterRead(row))) this.tail.delete(id);+ if (!row || (!receivedAfterRead(row) && (history.has(id)+ || (cleared && isHistoryCacheReceipt(row.cacheReceipt) && isHistoryCacheReceipt(snapshot.readReceipt))))) {+ this.tail.delete(id);+ }}const endMs = snapshot.stale ? historyViewEndMs(snapshot) : 0;for (const row of raw) {@@ -79,7 +85,10 @@ export class HistoryViewHandoff<T extends HistoryMessageSource> {}continue;}- if (receivedAfterRead(row) || (snapshot.stale && Date.parse(row.createdAt) > endMs)) this.tail.add(row.clientId);+ // Once receipt order is available, wall-clock fallback must not revive an+ // already superseded body when this fresh view becomes stale on blur.+ if (receivedAfterRead(row) || (!isHistoryCacheReceipt(row.cacheReceipt)+ && snapshot.stale && Date.parse(row.createdAt) > endMs)) this.tail.add(row.clientId);if (this.tail.has(row.clientId)) history.set(row.clientId, row);}const tail = this.tail.size ? new Set(this.tail) : EMPTY;diff --git a/packages/maker-shared/src/historyViewRender.ts b/packages/maker-shared/src/historyViewRender.tsindex 5780454b68..a27fae53b8 100644--- a/packages/maker-shared/src/historyViewRender.ts+++ b/packages/maker-shared/src/historyViewRender.ts@@ -108,9 +108,15 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(optionsisPendingHandoff(source) && !seen.has(source.clientId)? pendingTail[pendingIndex++] : source);for (const row of orderedLiveMessages) {- if (isLive(row) && !seen.has(row.clientId)- && (Date.parse(row.createdAt) >= endMs- || isPendingHandoff(row))) rows.push(row);+ if (!isLive(row) || seen.has(row.clientId)) continue;+ const createdAt = Date.parse(row.createdAt);+ if (isStaleTail(row) && !isPendingHandoff(row) && createdAt < endMs) {+ // The receipt already proves this body arrived after the page read. A+ // delayed/persisted timestamp cannot veto that proof. Insert missing durable+ // rows in time order without reordering the authoritative page itself.+ const before = rows.findIndex((known) => Date.parse(known.createdAt) > createdAt);+ rows.splice(before < 0 ? rows.length : before, 0, row);+ } else if (isStaleTail(row) || createdAt >= endMs || isPendingHandoff(row)) rows.push(row);}// Local pending/blocked user bubbles and ephemeral UI rows belong to the// current UI store, not persisted history. Anchor them to the reordered slots,