Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 保留完成补读目标并用本地序号接管缓存
Dash06abdd38f622
diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.tsindex aec02ad1fc..ff6f62c0bf 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts@@ -340,18 +340,18 @@ describe('readMessages / writeMessages', () => {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 updated = { ...old, content: 'updated', cacheReceipt: { run: 'renderer', order: 2 } };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,+ nextCursor: null, hasMore: false, ready: true, loading: false, error: null, readReceipt: { run: 'renderer', order: 1 },};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);+ expect(decodeRemoteHistory(cached.historyView)?.readReceipt).toEqual({ run: 'renderer', order: 1 });await c.writeMessages('dev', 'session', [], token.invalidation, token.ownerRoot, token.accountCounter,- encodeRemoteHistory({ ...snapshot, readAt: 300 }));+ encodeRemoteHistory({ ...snapshot, readReceipt: { run: 'restarted-renderer', order: 1 } }));expect((await c.readMessagesWithInvalidation('dev', 'session')).messages).toEqual([]);});diff --git a/apps/desktop/src/main/device-link/mirrorCacheStore.ts b/apps/desktop/src/main/device-link/mirrorCacheStore.tsindex c21c96191c..829ae9b8c2 100644--- a/apps/desktop/src/main/device-link/mirrorCacheStore.ts+++ b/apps/desktop/src/main/device-link/mirrorCacheStore.ts@@ -31,6 +31,7 @@*/import path from 'node:path';+import { historyCacheReceiptFollows } from '@cindy/maker-shared/message-window';import fsp from 'node:fs/promises';import { createHash, randomBytes } from 'node:crypto';@@ -1166,8 +1167,7 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {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));+ const arrivals = rows.filter(row => historyCacheReceiptFollows(row.cacheReceipt, history.readReceipt));retainedListReceipts = arrivals.length > 0;normalized = normalizeMessages([...normalized, ...arrivals]);}diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.tsindex 11ccffbe62..e16dee3e64 100644--- a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest';import { readFileSync } from 'node:fs';import {- HistoryViewController, HistoryViewHandoff, projectHistoryView, renderHistoryView, historyViewLeaves,+ HistoryViewController, HistoryViewHandoff, projectHistoryView, renderHistoryView, historyViewLeaves, nextHistoryCacheReceipt,} from '@cindy/maker-shared/message-window';import { buildRenderItems, groupWorkRuns, selectVisibleMessages, collectTurnFinalAssistantClientIds,findLastUserMessageClientId, planSessionBelongsToLatestUserTurn } from '../components/chat/MessageStream';@@ -57,11 +57,12 @@ describe('desktop remote history uses the shared live-to-history handoff', () =>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 };+ const readReceipt = nextHistoryCacheReceipt();+ const received = { ...old, content: 'updated received body', cacheReceipt: nextHistoryCacheReceipt() };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 }));+ readReceipt }));expect(render([received]).text).toContain('updated received body');expect(render([received]).text).not.toContain('old cached body');setSource([{ ...old, content: 'authoritative body' }]);diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.tsindex 6ec7cefd67..c8bc066bdc 100644--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts@@ -291,20 +291,22 @@ describe('冷缓存 hydrate', () => {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 () => {+ it.each([true, false])('shows list text while pending and only its owner persists receipts (owner=%s)', async (ownsRemoteListCache) => {const s = sid();setDataOwnerGeneration('owner-a', 1);registerRemote(s);let push!: Parameters<typeof window.electronAPI.deviceLink.onRemotePush>[0];window.electronAPI.deviceLink.onRemotePush = vi.fn(callback => { push = callback; return () => {}; });- makerChatStore.initGlobalListeners();+ makerChatStore.initGlobalListeners({ ownsRemoteListCache });const row = dbMessage(s, 'prefetched', '完整长正文'.repeat(2000), '2026-10-10T00:00:00.000Z');push({ deviceId: DEVICE_ID, channel: 'local-db:messages:created', payload: { sessionId: s, listMessage: true, message: row } });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([]);- expect(putMessages.mock.calls.find(([device, session]) => device === DEVICE_ID && session === s)?.[2])- .toEqual([{ ...row, cacheReceivedAt: expect.any(Number) }]);+ if (ownsRemoteListCache) {+ expect(putMessages.mock.calls.find(([device, session]) => device === DEVICE_ID && session === s)?.[2])+ .toEqual([{ ...row, cacheReceipt: { run: expect.any(String), order: expect.any(Number) } }]);+ } else expect(putMessages).not.toHaveBeenCalled();remoteListPromise = new Promise<Message[]>(() => {});makerChatStore.ensureInitialMessages(s);await flush(30);@@ -464,6 +466,39 @@ describe('冷缓存 hydrate', () => {expect(invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(1);});+ // Mirror the mobile queue regression through Desktop's real store and disk writer.+ it.each([false, true])('keeps a completion outside the queued reconnect budget (recent first=%s)', async (recentFirst) => {+ const held = sid();+ const done = sid();+ const running = Array.from({ length: 5 }, () => sid());+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [+ { id: held, status: 'active', updatedAt: '2026-10-11T00:00:00Z' },+ { id: done, status: 'active', updatedAt: '2026-10-11T00:00:01Z', lastTurnEndedAt: 100 },+ ...running.map(id => ({ id, status: 'active', updatedAt: '2026-10-11T00:00:09Z', activeTurnStartedAt: 100 })),+ ] as never);+ let release!: () => void;+ const original = invoke.getMockImplementation()!;+ invoke.mockImplementation((async (_device: string, channel: string, args: unknown[]) => {+ expect(channel).toBe('local-db:messages:view');+ const id = String(args[0]);+ if (id === held) await new Promise<void>(resolve => { release = resolve; });+ return { version: 1, items: projectHistoryView([dbMessage(id, 'reply', id, '2026-10-11T00:00:10Z')], false), hasMore: false, nextCursor: null };+ }) as unknown as Parameters<typeof invoke.mockImplementation>[0]);+ try {+ const first = makerChatStore.prefetchRemoteHistories(DEVICE_ID, new Set([held]));+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));+ const reconnect = () => makerChatStore.prefetchRemoteHistories(DEVICE_ID);+ const completion = () => makerChatStore.prefetchRemoteHistories(DEVICE_ID, new Set([done]));+ if (recentFirst) { await reconnect(); await completion(); }+ else { await completion(); await reconnect(); }+ release();+ await first;+ await flush(30);+ expect(invoke.mock.calls.map(([, , args]) => args[0])).toEqual(expect.arrayContaining([done, ...running]));+ expect(putMessages.mock.calls.find(([, id]) => id === done)?.[6]).toContain(done);+ } finally { invoke.mockImplementation(original); }+ });+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' }];@@ -485,9 +520,9 @@ describe('冷缓存 hydrate', () => {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 latest = { ...old, content: 'latest body', cacheReceipt: { run: 'cached', order: 2 } };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 });+ readReceipt: { run: 'cached', order: 1 }, ready: true, loading: false, error: null, nextCursor: null, hasMore: false });let reads = 0;getMessages.mockImplementation(async () => {if (++reads === 2 && delayed) await flush(30);diff --git a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsxindex 2d9cbeecf4..f0a6da31e7 100644--- a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx@@ -71,7 +71,7 @@ export function SidebarWindowLayout() {useEffect(() => {// 子窗口需要实时事件来维护面板内容,但认证失败后的凭证读取、会话重启与消息重发// 必须只由主 renderer 执行,避免多个 renderer 对同一远程任务并发重试。- makerChatStore.initGlobalListeners({ ownsRemoteAuthRetry: false });+ makerChatStore.initGlobalListeners({ ownsRemoteAuthRetry: false, ownsRemoteListCache: false });}, []);const isMac = window.electronAPI?.platform === 'darwin';const [ctx, setCtx] = useState<SidebarWindowContext | null>(null);diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex a68a4ec3bd..e69d2f4fcf 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -521,8 +521,8 @@ export interface AgentSwitchContent {}export interface Message {- /** Local durable-push receipt time, retained by the display cache. */- cacheReceivedAt?: number;+ /** Local durable-push order, retained by the display cache. */+ cacheReceipt?: import('@cindy/maker-shared/message-window').HistoryCacheReceipt;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 e4fe619e50..de58bf60f6 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -40,6 +40,7 @@ import { parsePluginConnectionInput, type InputHandoffSnapshot } from '@cindy/deimport { HISTORY_WORK_PATCH_CHANNEL, HistoryViewController, isHistoryViewUnavailable, mapHistoryViewMessages, historyViewLeaves, historyWorkSummaries, historyPrefetchVersion, historySnapshotCovers, historySnapshotForCache, selectHistoryPrefetchSessions, type HistoryViewPage, type HistoryDetailPage, type HistoryWorkPatch } from '@cindy/maker-shared/message-window';import type { CindyRegion } from '@cindy/maker-shared/brand-identity';+import { nextHistoryCacheReceipt, historyCacheReceiptFollows, mergeHistoryPrefetchRequest, type HistoryCacheReceipt, type HistoryPrefetchRequest } from '@cindy/maker-shared/message-window';import { SESSION_SYNC_CHANNEL } from '@cindy/device-link';import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from '@cindy/maker-shared/message-window';import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';@@ -409,8 +410,8 @@ export interface AskUserQuestionItem {}export interface ChatMessage {- /** Local durable-push receipt time, retained by the display cache. */- cacheReceivedAt?: number;+ /** Local durable-push order, retained by the display cache. */+ cacheReceipt?: HistoryCacheReceipt;/** Private Bot reply provenance, projected from persisted/live agent metadata. */botPrivateReply?: boolean;botLearning?: import('@cindy/maker-shared/bot-learning').BotLearningReceipt[];@@ -7936,6 +7937,8 @@ interface GlobalListenerOptions {* messages, or persist a retry failure independently.*/ownsRemoteAuthRetry?: boolean;+ /** The primary renderer owns list-cache receipts; auxiliary windows only display pushes. */+ ownsRemoteListCache?: boolean;}function initGlobalListeners(options: GlobalListenerOptions = {}): void {@@ -9112,9 +9115,9 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {// 远程会话的持久化消息(接管路径)→ 注入 in-memory state(同本机)。const payload = push.payload as { sessionId?: string; message?: Message };const row = payload?.message && listMessage- ? { ...payload.message, cacheReceivedAt: Date.now() } : payload?.message;+ ? { ...payload.message, cacheReceipt: nextHistoryCacheReceipt() } : payload?.message;handleMessageCreatedRaw({ ...payload, message: row }, remoteIngress);- if (listMessage && push.deviceId && inboundSid) {+ if (listMessage && options.ownsRemoteListCache !== false && push.deviceId && inboundSid) {if (row && !isBeforeOrAtRendererClearBoundary(inboundSid, row.createdAt)) persistListMessage(push.deviceId, inboundSid, row);}break;@@ -11488,9 +11491,9 @@ function hydrateRemoteMessagesFromCache(sessionId: string): void {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);+ return !existing?.isStreaming+ && historyCacheReceiptFollows(message.cacheReceipt, history?.readReceipt, history?.stale)+ && historyCacheReceiptFollows(message.cacheReceipt, existing?.cacheReceipt);}).map(message => message.clientId));// hasMoreMessages 显式压成 false:缓存窗口期间不许向上翻页。翻回来的权威老行// 不带 cacheHydrated,首拉落地剔除缓存行后会在窗口中间留出一段洞,得靠后续翻页@@ -11701,7 +11704,7 @@ function createRemoteHistoryView(sessionId: string) {setState(sessionId, (state) => ({ ...state, historyLoaded: true,messages: confirmRemoteUsers(mergeMessages(available, state.messages.filter((message) => !message.cacheHydrated- || (message.cacheReceivedAt !== undefined && message.cacheReceivedAt >= (snapshot.readAt ?? 0))), { addOnly: true }),+ || historyCacheReceiptFollows(message.cacheReceipt, snapshot.readReceipt, snapshot.stale)), { addOnly: true }),new Set(available.filter((message) => message.role === 'user').map((message) => message.clientId)),),hasMoreMessages: snapshot.hasMore, isLoadingMore: view.isLoadingOlder(),@@ -11719,7 +11722,7 @@ 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; targets: Set<string> | null }>();+const remoteHistoryPrefetchRuns = new Map<string, { again: boolean; request: HistoryPrefetchRequest }>();/*** After a list read that may follow missed pushes (bootstrap/reconnect), read the latest@@ -11730,11 +11733,10 @@ async function prefetchRemoteHistories(deviceId: string, sessionIds?: ReadonlySeconst run = remoteHistoryPrefetchRuns.get(deviceId);if (run) {run.again = true;- if (!sessionIds) run.targets = null;- else if (run.targets) for (const id of sessionIds) run.targets.add(id);+ run.request = mergeHistoryPrefetchRequest(run.request, sessionIds);return;}- const state = { again: true, targets: sessionIds ? new Set(sessionIds) : null };+ const state = { again: true, request: mergeHistoryPrefetchRequest(undefined, sessionIds) };remoteHistoryPrefetchRuns.set(deviceId, state);const owner = getDataOwnerGeneration();const key = (sessionId: string) => JSON.stringify([deviceId, sessionId]);@@ -11744,12 +11746,11 @@ async function prefetchRemoteHistories(deviceId: string, sessionIds?: ReadonlySetry {while (state.again) {state.again = false;- const targets = state.targets;- state.targets = new Set<string>();+ const request = state.request;+ state.request = mergeHistoryPrefetchRequest(undefined, new Set());const candidates = selectHistoryPrefetchSessions(remoteProjectsStore.getDeviceSessions(deviceId, 'active'), {- limit: targets?.size,- eligible: (session) => session.status === 'active' && session.source !== 'scheduler' && !getRemoteHistoryView(session.id)- && (!targets || (targets.has(session.id) && historyPrefetchVersion(session) !== undefined)),+ limit: request.recent ? undefined : 0, targets: request.targets,+ eligible: (session) => session.status === 'active' && session.source !== 'scheduler' && !getRemoteHistoryView(session.id),prefetchedAt: (sessionId) => {const entry = remoteHistoryPrefetchedAt.get(key(sessionId));return entry && isDataOwnerGenerationCurrent(entry.owner)@@ -11763,7 +11764,7 @@ async function prefetchRemoteHistories(deviceId: string, sessionIds?: ReadonlySeif (!historySnapshotCovers(previous, session)) {// Capture write authority before the read, like an open view does.const write = remoteHistoryCacheWriter(deviceId, session.id);- const readAt = Date.now();+ const readReceipt = nextHistoryCacheReceipt();let page: HistoryViewPage<Message>;try {page = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:messages:view',@@ -11780,7 +11781,7 @@ async function prefetchRemoteHistories(deviceId: string, sessionIds?: ReadonlySeconst snapshot = historySnapshotForCache({ ...page, items }, previous,(candidate) => fitsRemoteHistoryCache(encodeRemoteHistory(candidate)));if (!snapshot) continue;- write({ ...snapshot, readAt });+ write({ ...snapshot, readReceipt });}const version = historyPrefetchVersion(session);if (version !== undefined) {@@ -18691,7 +18692,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 receiptById = new Map(serverMsgs.map((m) => [m.clientId, m.cacheReceipt]));const remoteContentTruncatedById = new Map(serverMsgs.map((m) => [m.clientId, m.agentMeta?.remoteContentTruncated === true]),);@@ -19284,7 +19285,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 cacheReceipt = receiptById.get(cm.clientId);const remoteContentTruncated = remoteContentTruncatedById.get(cm.clientId) === true;const remoteRowsTrimmed = remoteRowsTrimmedById.get(cm.clientId) === true;const legacyUserTurnCost = legacyUserTurnCosts.get(cm.clientId);@@ -19304,7 +19305,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {...(iso ? { createdAt: iso } : {}),...(typeof serverId === 'string' && serverId.length > 0 ? { id: serverId } : {}),...(rowid !== undefined ? { rowid } : {}),- ...(cacheReceivedAt !== undefined ? { cacheReceivedAt } : {}),+ ...(cacheReceipt !== undefined ? { cacheReceipt } : {}),...(remoteContentTruncated ? { remoteContentTruncated: true } : {}),...(remoteRowsTrimmed ? { remoteRowsTrimmed: true } : {}),};diff --git a/apps/desktop/src/shared/remoteHistoryCache.ts b/apps/desktop/src/shared/remoteHistoryCache.tsindex 851417c9ca..6233f7b13b 100644--- a/apps/desktop/src/shared/remoteHistoryCache.ts+++ b/apps/desktop/src/shared/remoteHistoryCache.ts@@ -1,5 +1,5 @@import type { HistoryMessageSource, HistoryViewSnapshot } from '@cindy/maker-shared/message-window';-import { historyWorkSummaries } from '@cindy/maker-shared/message-window';+import { historyWorkSummaries, isHistoryCacheReceipt } from '@cindy/maker-shared/message-window';/** One eligibility rule for write admission, serialization and old cache reads. */export function currentRemoteHistoryDetails<T extends HistoryMessageSource>(snapshot: HistoryViewSnapshot<T>) {@@ -111,7 +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 } : {}),+ ...(isHistoryCacheReceipt(value.readReceipt) ? { readReceipt: value.readReceipt } : {}),ready: true,loading: false,error: null,@@ -133,7 +133,7 @@ export function encodeRemoteHistory<T extends HistoryMessageSource>(expanded: [...snapshot.expanded],hasMore: snapshot.hasMore,nextCursor: snapshot.nextCursor,- readAt: snapshot.readAt,+ readReceipt: snapshot.readReceipt,},(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 5fef681652..bc97d2afb2 100644--- a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts+++ b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from 'vitest';-import { HistoryViewController, HistoryViewHandoff, projectHistoryView } from '@cindy/maker-shared/message-window';+import { describe, expect, it, vi } from 'vitest';+import { HistoryViewController, HistoryViewHandoff, projectHistoryView, nextHistoryCacheReceipt } from '@cindy/maker-shared/message-window';import { buildMobileHistoryRenderItems } from '../session/mobileHistoryRender';import type { RemoteMessage } from '../session/types';@@ -17,7 +17,7 @@ describe('mobile history handoff', () => {// 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 received = { ...old, content: 'updated answer', cacheReceipt: { run: 'cached', order: 2 } };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 }),@@ -26,7 +26,7 @@ describe('mobile history handoff', () => {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 }));+ loading: false, ready: true, error: null, readReceipt: { run: 'cached', order: 1 } }));const handoff = createHandoff();const render = (snapshot = view.getSnapshot(), currentHandoff = handoff) => {const state = currentHandoff.reconcile(snapshot, [received]);@@ -40,10 +40,42 @@ describe('mobile history handoff', () => {// 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(render({ ...view.getSnapshot(), stale: false, readReceipt: { run: 'cached', order: 3 } })).toEqual(['old answer']);expect(handoff.reconcile(view.getSnapshot(), []).tail.size).toBe(0);});+ // A clock correction must not make an old receipt beat every future Host read,+ // including receipts restored from a previous app run.+ it.each([false, true])('retires old receipts after a clock rollback (previous run=%s)', async (previousRun) => {+ const clock = vi.spyOn(Date, 'now').mockReturnValue(50_000);+ const cachedRead = previousRun ? { run: 'previous-snapshot', order: 1 } : nextHistoryCacheReceipt();+ const receipt = previousRun ? { run: 'previous-run', order: 999_999 } : nextHistoryCacheReceipt();+ const old = { ...row('answer'), content: 'cached body', cacheReceipt: receipt };+ const view = new HistoryViewController<RemoteMessage>({+ page: async () => ({ version: 1, items: projectHistoryView([{ ...row('answer'), content: 'host body' }], false), hasMore: false, nextCursor: null }),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }), expanded: async () => undefined,+ });+ const handoff = createHandoff();+ const render = () => {+ const snapshot = view.getSnapshot();+ const state = handoff.reconcile(snapshot, [old]);+ 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.body);+ };+ try {+ view.setActive(false);+ await view.restoreCachedView(async () => ({ items: projectHistoryView([{ ...row('answer'), content: 'older body' }], false),+ details: new Map(), expanded: new Set(), nextCursor: null, hasMore: false, loading: false, ready: true, error: null, readReceipt: cachedRead }));+ expect(render()).toEqual(['cached body']);+ clock.mockReturnValue(100);+ view.setActive(true);+ await view.refresh();+ expect(render()).toEqual(['host body']);+ view.setActive(false);+ expect(render()).toEqual(['host body']); // Leaving the page must not revive the retired receipt.+ } finally { view.setActive(false); clock.mockRestore(); }+ });+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 2d7766c4fd..bf70f1bd13 100644--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts@@ -199,7 +199,7 @@ describe('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 };+ const newer = { ...old, content: 'updated', cacheReceipt: { ...authority.capturedReceipt, order: authority.capturedReceipt.order + 1 } };await cacheSessionListMessage('host-a', 'session-1', newer);await cacheSessionMessagesIfCurrent(authority, [old]);expect(await getCachedSessionMessages('host-a', 'session-1')).toEqual([newer]);diff --git a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.tsindex dabc35df4b..3c51492774 100644--- a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts+++ b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts@@ -43,6 +43,31 @@ afterEach(async () => {});describe('history read ahead after a list refresh', () => {+ // A bounded reconnect read is not a superset of completion targets. Hold one+ // real read pending, then enqueue both request kinds in either order.+ it.each([false, true])('retains completion targets alongside a queued reconnect (recent first=%s)', async (recentFirst) => {+ setMobileAuthOwner('user-1');+ const running = Array.from({ length: 5 }, (_, i) => session(`running-${i}`, '2026-10-11T00:00:09Z', { activeTurnStartedAt: 100 }));+ remoteSessionStore.setDeviceSessions(DEVICE, 'Mac', [+ session('held', '2026-10-11T00:00:01Z'), session('done', '2026-10-11T00:00:02Z', { lastTurnEndedAt: 100 }), ...running,+ ]);+ let release!: () => void;+ const reader = { readHistoryView: vi.fn(async (id: string) => {+ if (id === 'held') await new Promise<void>(resolve => { release = resolve; });+ return page([row(id, 9)]);+ }) };+ const first = prefetchRemoteHistories(DEVICE, reader, () => true, new Set(['held']));+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));+ const reconnect = () => prefetchRemoteHistories(DEVICE, reader, () => true);+ const completion = () => prefetchRemoteHistories(DEVICE, reader, () => true, new Set(['done']));+ if (recentFirst) { await reconnect(); await completion(); }+ else { await completion(); await reconnect(); }+ release();+ await first;+ expect(reader.readHistoryView.mock.calls.map(([id]) => id)).toEqual(expect.arrayContaining(['done', ...running.map(s => s.id)]));+ expect((await readHistoryDisk(historyDiskAuthority(DEVICE, 'done')))?.items).toEqual(page([row('done', 9)]).items);+ });+// 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 () => {diff --git a/apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx b/apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsxindex 834c18979d..d7751ac232 100644--- a/apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx+++ b/apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx@@ -1,4 +1,5 @@import { useEffect, useRef } from 'react';+import { mergeHistoryPrefetchRequest, type HistoryPrefetchRequest } from '@cindy/maker-shared/message-window';import { useAuth } from '@/auth/AuthContext';import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';@@ -18,22 +19,17 @@ export function RemoteHistoryPrefetchBridge() {const generation = accountGeneration;const isCurrent = () => latest.current.accountGeneration === generation;const timers = new Map<string, ReturnType<typeof setTimeout>>();- const pending = new Map<string, Set<string> | null>();+ const pending = new Map<string, HistoryPrefetchRequest>();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);- }+ pending.set(deviceId, mergeHistoryPrefetchRequest(pending.get(deviceId), sessionId ? new Set([sessionId]) : undefined));if (timers.has(deviceId)) return;timers.set(deviceId, setTimeout(() => {timers.delete(deviceId);- const ids = pending.get(deviceId);+ const request = pending.get(deviceId)!;pending.delete(deviceId);if (!isCurrent()) return;const reader = createMobileMakerTransport({ deviceId, invoke: latest.current.invoke, isCurrent });- void prefetchRemoteHistories(deviceId, reader, isCurrent, ids ?? undefined);+ void prefetchRemoteHistories(deviceId, reader, isCurrent, request.targets, request.recent);}, PREFETCH_DELAY_MS));});return () => {diff --git a/apps/mobile/src/session/mobileSessionMessageCache.ts b/apps/mobile/src/session/mobileSessionMessageCache.tsindex 04d09902ae..9ab453c34e 100644--- a/apps/mobile/src/session/mobileSessionMessageCache.ts+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts@@ -1,4 +1,5 @@import { messageCacheStorage } from './messageCacheStorage';+import { nextHistoryCacheReceipt, historyCacheReceiptFollows, type HistoryCacheReceipt } from '@cindy/maker-shared/message-window';import { getMobileAuthOwner, isMobileAuthOwnerCurrent, type MobileAuthOwnerGeneration } from '@/auth/authOwnerGeneration';import { MESSAGE_PAGE_SIZE } from '@/session/messagePaging';import type { RemoteMessage } from '@/session/types';@@ -37,7 +38,7 @@ let globalClearInProgress = false;let activeGlobalClear: Promise<void> | null = null;export interface SessionMessageCacheWriteAuthority {- readonly capturedAt: number;+ readonly capturedReceipt: HistoryCacheReceipt;readonly key: string;readonly owner: MobileAuthOwnerGeneration;readonly globalEpoch: number;@@ -75,7 +76,7 @@ export function captureSessionMessageCacheWriteAuthority(const key = safeStorageKey(deviceId, sessionId);if (!key) return null;return {- capturedAt: Date.now(),+ capturedReceipt: nextHistoryCacheReceipt(),key,owner,globalEpoch: globalWriteEpoch,@@ -110,7 +111,7 @@ export async function cacheSessionMessagesIfCurrent(}const arrivals = isRecord(previous) && Array.isArray(previous.messages)? normalizeCachedMessages(previous.messages).filter(row =>- typeof row.cacheReceivedAt === 'number' && row.cacheReceivedAt >= authority.capturedAt) : [];+ historyCacheReceiptFollows(row.cacheReceipt, authority.capturedReceipt)) : [];if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;normalized = normalizeCachedMessages([...normalized, ...arrivals]);const payload: StoredSessionMessageCache = {diff --git a/apps/mobile/src/session/remoteHistoryDiskCache.ts b/apps/mobile/src/session/remoteHistoryDiskCache.tsindex e9030fc512..565cf9b8cd 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, readAt: snapshot.readAt, items: items(snapshot.items),+ const text = JSON.stringify({ version: 1, readReceipt: snapshot.readReceipt, 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 4a312a191b..5307ecbe02 100644--- a/apps/mobile/src/session/remoteHistoryPrefetch.ts+++ b/apps/mobile/src/session/remoteHistoryPrefetch.ts@@ -4,6 +4,8 @@ import {historySnapshotForCache,isHistoryViewUnavailable,selectHistoryPrefetchSessions,+ mergeHistoryPrefetchRequest, type HistoryPrefetchRequest,+ nextHistoryCacheReceipt,} from '@cindy/maker-shared/message-window';import { isSharedTaskPeer } from '@cindy/device-link';import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';@@ -21,7 +23,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; targets: Set<string> | null }>();+const running = new Map<string, { again: boolean; request: HistoryPrefetchRequest }>();/*** After a list read that may follow missed pushes, read the latest history page of recently@@ -33,28 +35,27 @@ export async function prefetchRemoteHistories(reader: Reader,isCurrent: () => boolean,sessionIds?: ReadonlySet<string>,+ recent = sessionIds === undefined,): Promise<void> {if (!deviceId || isSharedTaskPeer(deviceId)) return;const run = running.get(deviceId);if (run) {run.again = true;- if (!sessionIds) run.targets = null;- else if (run.targets) for (const id of sessionIds) run.targets.add(id);+ run.request = mergeHistoryPrefetchRequest(run.request, sessionIds, recent);return;}- const state = { again: true, targets: sessionIds ? new Set(sessionIds) : null };+ const state = { again: true, request: mergeHistoryPrefetchRequest(undefined, sessionIds, recent) };running.set(deviceId, state);try {while (state.again && isCurrent()) {state.again = false;- const targets = state.targets;- state.targets = new Set<string>();+ const request = state.request;+ state.request = mergeHistoryPrefetchRequest(undefined, new Set());const candidates = selectHistoryPrefetchSessions(remoteSessionStore.getSessions().filter((session) => session.deviceLinkDeviceId === deviceId),{- limit: targets?.size,+ limit: request.recent ? undefined : 0, targets: request.targets,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) => {@@ -68,7 +69,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();+ const readReceipt = nextHistoryCacheReceipt();let page;try {page = await reader.readHistoryView(session.id);@@ -79,7 +80,7 @@ export async function prefetchRemoteHistories(}if (!isCurrent() || isRemoteHistoryViewMounted(deviceId, session.id)) continue;const snapshot = historySnapshotForCache(page, previous, fitsHistoryDisk);- if (!snapshot || !await writeHistoryDisk(authority, { ...snapshot, readAt })) continue;+ if (!snapshot || !await writeHistoryDisk(authority, { ...snapshot, readReceipt })) 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 d415380213..0693106441 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1,5 +1,5 @@import { readTokenSpeedSnapshot, type TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';-import { historyTurnEnded } from '@cindy/maker-shared/message-window';+import { historyTurnEnded, nextHistoryCacheReceipt } from '@cindy/maker-shared/message-window';import { normalizeTaskTags, reconcileTaskTags } from '@cindy/maker-shared';import {createContext,@@ -4609,7 +4609,7 @@ export const remoteSessionStore = {const fromList = payload.listMessage === true;if (fromList && (!sessionId || !listMessageWriteAllowed(sessionId, deviceId))) return;if (sessionId && message) {- const received = fromList ? { ...message, cacheReceivedAt: Date.now() } : message;+ const received = fromList ? { ...message, cacheReceipt: nextHistoryCacheReceipt() } : message;this.appendMessage(sessionId, received, { listMessage: fromList });if (fromList) void cacheSessionListMessage(deviceId, sessionId, received);}diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex 533e7882b9..02a008e7f8 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -132,8 +132,8 @@ export interface RemoteSessionRuntimePending {}export interface RemoteMessage {- /** Local durable-push receipt time, retained by the display cache. */- cacheReceivedAt?: number;+ /** Local durable-push order, retained by the display cache. */+ cacheReceipt?: import('@cindy/maker-shared/message-window').HistoryCacheReceipt;id: string;clientId: string;sessionId: string;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 493c3f6c96..8917b4402a 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -166,11 +166,13 @@ raw store 中晚于画面末尾的普通用户/助手行接在其后显示,收到轮次结束落库的 `lastTurnEndedAt` 更新时,两端也只补读该任务的最新一页,并按活动版本去重;简介变化不触发补读。手机合并短时间内的补读请求,已打开任务仍由自身视图读取。+重连补读与完成补读合并时保留两者的并集,指定的已完成任务不受最近 5 个任务的预算挤占。桌面打开时合并预收正文与磁盘旧历史,不因已有一条新消息跳过其余缓存。-两端缓存可选保存本地正文接收时间 `cacheReceivedAt` 与最新页读取起始时间 `readAt`:+两端缓存可选保存本地正文接收标记 `cacheReceipt` 与最新页读取起始标记 `readReceipt`:旧历史中的同 ID 正文不能遮住读取开始后收到的新正文,后续权威读取可接管。缓存延迟写回-也保留期间收到的正文;删除、rewind 和账号隔离继续遵守既有作废屏障。这两个时间只在本机-比较,不作为主机消息修订号,不改变网络协议或扩展流式订阅范围。+也保留期间收到的正文;删除、rewind 和账号隔离继续遵守既有作废屏障。标记使用运行期 ID+及递增序号,不依赖墙钟;冷启动先复用旧运行期缓存,成功的权威读取接管并退役旧标记。+标记不作为主机消息修订号,不改变网络协议或扩展流式订阅范围。`messages:list` / `messages:view` 的 options 可选携带 `messageBodies: { version: 1, known }`,known 是消息 ID 与主机提供的 SHA-256 正文指纹对。支持的主机在授权、净化之后返回diff --git a/packages/maker-shared/src/__tests__/historyViewPrefetch.test.ts b/packages/maker-shared/src/__tests__/historyViewPrefetch.test.tsindex 7bd310cce3..94025edb74 100644--- a/packages/maker-shared/src/__tests__/historyViewPrefetch.test.ts+++ b/packages/maker-shared/src/__tests__/historyViewPrefetch.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { historyPrefetchVersion, historySnapshotCovers, historySnapshotForCache, historySnapshotFromPage, selectHistoryPrefetchSessions } from '../historyViewPrefetch.js';+import { historyPrefetchVersion, historySnapshotCovers, historySnapshotForCache, historySnapshotFromPage, selectHistoryPrefetchSessions, mergeHistoryPrefetchRequest } from '../historyViewPrefetch.js';import type { HistoryViewSnapshot } from '../historyViewController.js';import type { HistoryMessageSource, HistoryViewItem, HistoryWorkSummary } from '../historyView.js';@@ -12,6 +12,19 @@ const work = (key: string, revision: string, endedAtMs = 0): HistoryViewItem<Hisconst detail = (revision: string) => ({ messages: [], revision, lastMessageId: 'x', loading: false, complete: true, error: null });describe('history read ahead', () => {+ // The bridge and both in-flight queues use this union, so a reconnect cannot+ // erase a completion outside the five-task list budget in either arrival order.+ it.each([false, true])('selects recent tasks plus explicit completions (recent first=%s)', (recentFirst) => {+ let request = mergeHistoryPrefetchRequest(undefined, recentFirst ? undefined : new Set(['done']));+ request = mergeHistoryPrefetchRequest(request, recentFirst ? new Set(['done']) : undefined);+ const running = Array.from({ length: 5 }, (_, i) => ({ id: `running-${i}`, updatedAt: '2026-10-11T00:00:09Z', activeTurnStartedAt: 100 }));+ const picked = selectHistoryPrefetchSessions([...running,+ { id: 'done', updatedAt: '2026-10-11T00:00:01Z' }, { id: 'unrelated', updatedAt: '2026-10-11T00:00:02Z' }], {+ limit: request.recent ? undefined : 0, targets: request.targets, eligible: () => true, prefetchedAt: () => undefined,+ });+ expect(picked.map(s => s.id)).toEqual([...running.map(s => s.id), 'done']);+ });+it('discards collapsed details before expanded ones and folds only if the latest page still cannot fit', () => {const page = { version: 1 as const, items: [work('collapsed', 'r1'), work('expanded', 'r1')], hasMore: false, nextCursor: null };const previous: HistoryViewSnapshot<HistoryMessageSource> = {diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.tsindex b76cf08745..f3dfd9bb85 100644--- a/packages/maker-shared/src/historyView.ts+++ b/packages/maker-shared/src/historyView.ts@@ -6,6 +6,24 @@ export const HISTORY_VIEW_PAGE_ITEMS = 20;export const HISTORY_VIEW_PAGE_BYTES = 1024 * 1024;export const HISTORY_DETAIL_PAGE_BYTES = 256 * 1024;+/** Local ordering only: the run changes on restart, and order never uses the wall clock. */+export interface HistoryCacheReceipt { run: string; order: number }+const cacheReceiptRun = `${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;+let cacheReceiptOrder = 0;+export function nextHistoryCacheReceipt(): HistoryCacheReceipt {+ return { run: cacheReceiptRun, order: ++cacheReceiptOrder };+}+export function isHistoryCacheReceipt(value: unknown): value is HistoryCacheReceipt {+ const receipt = value as HistoryCacheReceipt | null;+ return !!receipt && typeof receipt.run === 'string' && Number.isSafeInteger(receipt.order) && receipt.order > 0;+}+/** Restored snapshots may borrow other-run receipts; a successful fresh read retires them. */+export function historyCacheReceiptFollows(receipt: unknown, read: unknown, restored = false): boolean {+ if (!isHistoryCacheReceipt(receipt)) return false;+ if (!isHistoryCacheReceipt(read)) return true;+ return receipt.run === read.run ? receipt.order > read.order : restored && read.run !== cacheReceiptRun;+}+export function isHistoryViewUnavailable(error: unknown): boolean {return /CHANNEL_NOT_ALLOWED|UNSUPPORTED_CAPABILITY|not registered|No handler/i.test(String(error));}@@ -28,8 +46,8 @@ export interface HistoryMessageSource {content: unknown;createdAt: string;rowid?: number;- /** Controller-local receipt time of a durable push; never a Host revision. */- cacheReceivedAt?: number;+ /** Controller-local order of a durable push; never a Host revision. */+ cacheReceipt?: HistoryCacheReceipt;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 ac0a98c61b..2af65528e7 100644--- a/packages/maker-shared/src/historyViewController.ts+++ b/packages/maker-shared/src/historyViewController.ts@@ -1,4 +1,5 @@import {+ nextHistoryCacheReceipt, type HistoryCacheReceipt,readHistoryWorkDetails, retainHistoryViewPrefix, isHistoryViewUnavailable, historyWorkSummaries, historyViewLeaves, type HistoryDetailPage, type HistoryMessageSource,type HistoryViewItem, type HistoryViewPage, type HistoryWorkPatch, type HistoryWorkSummary,} from './historyView.js';@@ -27,7 +28,7 @@ export interface HistoryViewSnapshot<T extends HistoryMessageSource> {*/stale?: boolean;/** Controller-local start of the latest page read, also retained in its disk cache. */- readAt?: number;+ readReceipt?: HistoryCacheReceipt;}export interface HistoryViewTransport<T extends HistoryMessageSource> {@@ -160,7 +161,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();+ const readReceipt = nextHistoryCacheReceipt();this.publish({ loading: true, error: null });try {const page = await this.transport.page(before);@@ -182,7 +183,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, readAt }),+ ...(older ? {} : { stale: false, readReceipt }),hasMore: retained.hasMore, nextCursor: retained.nextCursor });for (const summary of historyWorkSummaries(items)) {if (this.state.expanded.has(summary.key)) void this.loadDetails(summary);@@ -358,7 +359,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, readAt: undefined });+ nextCursor: null, hasMore: false, loading: false, error: null, stale: false, readReceipt: 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 24eb705d2d..6a4aed0b95 100644--- a/packages/maker-shared/src/historyViewHandoff.ts+++ b/packages/maker-shared/src/historyViewHandoff.ts@@ -1,4 +1,4 @@-import { historyViewLeaves, historyWorkSummaries, type HistoryMessageSource } from './historyView.js';+import { historyViewLeaves, historyWorkSummaries, historyCacheReceiptFollows, 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. */@@ -47,9 +47,8 @@ export class HistoryViewHandoff<T extends HistoryMessageSource> {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);+ // older page arrives later. Fresh reads also retire receipts from an earlier run.+ const receivedAfterRead = (row: T) => historyCacheReceiptFollows(row.cacheReceipt, snapshot.readReceipt, snapshot.stale);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) {diff --git a/packages/maker-shared/src/historyViewPrefetch.ts b/packages/maker-shared/src/historyViewPrefetch.tsindex 8d00672bc4..60a9568fb3 100644--- a/packages/maker-shared/src/historyViewPrefetch.ts+++ b/packages/maker-shared/src/historyViewPrefetch.ts@@ -5,6 +5,15 @@ import { historyViewEndMs } from './historyViewHandoff.js';/** Recently changed tasks read ahead after a list refresh; older tasks wait to be opened. */export const HISTORY_PREFETCH_SESSION_LIMIT = 5;+export interface HistoryPrefetchRequest { recent: boolean; targets: Set<string> }++/** Recent tasks have a budget; explicit completion targets must survive that budget. */+export function mergeHistoryPrefetchRequest(+ previous: HistoryPrefetchRequest | undefined, targets?: ReadonlySet<string>, recent = targets === undefined,+): HistoryPrefetchRequest {+ return { recent: recent || previous?.recent === true, targets: new Set([...previous?.targets ?? [], ...targets ?? []]) };+}+export interface HistoryPrefetchSession {id: string;updatedAt: string;@@ -43,13 +52,14 @@ export function historyPrefetchVersion(session: HistoryPrefetchSession): string*/export function selectHistoryPrefetchSessions<S extends HistoryPrefetchSession>(sessions: readonly S[],- options: { eligible(session: S): boolean; prefetchedAt(sessionId: string): string | undefined; limit?: number },+ options: { eligible(session: S): boolean; prefetchedAt(sessionId: string): string | undefined; limit?: number; targets?: ReadonlySet<string> },): S[] {const rank = (session: S) => isTurnRunning(session) ? Number.POSITIVE_INFINITY : activityMs(session);return sessions.filter((session) => activityMs(session) > 0 && options.eligible(session)).sort((a, b) => rank(b) - rank(a) || activityMs(b) - activityMs(a))- .slice(0, options.limit ?? HISTORY_PREFETCH_SESSION_LIMIT)+ .filter((session, index) => index < (options.limit ?? HISTORY_PREFETCH_SESSION_LIMIT)+ || (options.targets?.has(session.id) && !isTurnRunning(session))).filter((session) => {const version = historyPrefetchVersion(session);return version === undefined || options.prefetchedAt(session.id) !== version;