Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 补齐远程发送连续性与离线恢复体验 (#4604)
Dashfb737faf64d2
diff --git a/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts b/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.tsindex 606f468108..0c927d04d6 100644--- a/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/historyScanFallback.test.ts@@ -26,9 +26,9 @@ describe.each(['\n', '\r\n'])('automatic scan budget fallback owners (%j)', (newconst view = { isActive: () => active, getSnapshot: () => ({ ready: false, error: new Error('[UNSUPPORTED_CAPABILITY] History view scan budget exceeded') }) };for (const current of [true, false]) {reconcile.mockClear();- callback(desktopSource, ' view.subscribe(() => {', '\n });\n return view;',- ['isCurrent', 'sessions', 'sessionId', 'view', 'isHistoryViewUnavailable', 'reconcileRemoteMessages'],- [() => current, new Set(['s']), 's', view, isHistoryViewUnavailable, reconcile]);+ callback(desktopSource, ' view.subscribe(() => {', '\n });\n void view.restoreCachedView',+ ['isCurrent', 'sessions', 'sessionId', 'view', 'isHistoryViewUnavailable', 'reconcileRemoteMessages', 'persistTimer', 'writeCache', 'setState'],+ [() => current, new Set(['s']), 's', view, isHistoryViewUnavailable, reconcile, undefined, undefined, vi.fn()]);expect(reconcile).toHaveBeenCalledTimes(active && current ? 1 : 0);if (active && current) expect(reconcile).toHaveBeenCalledWith('s', { force: true });}diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.tsindex ea65851385..c4eb6ee507 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts@@ -15,6 +15,8 @@ import os from 'node:os';import path from 'node:path';import type { MirrorCache } from '../mirrorCacheStore';+import { decodeRemoteHistory, encodeRemoteHistory } from '../../../shared/remoteHistoryCache';+import { projectHistoryView, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';import {createMirrorCache,MirrorCachePurgeError,@@ -332,6 +334,41 @@ describe('normalizeDeviceSessions', () => {});describe('readMessages / writeMessages', () => {+ it('round-trips structured history in the existing guarded file and strips live/media data', async () => {+ const c = rawCache();+ const rows = [row('one', '2026-01-01T00:00:00Z', { isStreaming: true, images: [{ base64: 'secret-bytes', url: 'data:image/png;base64,secret' }], retryFiles: ['private'] })];+ const snapshot: HistoryViewSnapshot<typeof rows[number]> = {+ items: projectHistoryView(rows, false), details: new Map(), expanded: new Set(),+ nextCursor: 'older', hasMore: true, ready: true, loading: false, error: null,+ };+ const token = await c.readMessagesWithInvalidation('dev', 'session');+ await c.writeMessages('dev', 'session', [], token.invalidation, token.ownerRoot, token.accountCounter, encodeRemoteHistory(snapshot));+ const result = await c.readMessagesWithInvalidation('dev', 'session');+ expect(result.messages).toEqual([]);+ expect(result.historyView).not.toContain('secret');+ expect(result.historyView).not.toContain('private');+ const restored = decodeRemoteHistory(result.historyView)!;+ expect(restored.hasMore).toBe(true);+ expect(restored.nextCursor).toBe('older');+ expect(JSON.stringify(restored.items)).toContain('body-one');+ expect(JSON.stringify(restored.items)).toContain('"isStreaming":false');+ // Explicit clear retires both forms, including a delayed structured write.+ await c.writeMessages('dev', 'session', []);+ await c.writeMessages('dev', 'session', [], token.invalidation, token.ownerRoot, token.accountCounter, encodeRemoteHistory(snapshot));+ expect((await c.readMessagesWithInvalidation('dev', 'session')).historyView).toBeUndefined();+ const fresh = await c.readMessagesWithInvalidation('dev', 'session');+ await c.writeMessages('dev', 'session', [], fresh.invalidation, fresh.ownerRoot, fresh.accountCounter, encodeRemoteHistory({ ...snapshot, items: [] }));+ expect(decodeRemoteHistory((await c.readMessagesWithInvalidation('dev', 'session')).historyView)?.items).toEqual([]);+ await c.writeMessages('dev', 'session', rows, fresh.invalidation, fresh.ownerRoot, fresh.accountCounter);+ expect((await c.readMessagesWithInvalidation('dev', 'session')).historyView).toBeUndefined();+ });++ it('rejects corrupt structured message content instead of crashing the renderer', () => {+ const text = JSON.stringify({ version: 1, items: [{ type: 'messages', key: 'm', messages: [row('m', '2026-01-01', { content: null })] }], details: [], expanded: [], hasMore: false, nextCursor: null });+ expect(decodeRemoteHistory(text)).toBeNull();+ expect(decodeRemoteHistory('{')).toBeNull();+ });+it('写入后可读回,内容与归一化结果一致', async () => {const c = cache();await c.writeMessages('dev-1', 'sess-1', [diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 390ebef573..2b5bd71663 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -17,6 +17,7 @@ import { serverApiFetch, ServerApiError } from '../serverApiClient';import { requireString, throwIpcError } from '../utils/ipcValidate';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';import type { IpcErrorCode } from '../../shared/ipc-errors';+import { decodeRemoteHistory } from '../../shared/remoteHistoryCache';import {DEVICE_LINK_INVOKE,DEVICE_LINK_PUSH,@@ -955,6 +956,7 @@ export async function handleMirrorCacheGetMessages(sessionId: unknown,): Promise<{messages: Record<string, unknown>[];+ historyView?: string;invalidation?: number;ownerToken?: string;accountCounter?: number;@@ -990,6 +992,7 @@ export async function handleMirrorCacheGetMessages(// 暴露给不可信 renderer(review: codex P2)。账号代际再区分同账号登出重登。return {messages,+ ...(read.historyView !== undefined ? { historyView: read.historyView } : {}),invalidation: read.invalidation,ownerToken,accountCounter: read.accountCounter,@@ -1010,10 +1013,12 @@ export async function handleMirrorCachePutMessages(expectedInvalidation?: unknown,expectedOwnerToken?: unknown,expectedAccountCounter?: unknown,+ historyView?: unknown,): Promise<{ ok: true; invalidation?: number }> {const device = requireCacheId(deviceId, 'deviceId');const session = requireCacheId(sessionId, 'sessionId');if (!Array.isArray(messages)) throwIpcError('INVALID_PARAMS', 'messages must be an array');+ if (historyView !== undefined && !decodeRemoteHistory(historyView)) throwIpcError('INVALID_PARAMS', 'Invalid history view cache');const bounded = boundedItems(messages, MIRROR_CACHE_MAX_INBOUND_MESSAGES, 'messages');const expected =typeof expectedInvalidation === 'number'@@ -1046,6 +1051,7 @@ export async function handleMirrorCachePutMessages(expected,expectedOwner,expectedAccount,+ ...(historyView !== undefined ? [historyView as string] : []),);return { ok: true, invalidation: result.invalidation };} catch (err) {@@ -1368,6 +1374,7 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):expectedInvalidation?: unknown;expectedOwnerToken?: unknown;expectedAccountCounter?: unknown;+ historyView?: unknown;};return handleMirrorCachePutMessages(getMirrorCache(),@@ -1378,6 +1385,7 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):p.expectedInvalidation,p.expectedOwnerToken,p.expectedAccountCounter,+ p.historyView,);});ipcMain.handle(DEVICE_LINK_INVOKE.MIRROR_CACHE_GET_SESSION_LIST, (e) => {diff --git a/apps/desktop/src/main/device-link/mirrorCacheStore.ts b/apps/desktop/src/main/device-link/mirrorCacheStore.tsindex 659b2080f3..84afe098a8 100644--- a/apps/desktop/src/main/device-link/mirrorCacheStore.ts+++ b/apps/desktop/src/main/device-link/mirrorCacheStore.ts@@ -21,7 +21,7 @@** 存储位置与生命周期(docs/dev-rules/credentials-and-local-storage.md):* ownerScopedUserDataPath('device-link-mirror-cache')/- * messages/<deviceHash>-<sessionHash>.json 每 (设备, 会话) 最近一页消息+ * messages/<deviceHash>-<sessionHash>.json 最近一页消息或结构化历史视图* session-list.json 全部被控设备的会话列表快照* owner 命名空间由 appSessionState 提供 —— 换账号 / 登出后天然读不到旧数据,无需手工按* userId 键控(手机端 mobileHomeListCache 的 v2 正是为此改成按账号键控)。clearAll 仍保留,@@ -35,6 +35,7 @@ import fsp from 'node:fs/promises';import { createHash, randomBytes } from 'node:crypto';import { ownerScopedUserDataPath } from '../appSessionState';+import { decodeRemoteHistory, encodeRemoteHistory } from '../../shared/remoteHistoryCache';import { withCrossProcessLock } from './crossProcessLock';// 作废屏障(持久计数器)与 purge 队列共用一份实现 —— 队列在补删残留后要顺手把屏障修好。import {@@ -91,6 +92,7 @@ interface StoredMessages {version: 1;updatedAt: number;messages: Record<string, unknown>[];+ historyView?: string;}interface StoredSessionList {@@ -427,6 +429,7 @@ export interface MirrorCache {expectedInvalidation?: number,expectedOwnerRoot?: string,expectedAccountCounter?: number,+ historyView?: string,): Promise<{ invalidation: number }>;/*** 读某 (设备, 会话) 的最近一页,并带回当前作废计数与账号代际(供写入侧比对)。@@ -440,6 +443,7 @@ export interface MirrorCache {sessionId: string,): Promise<{messages: Record<string, unknown>[];+ historyView?: string;invalidation: number;ownerRoot: string;accountCounter: number;@@ -985,6 +989,8 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {const keys = [key, deviceClearKey(deviceId), CLEARED_ACCOUNT];const before = await readCounters(root, keys);const messages = await this.readMessages(deviceId, sessionId);+ const parsed = await readJson(path.join(root, MESSAGES_DIR, messageFileName(deviceId, sessionId)));+ const historyView = isRecord(parsed) && decodeRemoteHistory(parsed.historyView) ? parsed.historyView as string : undefined;const after = await readCounters(root, keys);if (await hasPendingClears(root)) {return { messages: [], invalidation: -1, ownerRoot, accountCounter: -1 };@@ -999,6 +1005,7 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {}return {messages,+ ...(historyView !== undefined ? { historyView } : {}),invalidation: numericCounter(after[0]),ownerRoot,accountCounter: numericCounter(after[2]),@@ -1019,6 +1026,7 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {expectedInvalidation,expectedOwnerRoot,expectedAccountCounter,+ historyView,) {if (!deviceId.trim() || !sessionId.trim()) return { invalidation: -1 };// root 在**发起时**快照,不能在出错时再 resolve:owner 会在进程生命周期内变(登出 /@@ -1044,9 +1052,15 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {const dir = path.join(rootAtStart, MESSAGES_DIR);const file = path.join(dir, messageFileName(deviceId, sessionId));const normalized = normalizeMessages(messages);+ const history = decodeRemoteHistory(historyView);+ // Sanitize the whole projection, including images outside message.content.+ const sanitizedHistory = history ? JSON.stringify(stripInlineMedia(JSON.parse(encodeRemoteHistory(history)), 0)) : undefined;+ if (historyView !== undefined && (!sanitizedHistory || !decodeRemoteHistory(sanitizedHistory))) {+ return { invalidation: numericCounter(await readClearCounter(rootAtStart, sessionKey)) };+ }// 空列表 = 清掉这条缓存(被控端 /clear、rewind 或删完最后一条时,残留会在// 下次冷开 hydrate 出已经不存在的正文)。- if (normalized.length === 0) {+ if (normalized.length === 0 && sanitizedHistory === undefined) {// 先落"作废意图"再删数据:计数自增在删除**之前**,于是即使本进程在删除中途崩掉,// 屏障也已经在盘上 —— 另一个实例(哪怕它的页取自作废之前)提交时会被挡掉// (review: codex P1)。自增失败就不删:宁可缓存暂留,也不要"删了却没有屏障" ——@@ -1131,11 +1145,12 @@ export function createMirrorCache(resolveRoot: () => string): MirrorCache {}return true;};- const body = JSON.stringify(normalized);+ const body = sanitizedHistory === undefined ? JSON.stringify(normalized) : JSON.stringify([normalized, sanitizedHistory]);const payload: StoredMessages = {version: 1,updatedAt: Date.now(),messages: normalized,+ ...(sanitizedHistory !== undefined ? { historyView: sanitizedHistory } : {}),};const serialized = JSON.stringify(payload);if (Buffer.byteLength(serialized, 'utf8') > MAX_MESSAGE_FILE_BYTES) {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 14cdc0cdff..4ef7093cc2 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4422,6 +4422,7 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string,): Promise<{messages: Record<string, unknown>[];+ historyView?: string;invalidation?: number;ownerToken?: string;accountCounter?: number;@@ -4444,6 +4445,7 @@ contextBridge.exposeInMainWorld('electronAPI', {expectedInvalidation?: number,expectedOwnerToken?: string,expectedAccountCounter?: number,+ historyView?: string,): Promise<{ ok: true; invalidation?: number }> =>ipcRenderer.invoke('device-link:mirror-cache:messages:put', {deviceId,@@ -4452,6 +4454,7 @@ contextBridge.exposeInMainWorld('electronAPI', {expectedInvalidation,expectedOwnerToken,expectedAccountCounter,+ historyView,}),/** 读侧边栏远程会话列表快照 */getSessionList: (): Promise<{diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex 0800967498..ca66b63593 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -161,6 +161,7 @@ contextBridge.exposeInMainWorld('electronAPI', {expectedInvalidation?: number,expectedOwnerToken?: string,expectedAccountCounter?: number,+ historyView?: string,): Promise<unknown> =>ipcRenderer.invoke(DEVICE_LINK_INVOKE.MIRROR_CACHE_PUT_MESSAGES, {deviceId,@@ -169,6 +170,7 @@ contextBridge.exposeInMainWorld('electronAPI', {expectedInvalidation,expectedOwnerToken,expectedAccountCounter,+ historyView,}),getSessionList: (): Promise<unknown> =>ipcRenderer.invoke(DEVICE_LINK_INVOKE.MIRROR_CACHE_GET_SESSION_LIST),diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.tsindex d395c6ede9..9c2e9e48dc 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts@@ -238,6 +238,53 @@ afterEach(() => {});describe('device-link controller mirror — end-to-end scenarios', () => {+ it('keeps the existing mirror when an old Host rejects history-view and raw fallback fails', async () => {+ const s = sid();+ const cached = dbMessage(s, 'cached', 'usable offline history', '2026-09-08T00:00:00Z');+ vi.mocked(readCachedMessages).mockResolvedValue([cached]);+ host.seedSession(s);+ const original = host.invoke.getMockImplementation()!;+ host.invoke.mockImplementation((...args) => {+ if (args[1] === 'local-db:messages:list') return Promise.reject(new Error('raw fallback timed out'));+ return original(...args);+ });+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);+ makerChatStore.enterView(s);+ makerChatStore.ensureInitialMessages(s);+ await vi.waitFor(() => expect(host.invoke).toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything()));+ await flush();+ expect(clearCachedMessages).not.toHaveBeenCalled();+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.content)).toContain('usable offline history');+ makerChatStore.purgeSession(s);+ vi.mocked(readCachedMessages).mockResolvedValue([]);+ });++ it('keeps the real sent row reserved through DB echo until history takes ownership', async () => {+ const s = sid();+ host.enableHistoryView();+ host.seedSession(s);+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);+ makerChatStore.enterView(s);+ makerChatStore.ensureInitialMessages(s);+ await flush(); await flush();+ const original = host.invoke.getMockImplementation()!;+ host.invoke.mockImplementation((...args) => args[1] === 'maker:input:enqueue'+ ? Promise.resolve(emptyProjection(s)) : original(...args));+ await makerChatStore.sendMessage(s, 'keep my message', 'claude', '', 'default', '/remote/project');+ const sent = makerChatStore.getSnapshot(s).messages.find((row) => row.content === 'keep my message')!;+ expect(sent.localSendPrecedingClientIds).toBeDefined();+ host.hostMessage(s, { ...dbMessage(s, 'sent-db', 'keep my message', '2026-09-17T00:00:00Z', 'user'), clientId: sent.clientId });+ await flush();+ const echoed = makerChatStore.getSnapshot(s).messages.find((row) => row.clientId === sent.clientId)!;+ expect(echoed.isPendingPersist).toBeUndefined();+ expect(echoed.localSendPrecedingClientIds).toBeDefined();+ await getRemoteHistoryView(s)!.refresh();+ const final = makerChatStore.getSnapshot(s).messages.filter((row) => row.clientId === sent.clientId);+ expect(final).toHaveLength(1);+ expect(final[0].localSendPrecedingClientIds).toBeUndefined();+ makerChatStore.purgeSession(s);+ });+it('does not lose repair signals received while the first historical page is in flight', async () => {const s = sid();const old = dbMessage(s, 'h1', 'old page', '2026-09-08T00:00:00Z');@@ -803,7 +850,8 @@ describe('device-link controller mirror — end-to-end scenarios', () => {expect(state.historyLoaded).toBe(true);expect(state.messages.some((row) => row.cacheHydrated)).toBe(false);expect(getLatestMessageTodoState(state.messages).hasPlanEvent).toBe(false);- expect(clearCachedMessages).toHaveBeenCalledWith(DEVICE_ID, s);+ // Successful structured history now replaces the mirror snapshot instead of deleting it.+ expect(clearCachedMessages).not.toHaveBeenCalled();if (scenario === 'rewound') {expect(state.messages.map((row) => row.content)).toEqual(['current text', 'live output']);} else expect(state.messages).toHaveLength(0);diff --git a/apps/desktop/src/renderer/__tests__/deviceProvidersRecovery.test.tsx b/apps/desktop/src/renderer/__tests__/deviceProvidersRecovery.test.tsxnew file mode 100644index 0000000000..ae5998f00a--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/deviceProvidersRecovery.test.tsx@@ -0,0 +1,135 @@+// @vitest-environment jsdom+import { act, cleanup, render } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++beforeEach(() => {+ vi.resetModules();+ vi.useFakeTimers();+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++async function fixture() {+ const invoke = vi.fn().mockRejectedValue(new Error('[DEVICE_LINK_TIMEOUT] timed out'));+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { deviceLink: { invoke } },+ });+ const mod = await import('@/hooks/useDeviceProviders');+ let latest: ReturnType<typeof mod.useDeviceProviders>;+ function Probe({ device = 'a' }: { device?: string }) {+ latest = mod.useDeviceProviders(device);+ return null;+ }+ const view = render(<Probe />);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ return { invoke, mod, Probe, view, latest: () => latest! };+}++function foreground() {+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ document.dispatchEvent(new Event('visibilitychange'));+}++describe('mounted remote catalog recovery', () => {+ it('recovers on foreground entry and deduplicates readers without periodic retries', async () => {+ const f = await fixture();+ const other = render(<f.Probe />);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ const before = f.invoke.mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(f.invoke.mock.calls.length).toBe(before);+ f.invoke.mockResolvedValue({ providers: [] });+ await act(async () => {+ foreground();+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(f.invoke.mock.calls.length).toBe(before + 1);+ expect(f.latest().error).toBeNull();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(f.invoke.mock.calls.length).toBe(before + 1);+ other.unmount();+ });++ it.each([+ '[DEVICE_LINK_CHANNEL_NOT_ALLOWED] old host',+ '[ACCESS_REVOKED] denied',+ 'Invalid provider list response',+ ])('stops retrying permanent failures: %s', async (error) => {+ const f = await fixture();+ f.invoke.mockRejectedValue(new Error(error));+ await act(async () => {+ foreground();+ await vi.advanceTimersByTimeAsync(0);+ });+ const count = f.invoke.mock.calls.length;+ await act(async () => {+ foreground();+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(f.invoke.mock.calls.length).toBe(count);+ });++ it('pauses hidden windows and immediately recovers on visibility', async () => {+ const f = await fixture();+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ act(() => document.dispatchEvent(new Event('visibilitychange')));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(f.invoke).toHaveBeenCalledTimes(1);+ f.invoke.mockResolvedValue({ providers: [] });+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ act(() => document.dispatchEvent(new Event('visibilitychange')));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(f.latest().error).toBeNull();+ expect(f.invoke).toHaveBeenCalledTimes(2);+ });++ it.each(['unmount', 'device', 'owner'] as const)(+ 'cancels recovery on %s change',+ async (change) => {+ const f = await fixture();+ if (change === 'unmount') f.view.unmount();+ if (change === 'device') f.view.rerender(<f.Probe device="b" />);+ if (change === 'owner') {+ const { setDataOwnerGeneration } = await import('@/contexts/dataOwnerGeneration');+ setDataOwnerGeneration('new-owner');+ }+ await act(async () => {+ foreground();+ await vi.advanceTimersByTimeAsync(5_000);+ });+ expect(f.invoke.mock.calls.filter(([device]) => device === 'a')).toHaveLength(1);+ },+ );++ it('restarts recovery after invalidation followed by the same error', async () => {+ const f = await fixture();+ await act(async () => {+ f.mod.evictDeviceProviders('a');+ await f.mod.prefetchDeviceProviders('a');+ });+ const count = f.invoke.mock.calls.length;+ f.invoke.mockResolvedValue({ providers: [] });+ await act(async () => {+ foreground();+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(f.invoke.mock.calls.length).toBe(count + 1);+ expect(f.latest().error).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryCache.test.tsnew file mode 100644index 0000000000..f025feb64c--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryCache.test.ts@@ -0,0 +1,284 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ HistoryViewController,+ projectHistoryView,+ type HistoryViewSnapshot,+} from '@cindy/maker-shared/message-window';+import { decodeRemoteHistory, encodeRemoteHistory, fitsRemoteHistoryCache } from '../../shared/remoteHistoryCache';+import { readRemoteHistoryCache, remoteHistoryCacheWriter } from '../lib/remoteHistoryCache';+import {+ clearCachedMessages,+ clearMirrorCacheAccountState,+} from '../features/device-link/mirrorCacheClient';+import { setDataOwnerGeneration } from '../contexts/dataOwnerGeneration';++const row = {+ id: 'm',+ clientId: 'm',+ role: 'user',+ content: 'cached text',+ createdAt: '2026-09-17T00:00:00Z',+};+const snapshot: HistoryViewSnapshot<typeof row> = {+ items: projectHistoryView([row], false),+ details: new Map(),+ expanded: new Set(),+ nextCursor: null,+ hasMore: false,+ ready: true,+ loading: false,+ error: null,+};+const getMessages = vi.fn();+const putMessages = vi.fn();+const flush = async () => {+ for (let i = 0; i < 12; i++) await Promise.resolve();+};+beforeEach(() => {+ clearMirrorCacheAccountState();+ setDataOwnerGeneration('owner');+ getMessages+ .mockReset()+ .mockResolvedValue({+ messages: [],+ historyView: encodeRemoteHistory(snapshot),+ invalidation: 0,+ ownerToken: 'owner-token',+ accountCounter: 0,+ });+ putMessages.mockReset().mockResolvedValue({ ok: true, invalidation: 0 });+ vi.stubGlobal('window', {+ electronAPI: { deviceLink: { mirrorCache: { getMessages, putMessages } } },+ });+});+afterEach(() => {+ clearMirrorCacheAccountState();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('structured history mirror lifecycle', () => {+ it.each(['revision', 'lastMessageId', 'removed'] as const)(+ 'drops collapsed stale details on encode and legacy cache reads after %s changes',+ async (change) => {+ await readRemoteHistoryCache('dev', 'session');+ const summary = { key: 'work', firstMessageId: 'm', lastMessageId: 'm', revision: 'r1',+ startedAtMs: 0, endedAtMs: 1, isStreaming: false, messageCount: 1, toolCount: 0 };+ const detail = { messages: [row], revision: 'r1', lastMessageId: 'm', complete: true, loading: false, error: null };+ const cached: typeof snapshot = { ...snapshot, items: [{ type: 'work', key: 'work', summary }],+ details: new Map([['work', detail]]), expanded: new Set() };+ expect(decodeRemoteHistory(encodeRemoteHistory(cached))?.details.size).toBe(1);+ const next: typeof snapshot = { ...cached, items: change === 'removed' ? [] : [+ { type: 'work', key: 'work', summary: { ...summary, [change]: 'new' } },+ ] };+ const encoded = encodeRemoteHistory(next);+ expect(encoded).not.toContain('cached text');+ const legacy = JSON.parse(encoded);+ legacy.details = [...cached.details]; // Cache written before revision filtering existed.+ expect(decodeRemoteHistory(JSON.stringify(legacy))?.details.size).toBe(0);+ remoteHistoryCacheWriter('dev', 'session')(next);+ await flush();+ expect(putMessages).toHaveBeenCalledTimes(1);+ expect(putMessages.mock.calls[0][6]).not.toContain('cached text');+ },+ );++ it('keeps matching nested work and preview details when collapsed', () => {+ const summary = { key: 'work', firstMessageId: 'm', lastMessageId: 'm', revision: 'r1',+ startedAtMs: 0, endedAtMs: 1, isStreaming: false, messageCount: 1, toolCount: 0 };+ const detail = { messages: [row], revision: 'r1', lastMessageId: 'm', complete: true, loading: false, error: null };+ const nested: typeof snapshot = { ...snapshot,+ items: [{ type: 'work', key: 'outer', summary: { ...summary, key: 'outer' }, children: [+ { type: 'work', key: 'work', summary: { ...summary, preview: { ...summary, key: 'preview' } } },+ ] }], details: new Map([['work', detail], ['preview', detail]]) };+ expect([...decodeRemoteHistory(encodeRemoteHistory(nested))!.details.keys()]).toEqual(['work', 'preview']);+ });++ it('keeps the last mirror until current expanded details finish successfully', async () => {+ await readRemoteHistoryCache('dev', 'session');+ const writer = remoteHistoryCacheWriter('dev', 'session');+ const summary = { key: 'work', firstMessageId: 'm', lastMessageId: 'm', revision: 'new',+ startedAtMs: 0, endedAtMs: 1, isStreaming: false, messageCount: 1, toolCount: 0 };+ const complete = { messages: [row], revision: 'new', lastMessageId: 'm',+ complete: true, loading: false, error: null };+ const expanded: typeof snapshot = { ...snapshot,+ items: [{ type: 'work', key: 'work', summary }], expanded: new Set(['work']) };+ writer(expanded); // Missing detail, before the request starts.+ for (const patch of [+ { loading: true, complete: false },+ { loading: false, complete: false, error: 'timeout' },+ { complete: false },+ { revision: 'old' },+ { lastMessageId: 'old' },+ ]) {+ writer({ ...expanded, details: new Map([['work', { ...complete, ...patch }]]) });+ }+ await flush();+ expect(putMessages).not.toHaveBeenCalled();+ writer({ ...expanded, details: new Map([['work', complete]]) });+ await flush();+ expect(putMessages).toHaveBeenCalledTimes(1);+ expect(putMessages.mock.calls[0][6]).toContain('cached text');++ const failed = new Map([['work', { ...complete, complete: false, error: 'timeout' }]]);+ writer({ ...expanded, expanded: new Set(), details: failed }); // Collapsed.+ await flush();+ writer({ ...snapshot, expanded: new Set(['work']), details: failed }); // Removed.+ await flush();+ expect(putMessages).toHaveBeenCalledTimes(3);+ });++ it.each(['中', '\\', '"'])('rejects byte-oversize history containing %s before sending it to Main', async (character) => {+ await readRemoteHistoryCache('dev', 'session');+ const large = { ...snapshot, items: projectHistoryView([{ ...row, content: character.repeat(180_000) }], false) };+ const text = encodeRemoteHistory(large);+ expect(text.length).toBeLessThan(512 * 1024);+ expect(Buffer.byteLength(JSON.stringify({ version: 1, updatedAt: Date.now(), messages: [], historyView: text }), 'utf8')).toBeGreaterThan(512 * 1024);+ remoteHistoryCacheWriter('dev', 'session')(large);+ await flush();+ // Existing oversize invalidation still retires a potentially rewound/deleted old page.+ expect(putMessages).toHaveBeenCalledTimes(1);+ expect(putMessages.mock.calls[0][2]).toEqual([]);+ expect(putMessages.mock.calls[0][6]).toBeUndefined();+ });++ it('reserves enough bytes for the persisted envelope at the ASCII boundary', () => {+ const text = 'a'.repeat(512 * 1024 - 256 - 2);+ expect(fitsRemoteHistoryCache(text)).toBe(true);+ expect(fitsRemoteHistoryCache(text + 'a')).toBe(false);+ const payload = JSON.stringify({ version: 1, updatedAt: Number.MAX_SAFE_INTEGER, messages: [], historyView: text });+ expect(Buffer.byteLength(payload, 'utf8')).toBeLessThanOrEqual(512 * 1024);+ });++ it('does not let a writer waiting for clear A cross clear B', async () => {+ await readRemoteHistoryCache('dev', 'session');+ let finishA!: (value: unknown) => void;+ let finishB!: (value: unknown) => void;+ putMessages.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishA = resolve;+ }),+ );+ clearCachedMessages('dev', 'session');+ remoteHistoryCacheWriter('dev', 'session')(snapshot);+ putMessages.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishB = resolve;+ }),+ );+ clearCachedMessages('dev', 'session');+ const next = remoteHistoryCacheWriter('dev', 'session');+ finishA({ ok: true, invalidation: 1 });+ finishB({ ok: true, invalidation: 2 });+ await flush();+ expect(putMessages).toHaveBeenCalledTimes(2);+ next(snapshot);+ await flush();+ expect(putMessages.mock.calls[2][3]).toBe(2);+ });++ it('bounds a stalled clear and does not remember its response after owner change', async () => {+ vi.useFakeTimers();+ await readRemoteHistoryCache('dev', 'session');+ let finish!: (value: unknown) => void;+ putMessages.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ clearCachedMessages('dev', 'session');+ remoteHistoryCacheWriter('dev', 'session')(snapshot);+ await vi.advanceTimersByTimeAsync(3000);+ expect(putMessages).toHaveBeenCalledTimes(2);+ expect(putMessages.mock.calls[1][3]).toBeUndefined();+ setDataOwnerGeneration('other');+ clearMirrorCacheAccountState();+ finish({ ok: true, invalidation: 99 });+ await flush();+ const { knownMainInvalidationFor } = await import('../features/device-link/mirrorCacheClient');+ expect(knownMainInvalidationFor('session')).toBeUndefined();+ });++ it('restores offline without a network read; fresh history wins over late disk', async () => {+ const page = vi.fn(async () => ({+ version: 1 as const,+ items: [],+ nextCursor: null,+ hasMore: false,+ }));+ const view = new HistoryViewController({ page, details: vi.fn(), expanded: vi.fn() });+ view.setNetworkAvailable(false);+ await view.restoreCachedView(() => readRemoteHistoryCache('dev', 'session'));+ expect(page).not.toHaveBeenCalled();+ expect(view.getSnapshot().items).toEqual(snapshot.items);+ view.setActive(false);+ const fresh = new HistoryViewController({ page, details: vi.fn(), expanded: vi.fn() });+ let finish!: (value: typeof snapshot) => void;+ const restore = fresh.restoreCachedView(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ await fresh.refresh();+ finish(snapshot);+ await restore;+ expect(fresh.getSnapshot().items).toEqual([]);+ fresh.setActive(false);+ });++ it.each(['clear', 'owner'] as const)(+ 'rejects late disk and pending writes across %s',+ async (boundary) => {+ await readRemoteHistoryCache('dev', 'session');+ const writer = remoteHistoryCacheWriter('dev', 'session');+ let finish!: (value: unknown) => void;+ getMessages.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const reading = readRemoteHistoryCache('dev', 'session');+ if (boundary === 'clear') clearCachedMessages('dev', 'session');+ else setDataOwnerGeneration('other');+ finish({+ messages: [],+ historyView: encodeRemoteHistory(snapshot),+ invalidation: 0,+ ownerToken: 'owner-token',+ accountCounter: 0,+ });+ expect(await reading).toBeNull();+ writer(snapshot);+ await flush();+ expect(putMessages.mock.calls.filter((call) => call[6] !== undefined)).toHaveLength(0);+ },+ );++ it('captures the pending clear counter for the new read, but rejects the old writer', async () => {+ await readRemoteHistoryCache('dev', 'session');+ const old = remoteHistoryCacheWriter('dev', 'session');+ let finish!: (value: unknown) => void;+ putMessages.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ clearCachedMessages('dev', 'session');+ const next = remoteHistoryCacheWriter('dev', 'session');+ next(snapshot);+ old(snapshot);+ await flush();+ expect(putMessages).toHaveBeenCalledTimes(1);+ finish({ ok: true, invalidation: 1 });+ await flush();+ expect(putMessages).toHaveBeenCalledTimes(2);+ expect(putMessages.mock.calls[1][3]).toBe(1);+ expect(putMessages.mock.calls[1][6]).toBe(encodeRemoteHistory(snapshot));+ });+});diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.tsindex 2c3899b33d..8eb082756e 100644--- a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts@@ -1,9 +1,15 @@import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';import {- HistoryViewController, HistoryViewHandoff, projectHistoryView, renderHistoryView,+ HistoryViewController, HistoryViewHandoff, projectHistoryView, renderHistoryView, historyViewLeaves,} from '@cindy/maker-shared/message-window';-import { buildRenderItems, groupWorkRuns } from '../components/chat/MessageStream';+import { buildRenderItems, groupWorkRuns, selectVisibleMessages, collectTurnFinalAssistantClientIds,+ findLastUserMessageClientId, planSessionBelongsToLatestUserTurn } from '../components/chat/MessageStream';+import { deriveNavRailEntries } from '../components/chat/messageNavRailModel';+import { collectAssistantTurnUsageDetails } from '../lib/userTurnUsage';+import { buildTurnUsageDetails } from '../../shared/turnUsageDetails';import type { HistoryChatMessage } from '../lib/makerChatStore';+import { confirmRemoteUsers, projectRemoteUsers, reserveRemoteUser } from '../lib/remoteUserHandoff';const row = (clientId: string, isStreaming = false): HistoryChatMessage => ({id: clientId, clientId, role: clientId === 'user' ? 'user' : 'assistant',@@ -21,13 +27,17 @@ function fixture() {const handoff = new HistoryViewHandoff<HistoryChatMessage>((message) => message.isStreaming === true);const render = (raw: HistoryChatMessage[]) => {const snapshot = view.getSnapshot();+ const historyIds = new Set(historyViewLeaves(snapshot.items).flatMap((item) =>+ item.type === 'messages' ? item.messages.map((row) => row.clientId) : []));+ for (const detail of snapshot.details.values()) for (const row of detail.messages) historyIds.add(row.clientId);+ raw = projectRemoteUsers(raw, historyIds);const state = handoff.reconcile(snapshot, raw);const build = (rows: readonly HistoryChatMessage[]) => groupWorkRuns(buildRenderItems([...rows]).items, false);const items = snapshot.ready ? renderHistoryView({view, snapshot, liveMessages: raw, streaming: false,isLive: (message) => message.isStreaming === true,pendingHandoff: state.pending,- isLocalUser: (message) => message.role === 'user' && (message.isPendingPersist === true || !!message.blockedByGhost),+ isLocalUser: (message) => message.role === 'user' && (message.isPendingPersist === true || !!message.blockedByGhost || !!message.localSendPrecedingClientIds),build,structure: {placeholder: () => { throw new Error('This fixture contains prose only'); },@@ -42,6 +52,121 @@ function fixture() {}describe('desktop remote history uses the shared live-to-history handoff', () => {+ it('keeps the live tail after history when the last send reservation retires', async () => {+ const { view, render, setSource } = fixture();+ await view.refresh();+ const sent = reserveRemoteUser({ ...row('sent'), role: 'user' as const }, [row('user')]);+ const reply = { ...row('reply', true), content: 'current answer',+ turnUsageDetails: buildTurnUsageDetails({ inputTokens: 3, outputTokens: 1 })! };+ const raw = [row('user'), reply, sent];+ render(raw); // Observe the live reply before the Host owns either row.+ const { localSendPrecedingClientIds: _reservation, ...hostUser } = sent;+ setSource([row('user'), hostUser]);+ await view.refresh();+ const historyIds = new Set(['user', 'sent']);+ const confirmed = confirmRemoteUsers(raw, historyIds);+ expect(confirmed.every((message) => !message.localSendPrecedingClientIds)).toBe(true);+ const display = projectRemoteUsers(confirmed, historyIds);+ expect(display.map((message) => message.clientId)).toEqual(['user', 'sent', 'reply']);+ expect(render(confirmed).items.filter((item) => item.type === 'message')+ .map((item) => item.message.clientId)).toEqual(['user', 'sent', 'reply']);+ const visible = selectVisibleMessages(display);+ const finals = collectTurnFinalAssistantClientIds(visible);+ expect(finals).toEqual(new Set(['reply']));+ expect(findLastUserMessageClientId(visible)).toBe('sent');+ expect(planSessionBelongsToLatestUserTurn(display, ['reply'])).toBe(true);+ expect(deriveNavRailEntries(visible).at(-1)?.answerExcerpt).toBe('current answer');+ expect(collectAssistantTurnUsageDetails(display, finals).get('reply')?.totalTokens).toBe(4);+ const second = reserveRemoteUser({ ...row('second'), role: 'user' as const }, display);+ const secondReply = row('second-reply', true);+ expect(projectRemoteUsers([...confirmed, secondReply, second], historyIds)+ .map((message) => message.clientId)).toEqual(['user', 'sent', 'reply', 'second', 'second-reply']);+ // Empty history (including the legacy path) provides no ordering evidence.+ expect(projectRemoteUsers(confirmed)).toEqual(confirmed);+ setSource([]);+ await view.refresh();+ expect(render(confirmed).items.filter((item) => item.type === 'message' && item.message.clientId === 'sent')).toEqual([]);+ view.setActive(false);+ });++ it('keeps turn actions, navigation, plans and usage aligned through skewed consecutive sends', () => {+ const oldAnswer = { ...row('old-answer'), content: 'old answer',+ turnUsageDetails: buildTurnUsageDetails({ inputTokens: 100, outputTokens: 1 })! };+ const history = [row('user'), oldAnswer];+ const sent = reserveRemoteUser({ ...row('sent'), role: 'user' as const }, history);+ const internal = { ...row('internal'), parentToolUseId: 'toolu_subagent',+ turnUsageDetails: buildTurnUsageDetails({ inputTokens: 5, outputTokens: 2 })! };+ const reply = { ...row('reply'), content: 'current answer',+ turnUsageDetails: buildTurnUsageDetails({ inputTokens: 3, outputTokens: 1 })! };+ const second = reserveRemoteUser({ ...row('second'), role: 'user' as const }, [...history, sent, internal, reply]);+ const secondReply = { ...row('second-reply'), content: 'second answer' };+ const display = projectRemoteUsers([...history, internal, reply, secondReply, second, sent]);+ const visible = selectVisibleMessages(display);+ expect(visible.map((message) => message.clientId)).toEqual(['user', 'old-answer', 'sent', 'reply', 'second', 'second-reply']);+ const finals = collectTurnFinalAssistantClientIds(visible);+ expect(finals).toEqual(new Set(['old-answer', 'reply', 'second-reply']));+ expect(findLastUserMessageClientId(visible)).toBe('second');+ expect(planSessionBelongsToLatestUserTurn(display, ['second-reply'])).toBe(true);+ expect(planSessionBelongsToLatestUserTurn(display, ['reply'])).toBe(false);+ expect(deriveNavRailEntries(visible).map((entry) => entry.answerExcerpt)).toEqual(['old answer', 'current answer', 'second answer']);+ expect(collectAssistantTurnUsageDetails(display, finals).get('reply')?.totalTokens).toBe(11);+ // Pin the component's inputs too: pure helpers alone cannot catch a raw-order caller.+ const source = readFileSync(new URL('../components/chat/MessageStream.tsx', import.meta.url), 'utf8');+ expect(source).toContain('selectVisibleMessages(displayMessages)');+ expect(source).toContain('planSessionBelongsToLatestUserTurn(displayMessages,');+ expect(source).toContain('findFirstUserMessageClientId(displayMessages,');+ expect(source).toContain('collectAssistantTurnUsageDetails(displayMessages,');+ });++ it.each([{ predecessors: [] as string[] }, { predecessors: ['removed'] }, { predecessors: ['user'] }])('anchors a send after late history with $predecessors', async ({ predecessors }) => {+ const { view, render, setSource } = fixture();+ const sent = reserveRemoteUser({ ...row('sent'), role: 'user' as const }, predecessors.map((id) => row(id)));+ const reply = { ...row('reply', true), content: 'first reply' };+ expect(render([reply, sent]).items.filter((item) => item.type === 'message').map((item) => item.message.clientId)).toEqual(['sent', 'reply']);+ const late = { ...row('late'), role: 'user' as const, content: 'newer historical question' };+ setSource([row('user'), late]);+ await view.refresh();+ expect(render([reply, row('user'), late, sent]).items.filter((item) => item.type === 'message').map((item) => item.message.clientId)).toEqual(['user', 'late', 'sent', 'reply']);+ const second = reserveRemoteUser({ ...row('second'), role: 'user' as const }, [sent, reply]);+ const secondReply = { ...row('second-reply', true), content: 'second reply' };+ expect(render([reply, secondReply, row('user'), late, second, sent]).items.filter((item) => item.type === 'message').map((item) => item.message.clientId)).toEqual(['user', 'late', 'sent', 'reply', 'second', 'second-reply']);+ view.setActive(false);+ });++ it.each([false, true])('keeps a sent user through DB echo and stale history, ready=%s', async (ready) => {+ const { view, render, setSource } = fixture();+ if (ready) await view.refresh();+ const pending = reserveRemoteUser({ ...row('sent'), role: 'user' as const, content: 'sent text', isPendingPersist: true }, [row('user')]);+ expect(render([row('user'), pending]).text).toContain('sent text');+ const echo = { ...pending, isPendingPersist: undefined, id: 'db-sent' };+ await view.refresh();+ expect(render([row('user'), echo]).items.filter((item) => item.type === 'message' && item.message.clientId === 'sent')).toHaveLength(1);+ const authoritative = { ...row('sent'), role: 'user' as const, content: 'authoritative sent' };+ setSource([row('user'), authoritative]);+ await view.refresh();+ const confirmed = confirmRemoteUsers([echo], new Set(['sent']));+ expect(confirmed[0].localSendPrecedingClientIds).toBeUndefined();+ expect(render(confirmed).text).toContain('authoritative sent');+ setSource([]);+ await view.refresh();+ expect(render(confirmed).text).not.toContain('sent text');+ expect(render([]).items).toEqual([]);+ view.setActive(false);+ });++ it.each(['2000-01-01', '2040-01-01'])('keeps user before its reply regardless of controller clock %s', async (createdAt) => {+ const { view, render } = fixture();+ await view.refresh();+ const pending = reserveRemoteUser({ ...row('sent'), role: 'user' as const, createdAt }, [row('user')]);+ const answer = row('answer', true);+ // Raw store may have sorted the host reply ahead of the controller's user row.+ const result = render([row('user'), answer, pending]);+ expect(result.items.filter((item) => item.type === 'message').map((item) => item.message.clientId)).toEqual(['user', 'sent', 'answer']);+ const second = reserveRemoteUser({ ...row('second'), role: 'user' as const }, [row('user'), pending, answer]);+ expect(projectRemoteUsers([row('user'), second, answer, pending]).map((item) => item.clientId)).toEqual(['user', 'sent', 'answer', 'second']);+ view.setActive(false);+ });+it('keeps finalized prose through the first stale page and takes over once by clientId', async () => {const { view, render, setSource } = fixture();expect(render([row('answer', true)]).text).toContain('visible answer');diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.tsindex 7d11ecf466..dc7e6c709a 100644--- a/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts@@ -32,7 +32,7 @@ vi.mock('@/lib/sessionService', () => ({touchUserSend: vi.fn(async () => ({})),}));-import { makerChatStore } from '@/lib/makerChatStore';+import { makerChatStore, getRemoteHistoryView } from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';import * as sessionService from '@/lib/sessionService';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';@@ -116,7 +116,9 @@ describe('makerChatStore.reconcileOpenSessionOrigins (device-link 历史竞速)'const s = sid();const cached = dbMessage(s, 'cached', 'Saved answer');const getMessages = vi.fn(async () => ({ accountCounter: 0, messages: [cached] }));- Object.assign(window.electronAPI.deviceLink, { mirrorCache: { getMessages } });+ Object.assign(window.electronAPI.deviceLink, { mirrorCache: { getMessages,+ putMessages: vi.fn(async () => ({ ok: true, invalidation: 1 })),+ } });seedRemote(s);remoteProjectsStore.markDeviceDisconnected(DEVICE_ID);const leave = makerChatStore.enterView(s);@@ -124,18 +126,23 @@ describe('makerChatStore.reconcileOpenSessionOrigins (device-link 历史竞速)'await flush();const messages = makerChatStore.getSnapshot(s).messages;expect(messages.map((message) => message.clientId)).toEqual([cached.clientId]);+ // One protected structured-view read and one legacy raw-row fallback read.+ expect(getMessages).toHaveBeenCalledTimes(2);makerChatStore.reconcileOpenSessionOrigins();makerChatStore.reconcileOpenSessionOrigins();await flush();expect(makerChatStore.getSnapshot(s).messages).toBe(messages);- expect(getMessages).toHaveBeenCalledTimes(1);+ expect(getMessages).toHaveBeenCalledTimes(2);expect(invoke).not.toHaveBeenCalled();remoteHistory = [cached, dbMessage(s, 'new', 'New answer')];seedRemote(s);+ // Match the production remote-projects subscriber before origin reconciliation.+ getRemoteHistoryView(s)?.setNetworkAvailable(true);makerChatStore.reconcileOpenSessionOrigins();- await flush();- expect(invoke).toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());- expect(makerChatStore.getSnapshot(s).messages.map((message) => message.clientId)).toContain('client-new');+ await vi.waitFor(() => {+ expect(invoke).toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());+ expect(makerChatStore.getSnapshot(s).messages.map((message) => message.clientId)).toContain('client-new');+ });leave();});it('启动竞速:origin 解析后经隧道重载被控端真历史(不再停留本机空库)', async () => {diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.tsindex 459c82a3ea..5137509c46 100644--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts@@ -32,7 +32,9 @@ vi.mock('@/lib/sessionService', () => ({touchUserSend: vi.fn(async () => ({})),}));-import { makerChatStore } from '@/lib/makerChatStore';+import { makerChatStore, getRemoteHistoryView } from '@/lib/makerChatStore';+import { projectHistoryView } from '@cindy/maker-shared/message-window';+import { encodeRemoteHistory } from '../../shared/remoteHistoryCache';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';import { listMessagesFor } from '@/lib/makerTransport';import { collectSessionListSnapshot } from '@/features/device-link/refreshRemoteSessions';@@ -267,6 +269,22 @@ afterEach(() => {});describe('冷缓存 hydrate', () => {+ 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' }];+ const historyView = encodeRemoteHistory({ items: projectHistoryView(rows, false), details: new Map(), expanded: new Set(),+ ready: true, loading: false, error: null, nextCursor: 'older', hasMore: true });+ getMessages.mockResolvedValueOnce({ messages: [], invalidation: 0, ownerToken: cachedOwnerToken, accountCounter: 0, historyView } as CachedRead);+ registerRemote(s);+ remoteProjectsStore.markDeviceDisconnected(DEVICE_ID);+ makerChatStore.ensureInitialMessages(s);+ await flush(30);+ expect(getRemoteHistoryView(s)?.getSnapshot().items).toEqual(projectHistoryView(rows, false));+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.content)).toEqual(['offline history']);+ expect(invoke).not.toHaveBeenCalled();+ makerChatStore.purgeSession(s);+ });+it('首拉未回来时用缓存种入,行带 cacheHydrated 且不置 historyLoaded', async () => {const s = sid();cachedMessages.set(`${DEVICE_ID}::${s}`, [@@ -1189,8 +1207,8 @@ describe('会话作废计数补读的等待纪律', () => {});await flush(20);- expect(putMessages).toHaveBeenCalledTimes(1);- expect(putMessages.mock.calls[0]?.[3]).toBeUndefined();+ // The renderer now drops the old owner's write before dispatch as well.+ expect(putMessages).not.toHaveBeenCalled();// 第二次仍须补读:99 属于旧 owner,不能成为 B 的已知计数。putMessages.mockClear();diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex a00c339670..257ad406d8 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -29,7 +29,7 @@ import {type CSSProperties,type ReactNode,} from 'react';-import { HistoryViewHandoff, renderHistoryView, historyPrefetchThreshold } from '@cindy/maker-shared/message-window';+import { HistoryViewHandoff, renderHistoryView, historyPrefetchThreshold, historyViewLeaves } from '@cindy/maker-shared/message-window';import { getRemoteHistoryView, type HistoryChatMessage } from '@/lib/makerChatStore';import { createPortal } from 'react-dom';import { GitFork } from 'lucide-react';@@ -74,6 +74,7 @@ import { Spinner } from '@/components/ui/spinner';import { BrandLoadingMark } from '@/components/branding/BrandLoadingMark';import { useMessageNavRailPreference } from '@/hooks/useMessageNavRailPreference';import { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';+import { projectRemoteUsers } from '@/lib/remoteUserHandoff';import { resolveToolFilePath, type KnownLocalFileRef } from '@/lib/localPathResolver';import { collectGeneratedFiles, type GeneratedFileRef } from '@/lib/generatedFiles';import { useTurnChangeSets } from './useTurnChangeSets';@@ -2549,14 +2550,23 @@ export function MessageStream({historyView?.getSnapshot ?? (() => null),historyView?.getSnapshot ?? (() => null),);+ const displayMessages = useMemo(() => {+ if (!historySnapshot) return messages;+ const historyIds = new Set(historyViewLeaves(historySnapshot.items).flatMap((item) =>+ item.type === 'messages' ? item.messages.map((row) => row.clientId) : []));+ for (const detail of historySnapshot.details.values()) {+ for (const row of detail.messages) historyIds.add(row.clientId);+ }+ return projectRemoteUsers(messages, historyIds);+ }, [historySnapshot, messages]);const historyHandoff = useMemo(() => new HistoryViewHandoff<HistoryChatMessage>((row) => row.isStreaming === true,), [historyView]);// Observe live rows before the first history page too: a stream can finish// while that page is in flight. Local tasks retain their existing path.- const historyLiveMessages = useMemo(() => historyView ? messages.map((row) => ({+ const historyLiveMessages = useMemo(() => historyView ? displayMessages.map((row) => ({...row, id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',- })) : [], [historyView, messages]);+ })) : [], [historyView, displayMessages]);const handoff = useMemo(() => historySnapshot? historyHandoff.reconcile(historySnapshot, historyLiveMessages) : null,[historyHandoff, historySnapshot, historyLiveMessages]);@@ -2751,7 +2761,7 @@ export function MessageStream({// 入口与运行态标记(review: codex P2;同族的 isSyntheticTrigger 坑见// findLastUserMessageClientId 注释)。按子代理归属反查的派生(buildSubagentModelMap)// 仍吃原始 messages —— 它要的正是这些被隐藏的行。- const visibleMessages = useMemo(() => selectVisibleMessages(messages), [messages]);+ const visibleMessages = useMemo(() => selectVisibleMessages(displayMessages), [displayMessages]);// 全量 build:折叠 / 丢弃 / 反向膨胀的所有规则一次性吸收 — 窗口看到的就是// 用户看到的。流式中每 token messages 引用变 → 这里跑一次 O(n) 单线性扫描,@@ -2765,7 +2775,7 @@ export function MessageStream({// parsed image targets without retaining state beyond the session mount.const markdownImageTargetCacheRef = useRef<MarkdownImageTargetCache>(new Map());const { items: ungroupedRenderItems, singleResultMap } = useMemo(() => {- const built = buildRenderItems(messages, taskUpdates, ghostCardSnapshot, {+ const built = buildRenderItems(displayMessages, taskUpdates, ghostCardSnapshot, {historyWindowIncomplete: !historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,turnChangeSets,workingDir,@@ -2778,7 +2788,7 @@ export function MessageStream({view: historyView, snapshot: historySnapshot, liveMessages: historyLiveMessages, streaming: isSessionStreaming,isLive: (row) => row.isStreaming === true,pendingHandoff: handoff?.pending,- isLocalUser: (row) => row.role === 'user' && (row.isPendingPersist === true || !!row.blockedByGhost),+ isLocalUser: (row) => row.role === 'user' && (row.isPendingPersist === true || !!row.blockedByGhost || !!row.localSendPrecedingClientIds),build: (rows) => {const chunk = buildRenderItems([...rows], taskUpdates, ghostCardSnapshot, {historyWindowIncomplete: true, workingDir,@@ -2812,7 +2822,7 @@ export function MessageStream({singleResultMap: built.singleResultMap,};}, [- messages,+ displayMessages,historyView,historySnapshot,historyLiveMessages,@@ -2897,9 +2907,9 @@ export function MessageStream({const latestInlinePlanBelongsToActiveTurn = useMemo(() =>latestInlinePlan- ? planSessionBelongsToLatestUserTurn(messages, latestInlinePlan.sourceClientIds)+ ? planSessionBelongsToLatestUserTurn(displayMessages, latestInlinePlan.sourceClientIds): false,- [latestInlinePlan, messages],+ [latestInlinePlan, displayMessages],);/**@@ -5516,8 +5526,8 @@ export function MessageStream({// 切片,还有老页未加载(hasMoreMessages)时不能把切片首条误判为对话首条// (判定逻辑与陷阱见 findFirstUserMessageClientId 注释)。const firstUserMessageClientId = useMemo(- () => findFirstUserMessageClientId(messages, Boolean(hasMoreMessages)),- [messages, hasMoreMessages],+ () => findFirstUserMessageClientId(displayMessages, Boolean(hasMoreMessages)),+ [displayMessages, hasMoreMessages],);// edit-last-message: 最后一条 user 消息才显示编辑入口(编辑 = rewind 到该条@@ -5538,12 +5548,12 @@ export function MessageStream({[visibleMessages],);- // 刻意吃**原始** messages,不走 visibleMessages:子代理消耗的 token 是这个 turn 的+ // 使用未过滤子代理的 displayMessages,不走 visibleMessages:子代理消耗的 token 是这个 turn 的// 真实花费,过滤掉等于把子代理的账从用量里抹掉(成本失真,比显示问题更糟)。// 归属键 turnFinalAssistantClientIds 已按可见序列算出,聚合区间仍落在正确的 turn 内。const userTurnUsageDetailsByAssistantId = useMemo(() => {- return collectAssistantTurnUsageDetails(messages, turnFinalAssistantClientIds);- }, [messages, turnFinalAssistantClientIds]);+ return collectAssistantTurnUsageDetails(displayMessages, turnFinalAssistantClientIds);+ }, [displayMessages, turnFinalAssistantClientIds]);// error-tail-banner:尾部未忽略的 error 行由输入框上方红条独家承载,流内需要// 知道"是不是最后一条"来跳过重复渲染。走可见序列:尾部挂着子代理内部行时,diff --git a/apps/desktop/src/renderer/features/device-link/mirrorCacheClient.ts b/apps/desktop/src/renderer/features/device-link/mirrorCacheClient.tsindex 3742a6d879..631e8cada8 100644--- a/apps/desktop/src/renderer/features/device-link/mirrorCacheClient.ts+++ b/apps/desktop/src/renderer/features/device-link/mirrorCacheClient.ts@@ -66,6 +66,8 @@ interface PendingProtectedRead {}const pendingProtectedRead = new Map<string, PendingProtectedRead>();+/** A post-clear remote read must inherit the counter returned by that clear. */+const pendingMessageClears = new Map<string, Promise<number | undefined>>();/*** 等在途受保护读完成后取令牌,带超时与账号代际复核。@@ -97,7 +99,7 @@ function afterProtectedRead<T>(}/** 读某 (设备, 会话) 缓存的最近一页 server rows;未命中 / 出错一律空数组。 */-export async function readCachedMessages(deviceId: string, sessionId: string): Promise<Message[]> {+export async function readCachedMessages(deviceId: string, sessionId: string, onHistory?: (value: unknown) => void): Promise<Message[]> {const api = bridge();if (!api || !deviceId || !sessionId) return [];const ownerAtStart = getDataOwnerGeneration();@@ -124,6 +126,7 @@ export async function readCachedMessages(deviceId: string, sessionId: string): PrememberMainInvalidation(sessionId, result?.invalidation);rememberOwnerToken(sessionId, result?.ownerToken);rememberAccountCounter(sessionId, accountCounter);+ onHistory?.(result.historyView);return Array.isArray(result?.messages) ? (result.messages as unknown as Message[]) : [];} catch (err) {log.debug('read cached messages failed', err);@@ -230,15 +233,19 @@ export function persistCachedMessages(expectedInvalidation?: number | Promise<number | undefined>,expectedOwnerToken?: string | Promise<string | undefined>,expectedAccountCounter?: number | Promise<number | undefined>,-): void {+ historyView?: string,+): Promise<number | undefined> {const api = bridge();- if (!api || !deviceId || !sessionId) return;+ if (!api || !deviceId || !sessionId) return Promise.resolve(undefined);+ const owner = getDataOwnerGeneration();+ const localToken = sessionCacheInvalidationToken(sessionId);const dispatch = (expected: number | undefined,ownerToken: string | undefined,accountCounter: number | undefined,- ): void => {- void api+ ): Promise<number | undefined> => {+ if (!isDataOwnerGenerationCurrent(owner) || localToken !== sessionCacheInvalidationToken(sessionId)) return Promise.resolve(undefined);+ return api.putMessages(deviceId,sessionId,@@ -246,9 +253,14 @@ export function persistCachedMessages(expected,ownerToken,accountCounter,+ ...(historyView !== undefined ? [historyView] : []),)- .then((result) => rememberMainInvalidation(sessionId, result?.invalidation))- .catch((err: unknown) => log.debug('persist cached messages failed', err));+ .then((result) => {+ if (!isDataOwnerGenerationCurrent(owner) || localToken !== sessionCacheInvalidationToken(sessionId)) return undefined;+ rememberMainInvalidation(sessionId, result?.invalidation);+ return result?.invalidation;+ })+ .catch((err: unknown) => { log.debug('persist cached messages failed', err); return undefined; });};// 令牌已经在手 / 根本没有(空写)时**同步**派发 —— 清缓存这类"必须尽快到 main"的调用不该// 因为多一个 await 被推到下一个微任务(顺序会被后面的写入抢到前面去)。@@ -257,10 +269,9 @@ export function persistCachedMessages(&& (typeof expectedOwnerToken === 'string' || expectedOwnerToken === undefined)&& (typeof expectedAccountCounter === 'number' || expectedAccountCounter === undefined)) {- dispatch(expectedInvalidation, expectedOwnerToken, expectedAccountCounter);- return;+ return dispatch(expectedInvalidation, expectedOwnerToken, expectedAccountCounter);}- void Promise.all([+ return Promise.all([expectedInvalidation instanceof Promise? expectedInvalidation: Promise.resolve(expectedInvalidation),@@ -272,7 +283,7 @@ export function persistCachedMessages(.then(([expected, ownerToken, accountCounter]) =>dispatch(expected, ownerToken, accountCounter),)- .catch((err: unknown) => log.debug('persist cached messages failed', err));+ .catch((err: unknown) => { log.debug('persist cached messages failed', err); return undefined; });}/**@@ -287,6 +298,8 @@ export function invalidationAtRequestStart(deviceId: string,sessionId: string,): number | Promise<number | undefined> {+ const clearing = pendingMessageClears.get(sessionId);+ if (clearing) return clearing;const known = knownMainInvalidation.get(sessionId);if (typeof known === 'number') return known;const api = bridge();@@ -317,7 +330,12 @@ export function clearCachedMessages(deviceId: string, sessionId: string): void {// 于是丢弃那次写 —— 否则它排在这次空写之后落地,把已经被 /clear、rewind、删消息抹掉的// 正文重新写回盘上(review: pr-code-review)。invalidationTokens.set(sessionId, (invalidationTokens.get(sessionId) ?? 0) + 1);- persistCachedMessages(deviceId, sessionId, []);+ knownMainInvalidation.delete(sessionId);+ const clearing = tokenReadWithin(persistCachedMessages(deviceId, sessionId, []));+ pendingMessageClears.set(sessionId, clearing);+ void clearing.finally(() => {+ if (pendingMessageClears.get(sessionId) === clearing) pendingMessageClears.delete(sessionId);+ });}/**@@ -504,6 +522,7 @@ export function clearMirrorCacheAccountState(): void {// sessionId 时的写点去等一笔注定拿不到令牌的读(review: Greptile P1)。`afterProtectedRead`// 的代际复核已是兜底,这里直接摘掉登记,让 B 的写点走「无在途读 → undefined」的快路径。pendingProtectedRead.clear();+ pendingMessageClears.clear();}export const __testing = {diff --git a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts b/apps/desktop/src/renderer/hooks/useDeviceProviders.tsindex 4c605ed454..400bfbdc7f 100644--- a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts+++ b/apps/desktop/src/renderer/hooks/useDeviceProviders.ts@@ -16,6 +16,8 @@ import { useEffect, useState } from 'react';import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';import type { ProviderView } from '@cindy/model-providers';import { defaultEffortForCapabilities } from '@cindy/model-providers';+import { isTransientRemoteError, isDeviceUnresponsiveRemoteError } from '@cindy/maker-shared/device-link-contract';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';import { createLogger } from '@/lib/logger';import { extractIpcError } from '@/utils/ipcError';@@ -279,9 +281,23 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResultreturn;}let cancelled = false;+ let retryOwner = getDataOwnerGeneration();+ let retryGeneration: number | undefined;+ const retryCurrent = () => !cancelled && isDataOwnerGenerationCurrent(retryOwner)+ && retryGeneration !== undefined && retryGeneration === (deviceGen.get(deviceId) ?? 0);+ // Recover on foreground entry only. Periodic per-hook retries would bypass+ // shared peer recovery scheduling and multiply across renderer windows.+ // Reconnect and provider-change refreshes retain their existing owners.+ const onVisibility = () => {+ if (document.visibilityState === 'visible' && retryCurrent()) {+ void fetchDeviceProviders(deviceId).catch(() => undefined);+ }+ };+ document.addEventListener('visibilitychange', onVisibility);const unsubscribe = subscribeDeviceProviders(deviceId, (event) => {if (cancelled) return;if (event.status === 'loading') {+ retryGeneration = undefined;// 保留上一份完整列表避免视觉跳变,但让模型选择逻辑等待同轮新快照。setOwnerDeviceId(deviceId);setLoading(true);@@ -290,6 +306,11 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResultreturn;}if (event.status === 'error') {+ retryOwner = getDataOwnerGeneration();+ retryGeneration = !event.unsupported && (+ isTransientRemoteError(event.error) || isDeviceUnresponsiveRemoteError(event.error)+ || extractIpcError(new Error(event.error))?.code === 'MODEL_VISIBILITY_NOT_READY'+ ) ? (deviceGen.get(deviceId) ?? 0) : undefined;setOwnerDeviceId(deviceId);if (event.unsupported) setPayload(EMPTY_PAYLOAD);setLoading(false);@@ -297,6 +318,7 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResultsetUnsupported(event.unsupported);return;}+ retryGeneration = undefined;setOwnerDeviceId(deviceId);setPayload({providers: event.providers,@@ -308,6 +330,11 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResultsetUnsupported(false);setLoading(false);});+ const cleanup = () => {+ cancelled = true;+ document.removeEventListener('visibilitychange', onVisibility);+ unsubscribe();+ };const cached = cache.get(deviceId);if (cached) {setOwnerDeviceId(deviceId);@@ -315,7 +342,7 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResultsetError(null);setUnsupported(false);setLoading(false);- return unsubscribe;+ return cleanup;}// cache miss:先清空,避免 fetch 解析前(失败则永远)残留上一设备的供应商。setOwnerDeviceId(deviceId);@@ -337,10 +364,7 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResultif (cancelled || (deviceGen.get(deviceId) ?? 0) !== remoteGeneration) return;setLoading(false);});- return () => {- cancelled = true;- unsubscribe();- };+ return cleanup;}, [deviceId]);const ownsSelectedDevice = ownerDeviceId === (deviceId ?? null);diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 69d2b94192..5c2d86f7a6 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -1,5 +1,7 @@import type { ImMessageSource } from '../../shared/imMessageSource';import { readBotAuthorizationCard } from '../../shared/botAuthorization';+import { confirmRemoteUsers, reserveRemoteUser } from './remoteUserHandoff';+import { readRemoteHistoryCache, remoteHistoryCacheWriter } from './remoteHistoryCache';/*** makerChatStore — Module-level store for Maker chat (Claude / Codex), sharded by sessionId.* ---------------------------------------------------------------------------@@ -446,6 +448,8 @@ export interface ChatMessage {* UI 可以据此显示 spinner / 灰色态(本轮不做,留给后续)。*/isPendingPersist?: boolean;+ /** Renderer-only position; DB acknowledgement does not yet transfer ownership to history. */+ localSendPrecedingClientIds?: readonly string[];/*** 意识拦截(订阅槽①):本条用户消息被某意识钩子拦下(未入库、未起 turn)。* 气泡照常显示(未发出),其下渲一条 error 红条,内容 = 意识返回的文本@@ -4477,7 +4481,8 @@ function applyInputProjection(...locallyDispatchedQueueItems,].reduce<ChatMessage[]>((messages, item) => {if (messages.some((message) => message.clientId === item.clientId)) return messages;- return [...messages, { ...item.chatMessage, isPendingPersist: true }];+ const row = { ...item.chatMessage, isPendingPersist: true };+ return [...messages, remoteProjection ? reserveRemoteUser(row, messages) : row];}, dedupedMessages);// Codex 原生重连已经被 host 接管、进入凭证切换等待或明确回落时,原生进行态行// 必须让位给 Cindy 的接管行、凭证切换状态或终态错误。没有这些字段的普通@@ -10855,6 +10860,10 @@ function createRemoteHistoryView(sessionId: string) {view: undefined, intentQueue: { tail: Promise.resolve() }, isCurrent: () => false,};const owner = getDataOwnerGeneration();+ // Begin the protected disk read before taking write tokens for remote requests.+ const cached = readRemoteHistoryCache<HistoryChatMessage>(deviceId, sessionId);+ let writeCache: ReturnType<typeof remoteHistoryCacheWriter> | undefined;+ let persistTimer: ReturnType<typeof setTimeout> | undefined;const isCurrent = (): boolean => isDataOwnerGenerationCurrent(owner)&& remoteProjectsStore.getSessionDeviceId(sessionId) === deviceId&& remoteHistoryViews.get(sessionId)?.view === view;@@ -10869,12 +10878,16 @@ function createRemoteHistoryView(sessionId: string) {};const view = new HistoryViewController<HistoryChatMessage>({page: async (before) => {+ const writer = remoteHistoryCacheWriter(deviceId, sessionId);const page = await call<HistoryViewPage<Message>>('local-db:messages:view', [sessionId, { before }]);if (page == null) throw new Error('[CHANNEL_NOT_ALLOWED] History view is unavailable');+ writeCache = writer;return { ...page, items: mapHistoryViewMessages(page.items, mapRows) };},details: async (ref, after) => {+ const writer = remoteHistoryCacheWriter(deviceId, sessionId);const page = await call<HistoryDetailPage<Message>>('local-db:messages:work-details', [sessionId, ref, { after }]);+ writeCache = writer;return { ...page, messages: mapRows(page.messages) };},expanded: async (refs) => {@@ -10892,8 +10905,18 @@ function createRemoteHistoryView(sessionId: string) {remoteHistoryViews.set(sessionId, entry);view.setNetworkAvailable(!isRemoteDeviceMarkedDisconnected(deviceId));view.subscribe(() => {+ if (persistTimer) clearTimeout(persistTimer);if (!isCurrent() || !sessions.has(sessionId)) return;const snapshot = view.getSnapshot();+ if (isHistoryViewUnavailable(snapshot.error)) {+ writeCache = undefined;+ // Keep the last usable mirror until the raw fallback succeeds and replaces it.+ setState(sessionId, (state) => ({ ...state, messages: confirmRemoteUsers(state.messages,+ new Set(state.messages.filter((row) => !row.isPendingPersist).map((row) => row.clientId))) }));+ } else if (snapshot.ready && !snapshot.loading && !snapshot.error && writeCache) {+ const writer = writeCache;+ persistTimer = setTimeout(() => { if (isCurrent()) writer(snapshot); }, 1200);+ }if (!snapshot.ready) {if (view.isActive() && isHistoryViewUnavailable(snapshot.error)) {void reconcileRemoteMessages(sessionId, { force: true }).catch(() => undefined);@@ -10903,12 +10926,19 @@ function createRemoteHistoryView(sessionId: string) {const available = historyViewLeaves(snapshot.items).flatMap((item) => item.type === 'messages' ? item.messages : []);for (const detail of snapshot.details.values()) available.push(...detail.messages);setState(sessionId, (state) => ({ ...state, historyLoaded: true,- messages: mergeMessages(available, state.messages.filter((message) => !message.cacheHydrated), { addOnly: true }),+ messages: confirmRemoteUsers(+ mergeMessages(available, state.messages.filter((message) => !message.cacheHydrated), { addOnly: true }),+ new Set(available.filter((message) => message.role === 'user').map((message) => message.clientId)),+ ),hasMoreMessages: snapshot.hasMore, isLoadingMore: snapshot.loading,oldestMessageId: snapshot.nextCursor,historyWindowHasIsland: false,}));});+ void view.restoreCachedView(async () => {+ const snapshot = await cached;+ return isCurrent() ? snapshot : null;+ });return view;}@@ -10918,6 +10948,7 @@ function ensureInitialMessages(sessionId: string): void {if (deviceId && isRemoteDeviceMarkedDisconnected(deviceId)) {_historyLoadOrigin.set(sessionId, deviceId);noteInputProjectionOrigin(sessionId, deviceId);+ createRemoteHistoryView(sessionId);hydrateRemoteMessagesFromCache(sessionId);return;}@@ -11055,9 +11086,7 @@ function ensureInitialMessages(sessionId: string): void {const snapshot = view.getSnapshot();if (!snapshot.error && snapshot.ready) {if (isCurrentHistoryLoad()) {- // This path bypasses the raw latest-page cache write. Retire that old- // cache instead of persisting an incomplete projection as raw history.- clearCachedMessages(historyOriginAtStart!, sessionId);+ // The structured snapshot is persisted through the same mirror-cache barriers.settleCacheHydration(sessionId);}releaseHistoryFetchIfCurrent(sessionId, historyFetchToken);@@ -11456,6 +11485,7 @@ async function continuePlanResolutionAfterIdleDiscovery(sessionId: string): Prom*/function reloadMessages(sessionId: string, opts?: { allowCacheHydrate?: boolean }): void {discardPendingTextDelta(sessionId);+ if (!opts?.allowCacheHydrate) invalidateRemoteMessageCache(sessionId);// 代际递增:作废 in-flight 的 loadOlderMessages 追页窗口(见 _messagesEpoch 注释)。invalidateMessageHistoryWindow(sessionId);invalidateHistoryFetch(sessionId);@@ -11480,7 +11510,6 @@ function reloadMessages(sessionId: string, opts?: { allowCacheHydrate?: boolean// 标记没了而盘上那份还是 rewind 之前的窗口 —— 下次离线冷启动照样 hydrate 出已被软删// 的消息(review: codex P1)。所以同时把盘上那份清掉:缓存是纯优化,重载后的首拉// 成功时会重新写上。- invalidateRemoteMessageCache(sessionId);}setState(sessionId, (s) => {const optimisticRecords = remoteOptimisticSendRecords(sessionId);@@ -13072,7 +13101,8 @@ function completeRemoteOptimisticMaterialization(const messages = state.messages.map((message) => {if (message.clientId !== clientId || message.isPendingPersist !== true) return message;changed = true;- return { ...queued.chatMessage, isPendingPersist: true };+ return { ...queued.chatMessage, isPendingPersist: true,+ ...(message.localSendPrecedingClientIds ? { localSendPrecedingClientIds: message.localSendPrecedingClientIds } : {}) };});return changed ? { ...state, pendingQueue, messages } : state;});@@ -13730,7 +13760,9 @@ async function sendMessageCore(setState(sessionId, (s) =>s.messages.some((m) => m.clientId === queued.clientId)? s- : { ...s, messages: [...s.messages, { ...queued.chatMessage, isPendingPersist: true }] },+ : { ...s, messages: [...s.messages, deviceLinkRemote+ ? reserveRemoteUser({ ...queued.chatMessage, isPendingPersist: true }, s.messages)+ : { ...queued.chatMessage, isPendingPersist: true }] },);}@@ -14124,7 +14156,7 @@ async function steerMessageCore(setState(sessionId, (s) =>s.messages.some((message) => message.clientId === queued.clientId)? s- : { ...s, messages: [...s.messages, { ...queued.chatMessage, isPendingPersist: true }] },+ : { ...s, messages: [...s.messages, reserveRemoteUser({ ...queued.chatMessage, isPendingPersist: true }, s.messages)] },);}const rollbackOptimisticSteer = () => {diff --git a/apps/desktop/src/renderer/lib/remoteHistoryCache.ts b/apps/desktop/src/renderer/lib/remoteHistoryCache.tsnew file mode 100644index 0000000000..9a21233db1--- /dev/null+++ b/apps/desktop/src/renderer/lib/remoteHistoryCache.ts@@ -0,0 +1,63 @@+import type { HistoryMessageSource, HistoryViewSnapshot } from '@cindy/maker-shared/message-window';+import { historyWorkSummaries } from '@cindy/maker-shared/message-window';+import {+ decodeRemoteHistory,+ encodeRemoteHistory,+ fitsRemoteHistoryCache,+ currentRemoteHistoryDetails,+} from '../../shared/remoteHistoryCache';+import {+ readCachedMessages,+ persistCachedMessages,+ clearCachedMessages,+ sessionCacheInvalidationToken,+ invalidationAtRequestStart,+ ownerTokenAtRequestStart,+ accountCounterAtRequestStart,+} from '@/features/device-link/mirrorCacheClient';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';++/** Capture before the remote read, never when the eventual snapshot is written. */+export function remoteHistoryCacheWriter(deviceId: string, sessionId: string) {+ const owner = getDataOwnerGeneration();+ const token = sessionCacheInvalidationToken(sessionId);+ const invalidation = invalidationAtRequestStart(deviceId, sessionId);+ const ownerToken = ownerTokenAtRequestStart(sessionId);+ const account = accountCounterAtRequestStart(sessionId);+ return <T extends HistoryMessageSource>(snapshot: HistoryViewSnapshot<T>) => {+ if (+ !isDataOwnerGenerationCurrent(owner) ||+ token !== sessionCacheInvalidationToken(sessionId) ||+ !snapshot.ready ||+ snapshot.loading ||+ snapshot.error+ )+ return;+ // A page can be ready while its expanded work is still refreshing. Do not+ // replace the last usable mirror with a projection whose detail is omitted.+ const currentDetails = currentRemoteHistoryDetails(snapshot);+ if (historyWorkSummaries(snapshot.items).some((summary) =>+ snapshot.expanded.has(summary.key) && !currentDetails.has(summary.key))) return;+ const text = encodeRemoteHistory(snapshot);+ if (!fitsRemoteHistoryCache(text)) {+ clearCachedMessages(deviceId, sessionId);+ return;+ }+ persistCachedMessages(deviceId, sessionId, [], invalidation, ownerToken, account, text);+ };+}++export async function readRemoteHistoryCache<T extends HistoryMessageSource>(+ deviceId: string,+ sessionId: string,+): Promise<HistoryViewSnapshot<T> | null> {+ const token = sessionCacheInvalidationToken(sessionId);+ let snapshot: HistoryViewSnapshot<T> | null = null;+ await readCachedMessages(deviceId, sessionId, (value) => {+ snapshot = decodeRemoteHistory<T>(value);+ });+ return token === sessionCacheInvalidationToken(sessionId) ? snapshot : null;+}diff --git a/apps/desktop/src/renderer/lib/remoteUserHandoff.ts b/apps/desktop/src/renderer/lib/remoteUserHandoff.tsnew file mode 100644index 0000000000..57c84a0e2a--- /dev/null+++ b/apps/desktop/src/renderer/lib/remoteUserHandoff.ts@@ -0,0 +1,56 @@+/** View-only send positions survive the DB echo until history owns the row. */+export interface LocalUserHandoff {+ clientId: string;+ role: string;+ localSendPrecedingClientIds?: readonly string[];+}++export function reserveRemoteUser<T extends LocalUserHandoff>(row: T, preceding: readonly T[]): T {+ return { ...row, localSendPrecedingClientIds: preceding.map((message) => message.clientId) };+}++/** Device clocks are not evidence of which turn the user sent into. */+export function projectRemoteUsers<T extends LocalUserHandoff>(+ messages: readonly T[],+ historyClientIds: ReadonlySet<string> = new Set(),+): T[] {+ // Authoritative history is rendered before its live tail, even if raw timestamps+ // put a new reply ahead of the late first page. This boundary still applies+ // after history confirms the last local user and retires its reservation.+ const historical = (row: T) => historyClientIds.has(row.clientId) && !row.localSendPrecedingClientIds;+ const result = [...messages.filter(historical), ...messages.filter((row) => !historical(row))];+ const reservations = messages.filter((row) => row.role === 'user' && row.localSendPrecedingClientIds);+ // Place earlier sends first: the raw timestamp order may put a later send first.+ reservations.sort((a, b) => b.localSendPrecedingClientIds!.includes(a.clientId) ? -1+ : a.localSendPrecedingClientIds!.includes(b.clientId) ? 1 : 0);+ for (const row of reservations) {+ const preceding = new Set(row.localSendPrecedingClientIds);+ result.splice(+ result.findIndex((message) => message.clientId === row.clientId),+ 1,+ );+ let after = -1;+ for (let index = 0; index < result.length; index++) {+ // A partial cold cache may have supplied an anchor before newer history+ // arrived. The whole authoritative prefix is still before this local send.+ if (preceding.has(result[index].clientId) || historical(result[index])) after = index;+ }+ result.splice(after + 1, 0, row);+ }+ return result;+}++/** Retire once, so later rewind/deletion cannot revive a local reservation. */+export function confirmRemoteUsers<T extends LocalUserHandoff>(+ messages: T[],+ confirmed: ReadonlySet<string>,+): T[] {+ let changed = false;+ const next = messages.map((row) => {+ if (!row.localSendPrecedingClientIds || !confirmed.has(row.clientId)) return row;+ const { localSendPrecedingClientIds: _position, ...message } = row;+ changed = true;+ return message as T;+ });+ return changed ? next : messages;+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex fc632713cb..642965b406 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3919,6 +3919,7 @@ interface ElectronAPI {sessionId: string,) => Promise<{messages: Record<string, unknown>[];+ historyView?: string;invalidation?: number;ownerToken?: string;accountCounter?: number;@@ -3930,6 +3931,7 @@ interface ElectronAPI {expectedInvalidation?: number,expectedOwnerToken?: string,expectedAccountCounter?: number,+ historyView?: string,) => Promise<{ ok: true; invalidation?: number }>;getSessionList: () => Promise<{devices: Array<{diff --git a/apps/desktop/src/shared/remoteHistoryCache.ts b/apps/desktop/src/shared/remoteHistoryCache.tsnew file mode 100644index 0000000000..f55c283448--- /dev/null+++ b/apps/desktop/src/shared/remoteHistoryCache.ts@@ -0,0 +1,141 @@+import type { HistoryMessageSource, HistoryViewSnapshot } from '@cindy/maker-shared/message-window';+import { historyWorkSummaries } 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>) {+ const summaries = new Map(historyWorkSummaries(snapshot.items).map((summary) => [summary.key, summary]));+ return new Map([...snapshot.details].filter(([key, detail]) => {+ const summary = summaries.get(key);+ return summary && detail.complete && !detail.loading && !detail.error+ && detail.revision === summary.revision && detail.lastMessageId === summary.lastMessageId;+ }));+}++/** Same bounded, versioned snapshot in Main's existing account-scoped mirror file. */+export const MAX_HISTORY_CACHE_CHARS = 512 * 1024;++/** Reserve space for StoredMessages metadata; historyView is itself a JSON string. */+export function fitsRemoteHistoryCache(text: string): boolean {+ return text.length <= MAX_HISTORY_CACHE_CHARS+ && new TextEncoder().encode(JSON.stringify(text)).byteLength + 256 <= 512 * 1024;+}+const record = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === 'object' && !Array.isArray(value);++function validRows(value: unknown): boolean {+ return (+ Array.isArray(value) &&+ value.every(+ (row) =>+ record(row) &&+ ['id', 'clientId', 'role', 'createdAt'].every((key) => typeof row[key] === 'string') &&+ typeof row.content === 'string' &&+ !row.isPendingPersist &&+ !row.localSendPrecedingClientIds,+ )+ );+}++function validSummary(value: unknown, depth: number): boolean {+ return (+ depth < 32 &&+ record(value) &&+ ['key', 'firstMessageId', 'lastMessageId', 'revision'].every(+ (key) => typeof value[key] === 'string',+ ) &&+ ['startedAtMs', 'endedAtMs', 'messageCount', 'toolCount'].every(+ (key) => typeof value[key] === 'number' && Number.isFinite(value[key]),+ ) &&+ typeof value.isStreaming === 'boolean' &&+ (value.preview === undefined || validSummary(value.preview, depth + 1))+ );+}++function validItems(value: unknown, depth = 0): boolean {+ return (+ depth < 32 &&+ Array.isArray(value) &&+ value.every(+ (item) =>+ record(item) &&+ typeof item.key === 'string' &&+ (item.type === 'messages'+ ? validRows(item.messages)+ : item.type === 'work' &&+ validSummary(item.summary, depth) &&+ (item.children === undefined || validItems(item.children, depth + 1))),+ )+ );+}++export function decodeRemoteHistory<T extends HistoryMessageSource>(+ text: unknown,+): HistoryViewSnapshot<T> | null {+ if (typeof text !== 'string' || text.length > MAX_HISTORY_CACHE_CHARS) return null;+ try {+ const value = JSON.parse(text);+ if (+ !record(value) ||+ value.version !== 1 ||+ !validItems(value.items) ||+ typeof value.hasMore !== 'boolean' ||+ !(value.nextCursor === null || typeof value.nextCursor === 'string') ||+ !Array.isArray(value.expanded) ||+ !value.expanded.every((key) => typeof key === 'string') ||+ !Array.isArray(value.details) ||+ !value.details.every(+ (entry) =>+ Array.isArray(entry) &&+ entry.length === 2 &&+ typeof entry[0] === 'string' &&+ record(entry[1]) &&+ entry[1].complete === true &&+ entry[1].loading === false &&+ entry[1].error === null &&+ typeof entry[1].revision === 'string' &&+ typeof entry[1].lastMessageId === 'string' &&+ validRows(entry[1].messages),+ )+ )+ return null;+ const snapshot = {+ items: value.items,+ details: new Map(value.details),+ expanded: new Set(value.expanded),+ hasMore: value.hasMore,+ nextCursor: value.nextCursor,+ ready: true,+ loading: false,+ error: null,+ } as HistoryViewSnapshot<T>;+ return { ...snapshot, details: currentRemoteHistoryDetails(snapshot) };+ } catch {+ return null;+ }+}++export function encodeRemoteHistory<T extends HistoryMessageSource>(+ snapshot: HistoryViewSnapshot<T>,+): string {+ return JSON.stringify(+ {+ version: 1,+ items: snapshot.items,+ details: [...currentRemoteHistoryDetails(snapshot)],+ expanded: [...snapshot.expanded],+ hasMore: snapshot.hasMore,+ nextCursor: snapshot.nextCursor,+ },+ (key, value) => {+ // A cached transcript may be read offline. Never revive a live indicator or send payload.+ if (key === 'isStreaming' || key === 'streaming') return false;+ if (+ key === 'retryFiles' ||+ key === 'localSendPrecedingClientIds' ||+ key === 'isPendingPersist'+ )+ return undefined;+ return value;+ },+ );+}