Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 统一桌面和手机任务缓存更新与完成补读
Dash06df3c9ad755
diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.tsindex ab0153ca7d..aec02ad1fc 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts@@ -334,6 +334,27 @@ describe('normalizeDeviceSessions', () => {});describe('readMessages / writeMessages', () => {+ // Regression: a delayed history write used to discard a newer list body.+ // Existing cache fixture exercises the production guarded write/read path.+ it('retains a list update through an older page write, then retires it after a newer read', async () => {+ const c = rawCache();+ const token = await c.readMessagesWithInvalidation('dev', 'session');+ const old = row('same', '2026-01-01T00:00:00Z', { content: 'old' });+ const updated = { ...old, content: 'updated', cacheReceivedAt: 200 };+ const snapshot: HistoryViewSnapshot<typeof old> = {+ items: projectHistoryView([old], false), details: new Map(), expanded: new Set(),+ nextCursor: null, hasMore: false, ready: true, loading: false, error: null, readAt: 100,+ };+ await c.writeMessages('dev', 'session', [updated], token.invalidation, token.ownerRoot, token.accountCounter, undefined, true);+ await c.writeMessages('dev', 'session', [], token.invalidation, token.ownerRoot, token.accountCounter, encodeRemoteHistory(snapshot));+ const cached = await c.readMessagesWithInvalidation('dev', 'session');+ expect(cached.messages).toEqual([updated]);+ expect(decodeRemoteHistory(cached.historyView)?.readAt).toBe(100);+ await c.writeMessages('dev', 'session', [], token.invalidation, token.ownerRoot, token.accountCounter,+ encodeRemoteHistory({ ...snapshot, readAt: 300 }));+ expect((await c.readMessagesWithInvalidation('dev', 'session')).messages).toEqual([]);+ });+it('merges list arrivals under the page-write lock, preserving history and clear barriers', async () => {const c = rawCache();const token = await c.readMessagesWithInvalidation('dev', 'session');diff --git a/apps/desktop/src/main/device-link/mirrorCacheStore.ts b/apps/desktop/src/main/device-link/mirrorCacheStore.tsindex 87be2e5288..c21c96191c 100644--- a/apps/desktop/src/main/device-link/mirrorCacheStore.ts+++ b/apps/desktop/src/main/device-link/mirrorCacheStore.ts@@ -1054,6 +1054,7 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {const dir = path.join(rootAtStart, MESSAGES_DIR);const file = path.join(dir, messageFileName(deviceId, sessionId));let normalized = normalizeMessages(messages);+ let retainedListReceipts = false;const history = decodeRemoteHistory(historyView);// Sanitize the whole projection, including images outside message.content.let sanitizedHistory = history ? JSON.stringify(stripInlineMedia(JSON.parse(encodeRemoteHistory(history)), 0)) : undefined;@@ -1159,6 +1160,16 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {normalized = normalizeMessages([...rows.filter(row => row.id !== message.id&& (!message.clientId || row.clientId !== message.clientId)), message]);if (isRecord(previous) && decodeRemoteHistory(previous.historyView)) sanitizedHistory = previous.historyView as string;+ } else if (history) {+ // A delayed page write must not erase list bodies received after+ // that page started reading. Older receipts are covered by the page.+ if (!(await canCommitNonEmpty())) return { invalidation: -1 };+ const previous = await readJson(file);+ const rows = isRecord(previous) && Array.isArray(previous.messages) ? normalizeMessages(previous.messages) : [];+ const arrivals = rows.filter(row => typeof row.cacheReceivedAt === 'number'+ && row.cacheReceivedAt >= (history.readAt ?? 0));+ retainedListReceipts = arrivals.length > 0;+ normalized = normalizeMessages([...normalized, ...arrivals]);}const body = sanitizedHistory === undefined ? JSON.stringify(normalized) : JSON.stringify([normalized, sanitizedHistory]);const payload: StoredMessages = {@@ -1170,7 +1181,7 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {const serialized = JSON.stringify(payload);if (Buffer.byteLength(serialized, 'utf8') > MAX_MESSAGE_FILE_BYTES) {// Prefetch is additive: if it cannot fit, retain the usable history.- if (mergeListMessage) return { invalidation: numericCounter(await readClearCounter(rootAtStart, sessionKey)) };+ if (mergeListMessage || retainedListReceipts) return { invalidation: numericCounter(await readClearCounter(rootAtStart, sessionKey)) };// 单会话超限:新页写不下 —— 但旧正本此刻可能是 rewind / 删消息**之前**的窗口,// 而同一个超限页每次对账都会走到这里,永远不会有第二次机会更新它。所以**作废**// 旧缓存,而不是留一份会骗人的旧页(review: codex P1)。diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.tsindex 6396aebdd8..11ccffbe62 100644--- a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts@@ -53,6 +53,25 @@ function fixture() {}describe('desktop remote history uses the shared live-to-history handoff', () => {+ // 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();+ const old = { ...row('reply'), content: 'old cached body' };+ const received = { ...old, content: 'updated received body', cacheReceivedAt: Date.now() - 100 };+ view.setActive(false);+ await view.restoreCachedView(async () => ({ items: projectHistoryView([old], false), details: new Map(),+ expanded: new Set(), nextCursor: null, hasMore: false, loading: false, ready: true, error: null,+ readAt: received.cacheReceivedAt - 100 }));+ expect(render([received]).text).toContain('updated received body');+ expect(render([received]).text).not.toContain('old cached body');+ setSource([{ ...old, content: 'authoritative body' }]);+ view.setActive(true);+ await view.refresh();+ expect(render([received]).text).toContain('authoritative body');+ expect(render([received]).text).not.toContain('updated received body');+ view.setActive(false);+ });+it.each([false, true])('places a late harness boundary before the reserved send (history ready=%s)', async (ready) => {const { view, render, setSource } = fixture();if (ready) await view.refresh();diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.tsindex 74b3903c31..6ec7cefd67 100644--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts@@ -272,6 +272,25 @@ afterEach(() => {});describe('冷缓存 hydrate', () => {+ // Regression: one pre-received row prevented the disk history from hydrating.+ // Unit: open through the real store with its network request held pending.+ it('merges older disk history under a list-pushed reply before the network returns', async () => {+ const s = sid();+ setDataOwnerGeneration('owner-a', 1);+ registerRemote(s);+ const old = dbMessage(s, 'old', 'earlier history', '2026-10-10T00:00:00.000Z');+ const latest = dbMessage(s, 'new', 'latest reply', '2026-10-10T00:01:00.000Z');+ cachedMessages.set(`${DEVICE_ID}::${s}`, [old as unknown as Record<string, unknown>]);+ let push!: Parameters<typeof window.electronAPI.deviceLink.onRemotePush>[0];+ window.electronAPI.deviceLink.onRemotePush = vi.fn(callback => { push = callback; return () => {}; });+ makerChatStore.initGlobalListeners();+ push({ deviceId: DEVICE_ID, channel: 'local-db:messages:created', payload: { sessionId: s, listMessage: true, message: latest } });+ remoteListPromise = new Promise<Message[]>(() => {});+ makerChatStore.ensureInitialMessages(s);+ await flush(30);+ expect(makerChatStore.getSnapshot(s).messages.map(message => message.content)).toEqual(['earlier history', 'latest reply']);+ });+it('shows a list-pushed reply immediately when opening a task while its history request is still pending', async () => {const s = sid();setDataOwnerGeneration('owner-a', 1);@@ -284,7 +303,8 @@ describe('冷缓存 hydrate', () => {await flush(30);expect(makerChatStore.getSnapshot(s).messages.map(message => message.content)).toEqual([row.content]);expect(invoke.mock.calls.filter(([, channel]) => channel.startsWith('local-db:messages:'))).toEqual([]);- expectPut(DEVICE_ID, s, [row]);+ expect(putMessages.mock.calls.find(([device, session]) => device === DEVICE_ID && session === s)?.[2])+ .toEqual([{ ...row, cacheReceivedAt: expect.any(Number) }]);remoteListPromise = new Promise<Message[]>(() => {});makerChatStore.ensureInitialMessages(s);await flush(30);@@ -421,6 +441,29 @@ describe('冷缓存 hydrate', () => {}});+ // Turn-end read ahead is targeted; duplicate end events must not refetch.+ it('reads only the completed task and coalesces its duplicate completion', async () => {+ const completed = sid();+ const other = sid();+ const running = sid();+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [+ { id: completed, status: 'active', updatedAt: '2026-10-11T00:00:00Z', lastTurnEndedAt: 100 },+ { id: other, status: 'active', updatedAt: '2026-10-11T00:00:00Z', lastTurnEndedAt: 100 },+ { id: running, status: 'active', updatedAt: '2026-10-11T00:00:00Z', lastTurnEndedAt: 100, activeTurnStartedAt: 200 },+ ] as never);+ invoke.mockImplementationOnce((async (_device: string, channel: string, args: unknown[]) => {+ expect(channel).toBe('local-db:messages:view');+ expect(args[0]).toBe(completed);+ return { version: 1, items: projectHistoryView([dbMessage(completed, 'reply', 'finished body', '2026-10-11T00:00:01Z')], false),+ hasMore: false, nextCursor: null };+ }) as unknown as Parameters<typeof invoke.mockImplementationOnce>[0]);+ await makerChatStore.prefetchRemoteHistories(DEVICE_ID, new Set([completed, running]));+ await flush(30);+ expect(putMessages.mock.calls.at(-1)?.[6]).toContain('finished body');+ await makerChatStore.prefetchRemoteHistories(DEVICE_ID, new Set([completed]));+ expect(invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(1);+ });+it('restores the structured view through the actual offline session entry', async () => {const s = sid();const rows = [{ id: 'cached', clientId: 'cached', role: 'user', content: 'offline history', createdAt: '2026-09-17T00:00:00Z' }];@@ -437,6 +480,35 @@ describe('冷缓存 hydrate', () => {makerChatStore.purgeSession(s);});+ // A restart restores two caches: the structured page and a later durable list receipt.+ // Neither resolution order may hide the newer body while the Host is offline.+ it.each([false, true])('restores a later disk receipt over the same row in old history (raw delayed=%s)', async (delayed) => {+ const s = sid();+ const old = dbMessage(s, 'reply', 'old body', '2026-10-11T00:00:01.000Z');+ const latest = { ...old, content: 'latest body', cacheReceivedAt: 200 };+ const historyView = encodeRemoteHistory({ items: projectHistoryView([old], false), details: new Map(), expanded: new Set(),+ readAt: 100, ready: true, loading: false, error: null, nextCursor: null, hasMore: false });+ let reads = 0;+ getMessages.mockImplementation(async () => {+ if (++reads === 2 && delayed) await flush(30);+ return { messages: [latest], historyView, invalidation: cachedInvalidation,+ ownerToken: cachedOwnerToken, accountCounter: cachedAccountCounter };+ });+ registerRemote(s);+ remoteProjectsStore.markDeviceDisconnected(DEVICE_ID);+ makerChatStore.ensureInitialMessages(s);+ await flush(60);+ expect(makerChatStore.getSnapshot(s).messages.map(row => row.content)).toEqual(['latest body']);+ getRemoteHistoryView(s)?.setActive(true);+ expect(makerChatStore.getSnapshot(s).messages.map(row => row.content)).toEqual(['latest body']);+ expect(invoke).not.toHaveBeenCalled();+ makerChatStore.purgeSession(s);+ getMessages.mockImplementation(async (deviceId, sessionId) => ({+ messages: cachedMessages.get(`${deviceId}::${sessionId}`) ?? [], invalidation: cachedInvalidation,+ ownerToken: cachedOwnerToken, accountCounter: cachedAccountCounter,+ }));+ });+it('首拉未回来时用缓存种入,行带 cacheHydrated 且不置 historyLoaded', async () => {const s = sid();cachedMessages.set(`${DEVICE_ID}::${s}`, [diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex efb3d76d81..6851011bb0 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -35,6 +35,7 @@ import { evictTaskTagCatalog } from '../task-tags/taskTagEvents';import { useEffect, useRef } from 'react';import { isSharedTaskPeer } from '@cindy/device-link';import { projectScheduleEvent } from '@cindy/maker-shared/schedule-events';+import { historyTurnEnded } from '@cindy/maker-shared/message-window';import { useAuth } from '@/contexts/AuthContext';import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { createLogger } from '@/lib/logger';@@ -854,6 +855,19 @@ export function useDeviceLinkRemoteProjects(const offRemotePush = window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {if (disposed || !eligible.has(push.deviceId)) return;if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;+ if (windowRole === 'main' && push.channel === 'local-db:sessions:patched') {+ const payload = push.payload as { sessionId?: string; patch?: { lastTurnEndedAt?: unknown } } | null;+ if (typeof payload?.sessionId === 'string' && payload.patch && historyTurnEnded({}, payload.patch)) {+ const sessionId = payload.sessionId;+ // Let the ordinary push router apply metadata first, independent of+ // listener registration order. Only this completed task is eligible.+ queueMicrotask(() => {+ if (!disposed && eligible.has(push.deviceId) && isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) {+ void makerChatStore.prefetchRemoteHistories(push.deviceId, new Set([sessionId]));+ }+ });+ }+ }if (push.channel === 'maker:schedule:event') {// 推送照收;闲着不跟事件去拉整份自动化索引。人回来 wake/10s 用 scope both 补上。const watching =diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex 1cd3672f65..a68a4ec3bd 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -521,6 +521,8 @@ export interface AgentSwitchContent {}export interface Message {+ /** Local durable-push receipt time, retained by the display cache. */+ cacheReceivedAt?: number;id: string;/*** SQLite insertion order for DB-backed history rows. Remote controllers use itdiff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex f06887a59f..e4fe619e50 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -409,6 +409,8 @@ export interface AskUserQuestionItem {}export interface ChatMessage {+ /** Local durable-push receipt time, retained by the display cache. */+ cacheReceivedAt?: number;/** Private Bot reply provenance, projected from persisted/live agent metadata. */botPrivateReply?: boolean;botLearning?: import('@cindy/maker-shared/bot-learning').BotLearningReceipt[];@@ -9106,14 +9108,17 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {case 'maker:interaction-dismissed':handleLiveInteractionDismissedRaw(push.payload, remoteIngress);break;- case 'local-db:messages:created':+ case 'local-db:messages:created': {// 远程会话的持久化消息(接管路径)→ 注入 in-memory state(同本机)。- handleMessageCreatedRaw(push.payload, remoteIngress);+ const payload = push.payload as { sessionId?: string; message?: Message };+ const row = payload?.message && listMessage+ ? { ...payload.message, cacheReceivedAt: Date.now() } : payload?.message;+ handleMessageCreatedRaw({ ...payload, message: row }, remoteIngress);if (listMessage && push.deviceId && inboundSid) {- const row = (push.payload as { message?: Message }).message;if (row && !isBeforeOrAtRendererClearBoundary(inboundSid, row.createdAt)) persistListMessage(push.deviceId, inboundSid, row);}break;+ }case 'local-db:messages:deleted':handleMessageDeletedRaw(push.payload, remoteIngress);break;@@ -11431,7 +11436,7 @@ const _cacheHydrateSuppressed = new Set<string>();/*** 远程会话:从本地冷缓存乐观 hydrate 最近一页(并行于 fresh 首拉)。*- * 只在**切片仍为空且 fresh 还没落地**时种入,种入的行打 `cacheHydrated` 标记,+ * 只在 fresh 还没落地时补入,种入的行打 `cacheHydrated` 标记,* 由首拉落地时整批换掉。刻意不动 `historyLoaded` / `oldestMessageId`,并把* `hasMoreMessages` 留在 false:缓存窗口通常只活几百毫秒(fresh 到达前),* 拿缓存的游标去翻页会和随后落地的权威窗口打架(见首拉里孤岛游标那段);@@ -11476,12 +11481,21 @@ function hydrateRemoteMessagesFromCache(sessionId: string): void {if (_cacheHydrateSuppressed.has(sessionId)) return;if (!isCurrentHydration()) return;setState(sessionId, (s) => {- // fresh 已经落地 / 期间已有实时消息进来 → 缓存没有价值了,原样返回不动切片。- if (s.historyLoaded || s.messages.length > 0) return s;+ // A pre-received reply does not contain the earlier disk history. Fill+ // missing rows while keeping every newer in-memory body and its identity.+ const history = getRemoteHistoryView(sessionId)?.getSnapshot();+ if (s.historyLoaded && !history?.stale) return s;+ const current = new Map(s.messages.map(message => [message.clientId, message]));+ const newerReceipts = new Set(mapped.filter(message => {+ const existing = current.get(message.clientId);+ return !existing?.isStreaming && message.cacheReceivedAt !== undefined+ && message.cacheReceivedAt >= (history?.readAt ?? 0)+ && message.cacheReceivedAt > (existing?.cacheReceivedAt ?? 0);+ }).map(message => message.clientId));// hasMoreMessages 显式压成 false:缓存窗口期间不许向上翻页。翻回来的权威老行// 不带 cacheHydrated,首拉落地剔除缓存行后会在窗口中间留出一段洞,得靠后续翻页// 才收敛。首拉通常几百毫秒就到并写回真实的 hasMore,压掉这段的代价近乎为零。- return { ...s, messages: mapped, hasMoreMessages: false };+ return { ...s, messages: mergeMessages(mapped, s.messages, { addOnly: true, addOnlyExcept: newerReceipts }), hasMoreMessages: false };});});}@@ -11686,7 +11700,8 @@ function createRemoteHistoryView(sessionId: string) {for (const detail of snapshot.details.values()) available.push(...detail.messages);setState(sessionId, (state) => ({ ...state, historyLoaded: true,messages: confirmRemoteUsers(- mergeMessages(available, state.messages.filter((message) => !message.cacheHydrated), { addOnly: true }),+ mergeMessages(available, state.messages.filter((message) => !message.cacheHydrated+ || (message.cacheReceivedAt !== undefined && message.cacheReceivedAt >= (snapshot.readAt ?? 0))), { addOnly: true }),new Set(available.filter((message) => message.role === 'user').map((message) => message.clientId)),),hasMoreMessages: snapshot.hasMore, isLoadingMore: view.isLoadingOlder(),@@ -11704,17 +11719,22 @@ function createRemoteHistoryView(sessionId: string) {// Activity version already read ahead, per device and task, valid only while that mirror entry// is current (account switch or cache invalidation resets it). Memory only.const remoteHistoryPrefetchedAt = new Map<string, { version: string; owner: ReturnType<typeof getDataOwnerGeneration>; token: number }>();-const remoteHistoryPrefetchRuns = new Map<string, { again: boolean }>();+const remoteHistoryPrefetchRuns = new Map<string, { again: boolean; targets: Set<string> | null }>();/*** After a list read that may follow missed pushes (bootstrap/reconnect), read the latest* history page of recently changed tasks into the mirror a task restores on open. Open tasks* read their own view. Sequential and best effort: a failed read waits for the next refresh.*/-async function prefetchRemoteHistories(deviceId: string): Promise<void> {+async function prefetchRemoteHistories(deviceId: string, sessionIds?: ReadonlySet<string>): Promise<void> {const run = remoteHistoryPrefetchRuns.get(deviceId);- if (run) { run.again = true; return; }- const state = { again: true };+ if (run) {+ run.again = true;+ if (!sessionIds) run.targets = null;+ else if (run.targets) for (const id of sessionIds) run.targets.add(id);+ return;+ }+ const state = { again: true, targets: sessionIds ? new Set(sessionIds) : null };remoteHistoryPrefetchRuns.set(deviceId, state);const owner = getDataOwnerGeneration();const key = (sessionId: string) => JSON.stringify([deviceId, sessionId]);@@ -11724,8 +11744,12 @@ async function prefetchRemoteHistories(deviceId: string): Promise<void> {try {while (state.again) {state.again = false;+ const targets = state.targets;+ state.targets = new Set<string>();const candidates = selectHistoryPrefetchSessions(remoteProjectsStore.getDeviceSessions(deviceId, 'active'), {- eligible: (session) => session.status === 'active' && session.source !== 'scheduler' && !getRemoteHistoryView(session.id),+ limit: targets?.size,+ eligible: (session) => session.status === 'active' && session.source !== 'scheduler' && !getRemoteHistoryView(session.id)+ && (!targets || (targets.has(session.id) && historyPrefetchVersion(session) !== undefined)),prefetchedAt: (sessionId) => {const entry = remoteHistoryPrefetchedAt.get(key(sessionId));return entry && isDataOwnerGenerationCurrent(entry.owner)@@ -11739,6 +11763,7 @@ async function prefetchRemoteHistories(deviceId: string): Promise<void> {if (!historySnapshotCovers(previous, session)) {// Capture write authority before the read, like an open view does.const write = remoteHistoryCacheWriter(deviceId, session.id);+ const readAt = Date.now();let page: HistoryViewPage<Message>;try {page = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:messages:view',@@ -11755,7 +11780,7 @@ async function prefetchRemoteHistories(deviceId: string): Promise<void> {const snapshot = historySnapshotForCache({ ...page, items }, previous,(candidate) => fitsRemoteHistoryCache(encodeRemoteHistory(candidate)));if (!snapshot) continue;- write(snapshot);+ write({ ...snapshot, readAt });}const version = historyPrefetchVersion(session);if (version !== undefined) {@@ -18666,6 +18691,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {const createdAtById = new Map(serverMsgs.map((m) => [m.clientId, m.createdAt]));const serverIdByClientId = new Map(serverMsgs.map((m) => [m.clientId, m.id]));const rowidById = new Map(serverMsgs.map((m) => [m.clientId, m.rowid]));+ const receivedAtById = new Map(serverMsgs.map((m) => [m.clientId, m.cacheReceivedAt]));const remoteContentTruncatedById = new Map(serverMsgs.map((m) => [m.clientId, m.agentMeta?.remoteContentTruncated === true]),);@@ -19258,6 +19284,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {const iso = mapServerCreatedAt(cm, ts);const serverId = serverIdByClientId.get(cm.clientId);const rowid = rowidById.get(cm.clientId);+ const cacheReceivedAt = receivedAtById.get(cm.clientId);const remoteContentTruncated = remoteContentTruncatedById.get(cm.clientId) === true;const remoteRowsTrimmed = remoteRowsTrimmedById.get(cm.clientId) === true;const legacyUserTurnCost = legacyUserTurnCosts.get(cm.clientId);@@ -19277,6 +19304,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {...(iso ? { createdAt: iso } : {}),...(typeof serverId === 'string' && serverId.length > 0 ? { id: serverId } : {}),...(rowid !== undefined ? { rowid } : {}),+ ...(cacheReceivedAt !== undefined ? { cacheReceivedAt } : {}),...(remoteContentTruncated ? { remoteContentTruncated: true } : {}),...(remoteRowsTrimmed ? { remoteRowsTrimmed: true } : {}),};diff --git a/apps/desktop/src/shared/remoteHistoryCache.ts b/apps/desktop/src/shared/remoteHistoryCache.tsindex b074344043..851417c9ca 100644--- a/apps/desktop/src/shared/remoteHistoryCache.ts+++ b/apps/desktop/src/shared/remoteHistoryCache.ts@@ -111,6 +111,7 @@ export function decodeRemoteHistory<T extends HistoryMessageSource>(expanded: new Set(value.expanded),hasMore: value.hasMore,nextCursor: value.nextCursor,+ ...(typeof value.readAt === 'number' && Number.isFinite(value.readAt) ? { readAt: value.readAt } : {}),ready: true,loading: false,error: null,@@ -132,6 +133,7 @@ export function encodeRemoteHistory<T extends HistoryMessageSource>(expanded: [...snapshot.expanded],hasMore: snapshot.hasMore,nextCursor: snapshot.nextCursor,+ readAt: snapshot.readAt,},(key, value) => {// A cached transcript may be read offline. Never revive a live indicator or send payload.diff --git a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.tsindex 27259f0368..5fef681652 100644--- a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts+++ b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts@@ -13,6 +13,37 @@ const row = (id: string, streaming = false): RemoteMessage => ({const createHandoff = () => new HistoryViewHandoff<RemoteMessage>((row) => row.agentMeta?.isStreaming === true);describe('mobile history handoff', () => {+ // 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 () => {+ const old = { ...row('answer'), content: 'old answer' };+ const received = { ...old, content: 'updated answer', cacheReceivedAt: 200 };+ const view = new HistoryViewController<RemoteMessage>({+ page: async () => ({ version: 1, items: projectHistoryView([old], 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([old], false),+ details: new Map(), expanded: new Set(), nextCursor: null, hasMore: false,+ loading: false, ready: true, error: null, readAt: 100 }));+ const handoff = createHandoff();+ const render = (snapshot = view.getSnapshot(), currentHandoff = handoff) => {+ const state = currentHandoff.reconcile(snapshot, [received]);+ return buildMobileHistoryRenderItems({ view, snapshot, messages: state.messages,+ pendingHandoff: state.pending, staleTail: state.tail, streaming: false, sessionId: 's',+ }).filter(item => item.type === 'message').map(item => item.message.body);+ };+ expect(render()).toEqual(['updated answer']);+ // An in-flight page captured before the push must not roll it back either.+ expect(render({ ...view.getSnapshot(), stale: false })).toEqual(['updated answer']);+ // A new receipt can also arrive while the very first page is in flight.+ expect(render({ ...view.getSnapshot(), items: [], stale: false }, createHandoff())).toEqual(['updated answer']);+ // A newer authoritative read is allowed to replace it, even with shorter text.+ expect(render({ ...view.getSnapshot(), stale: false, readAt: 300 })).toEqual(['old answer']);+ expect(handoff.reconcile(view.getSnapshot(), []).tail.size).toBe(0);+ });+it('keeps the live tail below completed text when recovery history has not caught up to that tail', async () => {const first = { ...row('A'), content: 'first paragraph' };let live = { ...row('B', true), content: 'second paragraph', createdAt: first.createdAt };diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.tsindex c573abc253..2d7766c4fd 100644--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts@@ -190,6 +190,24 @@ describe('mobileSessionMessageCache', () => {expect(rows[1].content).toBe(content);});+ // Unit regression: a blurred page's deferred write must not erase list pushes+ // received after that write was captured; explicit replacement still wins.+ it('preserves a later list receipt through a delayed page flush', async () => {+ const { cacheSessionMessages, cacheSessionListMessage, getCachedSessionMessages,+ captureSessionMessageCacheWriteAuthority, cacheSessionMessagesIfCurrent,+ replaceCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');+ const old = makeMessage({ id: 'same', clientId: 'same', createdAt: isoAt(1), content: 'old' });+ await cacheSessionMessages('host-a', 'session-1', [old]);+ const authority = captureSessionMessageCacheWriteAuthority('host-a', 'session-1')!;+ const newer = { ...old, content: 'updated', cacheReceivedAt: authority.capturedAt };+ await cacheSessionListMessage('host-a', 'session-1', newer);+ await cacheSessionMessagesIfCurrent(authority, [old]);+ expect(await getCachedSessionMessages('host-a', 'session-1')).toEqual([newer]);+ await replaceCachedSessionMessages('host-a', 'session-1', []);+ await cacheSessionMessagesIfCurrent(authority, [old]);+ expect(await getCachedSessionMessages('host-a', 'session-1')).toEqual([]);+ });+it('returns [] for missing cache or blank ids', async () => {const { getCachedSessionMessages, cacheSessionMessages } = await import('@/session/mobileSessionMessageCache');diff --git a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.tsindex 8b07b6c2ab..dabc35df4b 100644--- a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts+++ b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts@@ -43,6 +43,34 @@ afterEach(async () => {});describe('history read ahead after a list refresh', () => {+ // Unit regression: completion must warm its own disk page without reading+ // unrelated running tasks; ordinary preview/ack patches must not cause traffic.+ it('reads only the completed task and ignores repeated completion and preview patches', async () => {+ setMobileAuthOwner('user-1');+ const start = Date.parse('2026-10-11T00:00:01Z');+ remoteSessionStore.setDeviceSessions(DEVICE, 'Mac', [+ session('s', '2026-10-11T00:00:01Z', { activeTurnStartedAt: start }),+ session('running', '2026-10-11T00:00:09Z', { activeTurnStartedAt: start }),+ ]);+ const reader = { readHistoryView: vi.fn(async () => page([row('reply', 9)])) };+ const reads: Promise<void>[] = [];+ const off = remoteSessionStore.onSessionHistoryPrefetchRequested((device, id) => {+ reads.push(prefetchRemoteHistories(device, reader, () => true, id ? new Set([id]) : undefined));+ });+ try {+ remoteSessionStore.applySessionPatch(DEVICE, 's', { preview: 'still running' });+ expect(reader.readHistoryView).not.toHaveBeenCalled();+ remoteSessionStore.applySessionPatch(DEVICE, 's', { lastTurnEndedAt: start + 10_000 });+ await Promise.all(reads);+ expect(reader.readHistoryView.mock.calls).toEqual([['s']]);+ expect((await readHistoryDisk(historyDiskAuthority(DEVICE, 's')))?.items).toEqual(page([row('reply', 9)]).items);+ remoteSessionStore.applySessionPatch(DEVICE, 's', { lastTurnEndedAt: start + 10_000 });+ remoteSessionStore.applySessionPatch(DEVICE, 's', { preview: 'final reply' });+ await Promise.all(reads);+ expect(reader.readHistoryView).toHaveBeenCalledTimes(1);+ } finally { off(); }+ });+it.each(['prefix', 'collapsed', 'latest'] as const)('handles an oversized %s without losing the offline cache', async (kind) => {setMobileAuthOwner('user-1');const old = row('old', 1, 'x'.repeat(1_250_000));@@ -85,7 +113,7 @@ describe('history read ahead after a list refresh', () => {it('fires on the first list and on a reconnect reseed, not on ordinary refreshes', () => {const seen: string[] = [];- const off = remoteSessionStore.onSessionListRefreshAfterGap((deviceId) => seen.push(deviceId));+ const off = remoteSessionStore.onSessionHistoryPrefetchRequested((deviceId) => seen.push(deviceId));remoteSessionStore.setDeviceSessions(DEVICE, 'Mac', [session('s', '2026-10-11T00:00:01.000Z')]);remoteSessionStore.setDeviceSessions(DEVICE, 'Mac', [session('s', '2026-10-11T00:00:02.000Z')]);remoteSessionStore.requestReseed(DEVICE);diff --git a/apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx b/apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsxindex 779417956a..834c18979d 100644--- a/apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx+++ b/apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx@@ -8,7 +8,7 @@ import { remoteSessionStore } from './remoteSessionStore';// Let the list refresh and any task the user taps right away go first.const PREFETCH_DELAY_MS = 1500;-/** Reads changed tasks ahead after a list refresh that may follow missed pushes (renders nothing). */+/** Coalesces reconnect and completed-task read ahead (renders nothing). */export function RemoteHistoryPrefetchBridge() {const { invoke } = useDeviceLink();const { accountGeneration } = useAuth();@@ -18,13 +18,22 @@ export function RemoteHistoryPrefetchBridge() {const generation = accountGeneration;const isCurrent = () => latest.current.accountGeneration === generation;const timers = new Map<string, ReturnType<typeof setTimeout>>();- const unsubscribe = remoteSessionStore.onSessionListRefreshAfterGap((deviceId) => {+ const pending = new Map<string, Set<string> | null>();+ const unsubscribe = remoteSessionStore.onSessionHistoryPrefetchRequested((deviceId, sessionId) => {+ if (!sessionId) pending.set(deviceId, null);+ else if (pending.get(deviceId) !== null) {+ const ids = pending.get(deviceId) ?? new Set<string>();+ ids.add(sessionId);+ pending.set(deviceId, ids);+ }if (timers.has(deviceId)) return;timers.set(deviceId, setTimeout(() => {timers.delete(deviceId);+ const ids = pending.get(deviceId);+ pending.delete(deviceId);if (!isCurrent()) return;const reader = createMobileMakerTransport({ deviceId, invoke: latest.current.invoke, isCurrent });- void prefetchRemoteHistories(deviceId, reader, isCurrent);+ void prefetchRemoteHistories(deviceId, reader, isCurrent, ids ?? undefined);}, PREFETCH_DELAY_MS));});return () => {diff --git a/apps/mobile/src/session/mobileSessionMessageCache.ts b/apps/mobile/src/session/mobileSessionMessageCache.tsindex ab2d449fbd..04d09902ae 100644--- a/apps/mobile/src/session/mobileSessionMessageCache.ts+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts@@ -37,6 +37,7 @@ let globalClearInProgress = false;let activeGlobalClear: Promise<void> | null = null;export interface SessionMessageCacheWriteAuthority {+ readonly capturedAt: number;readonly key: string;readonly owner: MobileAuthOwnerGeneration;readonly globalEpoch: number;@@ -74,6 +75,7 @@ export function captureSessionMessageCacheWriteAuthority(const key = safeStorageKey(deviceId, sessionId);if (!key) return null;return {+ capturedAt: Date.now(),key,owner,globalEpoch: globalWriteEpoch,@@ -88,9 +90,10 @@ export function captureSessionMessageCacheWriteAuthority(export async function cacheSessionMessagesIfCurrent(authority: SessionMessageCacheWriteAuthority | null,messages: readonly RemoteMessage[],+ preserveLaterReceipts = true,): Promise<boolean> {if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return false;- const normalized = normalizeCachedMessages(messages);+ let normalized = normalizeCachedMessages(messages);let written = false;await enqueueCacheOperation(authority.key, async () => {if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;@@ -98,6 +101,18 @@ export async function cacheSessionMessagesIfCurrent(await messageCacheStorage.removeItem(authority.key);return;}+ // A blurred page's pending flush may run after a list push. Preserve only+ // receipts newer than the captured write, not arbitrary old cached history.+ let previous: unknown = null;+ if (preserveLaterReceipts) {+ const raw = await messageCacheStorage.getItem(authority.key);+ try { previous = raw ? JSON.parse(raw) : null; } catch { /* Replace an unreadable cache. */ }+ }+ const arrivals = isRecord(previous) && Array.isArray(previous.messages)+ ? normalizeCachedMessages(previous.messages).filter(row =>+ typeof row.cacheReceivedAt === 'number' && row.cacheReceivedAt >= authority.capturedAt) : [];+ if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;+ normalized = normalizeCachedMessages([...normalized, ...arrivals]);const payload: StoredSessionMessageCache = {version: 1,updatedAt: Date.now(),@@ -119,7 +134,7 @@ export async function replaceCachedSessionMessages(if (!key) return false;keyWriteEpochs.set(key, (keyWriteEpochs.get(key) ?? 0) + 1);const authority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);- return cacheSessionMessagesIfCurrent(authority, messages);+ return cacheSessionMessagesIfCurrent(authority, messages, false);}// 读取某 (host, session) 的缓存消息;无缓存 / 解析失败一律返回空数组(乐观 hydrate 不应抛错)。@@ -162,7 +177,8 @@ export async function cacheSessionListMessage(deviceId: string, sessionId: strinif (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;const raw = await messageCacheStorage.getItem(authority.key);const parsed: unknown = raw ? JSON.parse(raw) : null;- const previous = normalizeCachedMessages(isRecord(parsed) && Array.isArray(parsed.messages) ? parsed.messages : []);+ const previous = normalizeCachedMessages(isRecord(parsed) && Array.isArray(parsed.messages)+ ? parsed.messages : Array.isArray(parsed) ? parsed : []);const messages = normalizeCachedMessages([...previous.filter(row =>row.id !== message.id && (!message.clientId || row.clientId !== message.clientId)), message]);if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;diff --git a/apps/mobile/src/session/remoteHistoryDiskCache.ts b/apps/mobile/src/session/remoteHistoryDiskCache.tsindex dce083d030..e9030fc512 100644--- a/apps/mobile/src/session/remoteHistoryDiskCache.ts+++ b/apps/mobile/src/session/remoteHistoryDiskCache.ts@@ -84,7 +84,7 @@ export async function writeHistoryDisk(authority: Authority, snapshot: HistoryViconst items = (values: readonly HistoryViewItem<RemoteMessage>[]): HistoryViewItem<RemoteMessage>[] => values.map(item =>item.type === 'messages' ? { ...item, messages: messages(item.messages), ...(item.deferred ? { deferred: summary(item.deferred) } : {}) }: { ...item, summary: summary(item.summary), ...(item.children ? { children: items(item.children) } : {}) });- const text = JSON.stringify({ version: 1, items: items(snapshot.items),+ const text = JSON.stringify({ version: 1, readAt: snapshot.readAt, items: items(snapshot.items),details: [...snapshot.details].filter(([, detail]) => detail.complete && !detail.loading && !detail.error).map(([key, detail]) => [key, { ...detail, messages: messages(detail.messages) }]),expanded: [...snapshot.expanded], nextCursor: snapshot.nextCursor, hasMore: snapshot.hasMore,diff --git a/apps/mobile/src/session/remoteHistoryPrefetch.ts b/apps/mobile/src/session/remoteHistoryPrefetch.tsindex faead0ac00..4a312a191b 100644--- a/apps/mobile/src/session/remoteHistoryPrefetch.ts+++ b/apps/mobile/src/session/remoteHistoryPrefetch.ts@@ -21,7 +21,7 @@ type Reader = Pick<MobileMakerTransport, 'readHistoryView'>;// was written to is current (sign-out, account switch and cache clears invalidate it). Memory only.const prefetchedAt = new Map<string, { version: string; current(): boolean }>();const keyFor = (deviceId: string, sessionId: string) => JSON.stringify([deviceId, sessionId]);-const running = new Map<string, { again: boolean }>();+const running = new Map<string, { again: boolean; targets: Set<string> | null }>();/*** After a list read that may follow missed pushes, read the latest history page of recently@@ -32,19 +32,29 @@ export async function prefetchRemoteHistories(deviceId: string,reader: Reader,isCurrent: () => boolean,+ sessionIds?: ReadonlySet<string>,): Promise<void> {if (!deviceId || isSharedTaskPeer(deviceId)) return;const run = running.get(deviceId);- if (run) { run.again = true; return; }- const state = { again: true };+ if (run) {+ run.again = true;+ if (!sessionIds) run.targets = null;+ else if (run.targets) for (const id of sessionIds) run.targets.add(id);+ return;+ }+ const state = { again: true, targets: sessionIds ? new Set(sessionIds) : null };running.set(deviceId, state);try {while (state.again && isCurrent()) {state.again = false;+ const targets = state.targets;+ state.targets = new Set<string>();const candidates = selectHistoryPrefetchSessions(remoteSessionStore.getSessions().filter((session) => session.deviceLinkDeviceId === deviceId),{+ limit: targets?.size,eligible: (session) => session.status === 'active' && session.pendingLocalCreation !== true+ && (!targets || (targets.has(session.id) && historyPrefetchVersion(session) !== undefined))&& remoteSessionStore.getSessionRetention(session.id) === 'regular'&& !isRemoteHistoryViewMounted(deviceId, session.id),prefetchedAt: (sessionId) => {@@ -58,6 +68,7 @@ export async function prefetchRemoteHistories(const authority = historyDiskAuthority(deviceId, session.id);const previous = detachedRemoteHistorySnapshot(deviceId, session.id) ?? await readHistoryDisk(authority);if (!historySnapshotCovers(previous, session)) {+ const readAt = Date.now();let page;try {page = await reader.readHistoryView(session.id);@@ -68,7 +79,7 @@ export async function prefetchRemoteHistories(}if (!isCurrent() || isRemoteHistoryViewMounted(deviceId, session.id)) continue;const snapshot = historySnapshotForCache(page, previous, fitsHistoryDisk);- if (!snapshot || !await writeHistoryDisk(authority, snapshot)) continue;+ if (!snapshot || !await writeHistoryDisk(authority, { ...snapshot, readAt })) continue;dropDetachedRemoteHistoryView(deviceId, session.id);}const version = historyPrefetchVersion(session);diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 13ed5976ee..d415380213 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1,4 +1,5 @@import { readTokenSpeedSnapshot, type TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';+import { historyTurnEnded } from '@cindy/maker-shared/message-window';import { normalizeTaskTags, reconcileTaskTags } from '@cindy/maker-shared';import {createContext,@@ -715,7 +716,7 @@ const pendingRefreshSessions = new Set<string>();const reseedHandlers = new Map<string, Set<() => void>>();// A whole-list read after app start or a reconnect reseed may follow a gap in live pushes.// Listeners read changed tasks ahead; ordinary list refreshes while pushes flow do not fire.-const sessionListRefreshListeners = new Set<(deviceId: string) => void>();+const sessionListRefreshListeners = new Set<(deviceId: string, sessionId?: string) => void>();const sessionListRefreshArmed = new Set<string>();const sessionListRefreshSeen = new Set<string>();const subs = new Set<() => void>();@@ -3533,6 +3534,7 @@ export const remoteSessionStore = {return;}let shouldReseedAfterPatch = false;+ const turnEnded = historyTurnEnded(shard.sessions[idx], patch);if (patch.status === 'deleted' || patch.status === 'archived') {protectedQuestions.delete(sessionId);visibleInteractionCache.delete(sessionId);@@ -3574,6 +3576,9 @@ export const remoteSessionStore = {shouldReseedAfterPatch = wasPinned && unpinned;}recomputeSessions();+ if (turnEnded && patch.status !== 'deleted' && patch.status !== 'archived') {+ for (const listener of sessionListRefreshListeners) listener(deviceId, sessionId);+ }if (shouldReseedAfterPatch) this.requestReseed(deviceId);},@@ -4604,8 +4609,9 @@ export const remoteSessionStore = {const fromList = payload.listMessage === true;if (fromList && (!sessionId || !listMessageWriteAllowed(sessionId, deviceId))) return;if (sessionId && message) {- this.appendMessage(sessionId, message, { listMessage: fromList });- if (fromList) void cacheSessionListMessage(deviceId, sessionId, message);+ const received = fromList ? { ...message, cacheReceivedAt: Date.now() } : message;+ this.appendMessage(sessionId, received, { listMessage: fromList });+ if (fromList) void cacheSessionListMessage(deviceId, sessionId, received);}return;}@@ -5402,8 +5408,8 @@ export const remoteSessionStore = {reseedHandlers.get(deviceId)?.forEach((handler) => handler());},- /** Whole-list reads that may follow missed pushes (first read per app run, reconnect reseed). */- onSessionListRefreshAfterGap(listener: (deviceId: string) => void): () => void {+ /** First/reconnected lists, or a specific task whose durable turn just ended. */+ onSessionHistoryPrefetchRequested(listener: (deviceId: string, sessionId?: string) => void): () => void {sessionListRefreshListeners.add(listener);return () => { sessionListRefreshListeners.delete(listener); };},diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex 4571bb1d1e..533e7882b9 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -132,6 +132,8 @@ export interface RemoteSessionRuntimePending {}export interface RemoteMessage {+ /** Local durable-push receipt time, retained by the display cache. */+ cacheReceivedAt?: number;id: string;clientId: string;sessionId: string;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 36ceee229e..493c3f6c96 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -164,6 +164,14 @@ schema、数据库或 Mobile 原生指纹。完整管理需要两端客户端更raw store 中晚于画面末尾的普通用户/助手行接在其后显示,直到最新页覆盖。仅控制端行为,不新增 channel、能力或主机改动。+收到轮次结束落库的 `lastTurnEndedAt` 更新时,两端也只补读该任务的最新一页,并按活动版本+去重;简介变化不触发补读。手机合并短时间内的补读请求,已打开任务仍由自身视图读取。+桌面打开时合并预收正文与磁盘旧历史,不因已有一条新消息跳过其余缓存。+两端缓存可选保存本地正文接收时间 `cacheReceivedAt` 与最新页读取起始时间 `readAt`:+旧历史中的同 ID 正文不能遮住读取开始后收到的新正文,后续权威读取可接管。缓存延迟写回+也保留期间收到的正文;删除、rewind 和账号隔离继续遵守既有作废屏障。这两个时间只在本机+比较,不作为主机消息修订号,不改变网络协议或扩展流式订阅范围。+`messages:list` / `messages:view` 的 options 可选携带 `messageBodies: { version: 1, known }`,known 是消息 ID 与主机提供的 SHA-256 正文指纹对。支持的主机在授权、净化之后返回`message-bodies-v1` 包装,只省略指纹吻合的正文,顺序、分页与消息元数据始终重新读取。diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.tsindex d0d36f691c..b76cf08745 100644--- a/packages/maker-shared/src/historyView.ts+++ b/packages/maker-shared/src/historyView.ts@@ -28,6 +28,8 @@ export interface HistoryMessageSource {content: unknown;createdAt: string;rowid?: number;+ /** Controller-local receipt time of a durable push; never a Host revision. */+ cacheReceivedAt?: number;toolUseId?: string | null;agentMeta?: object | null;/** Host outline only; transferred in work summaries, never as a replacement body. */diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.tsindex 4f0130c618..ac0a98c61b 100644--- a/packages/maker-shared/src/historyViewController.ts+++ b/packages/maker-shared/src/historyViewController.ts@@ -26,6 +26,8 @@ export interface HistoryViewSnapshot<T extends HistoryMessageSource> {* disk, or was read before the view went inactive/offline. Cleared by a latest-page read.*/stale?: boolean;+ /** Controller-local start of the latest page read, also retained in its disk cache. */+ readAt?: number;}export interface HistoryViewTransport<T extends HistoryMessageSource> {@@ -158,6 +160,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {if (!this.isActive() || this.state.loading || (older && !this.state.hasMore)) return;const generation = this.generation;const before = older ? this.state.nextCursor ?? undefined : undefined;+ const readAt = Date.now();this.publish({ loading: true, error: null });try {const page = await this.transport.page(before);@@ -179,7 +182,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {const stableItems = items.length === this.state.items.length&& items.every((item, index) => item === this.state.items[index]) ? this.state.items : items;this.publish({ items: stableItems, ready: true, loading: false,- ...(older ? {} : { stale: false }),+ ...(older ? {} : { stale: false, readAt }),hasMore: retained.hasMore, nextCursor: retained.nextCursor });for (const summary of historyWorkSummaries(items)) {if (this.state.expanded.has(summary.key)) void this.loadDetails(summary);@@ -355,7 +358,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 });+ nextCursor: null, hasMore: false, loading: false, error: null, stale: false, readAt: undefined });this.sendIntent();if (this.active) void this.refresh();}diff --git a/packages/maker-shared/src/historyViewHandoff.ts b/packages/maker-shared/src/historyViewHandoff.tsindex e85021c1e8..24eb705d2d 100644--- a/packages/maker-shared/src/historyViewHandoff.ts+++ b/packages/maker-shared/src/historyViewHandoff.ts@@ -45,6 +45,11 @@ export class HistoryViewHandoff<T extends HistoryMessageSource> {const available = historyViewLeaves(snapshot.items).flatMap((item) => item.type === 'messages' ? item.messages : []);for (const detail of snapshot.details.values()) available.push(...detail.messages);const history = new Map(available.map(row => [row.clientId, row]));+ // IDs and createdAt do not change when a saved body is updated. A push+ // received after this page's read began must remain visible even if that+ // older page arrives later. Only local receipt/read times are compared.+ const receivedAfterRead = (row: T) => typeof row.cacheReceivedAt === 'number'+ && row.cacheReceivedAt >= (snapshot.readAt ?? 0);const current = new Set(raw.map(row => row.clientId));for (const id of this.pending) if (!current.has(id)) this.pending.delete(id);for (const row of raw) {@@ -59,11 +64,23 @@ export class HistoryViewHandoff<T extends HistoryMessageSource> {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).- for (const id of this.tail) if (!current.has(id) || history.has(id)) this.tail.delete(id);+ 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);+ }const endMs = snapshot.stale ? historyViewEndMs(snapshot) : 0;for (const row of raw) {- if ((row.role !== 'user' && row.role !== 'assistant') || history.has(row.clientId)) continue;- if (snapshot.stale && Date.parse(row.createdAt) > endMs) this.tail.add(row.clientId);+ if (row.role !== 'user' && row.role !== 'assistant') continue;+ const known = history.get(row.clientId);+ if (known) {+ if (receivedAfterRead(row)) {+ this.tail.add(row.clientId);+ history.set(row.clientId, liveContentWithHistoryOrder(row, known));+ }+ continue;+ }+ if (receivedAfterRead(row) || (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/historyViewPrefetch.ts b/packages/maker-shared/src/historyViewPrefetch.tsindex 259c7356cb..8d00672bc4 100644--- a/packages/maker-shared/src/historyViewPrefetch.ts+++ b/packages/maker-shared/src/historyViewPrefetch.ts@@ -12,6 +12,12 @@ export interface HistoryPrefetchSession {lastTurnEndedAt?: number | null;}+/** Durable turn-end patches, rather than activity text, trigger read ahead. */+export function historyTurnEnded(previous: { lastTurnEndedAt?: number | null }, patch: { lastTurnEndedAt?: unknown }): boolean {+ return typeof patch.lastTurnEndedAt === 'number' && Number.isFinite(patch.lastTurnEndedAt)+ && patch.lastTurnEndedAt > (previous.lastTurnEndedAt ?? 0);+}+/** A turn that started after the last one ended keeps writing rows without touching `updatedAt`. */function isTurnRunning(session: HistoryPrefetchSession): boolean {return typeof session.activeTurnStartedAt === 'number'