Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(device-link): 修复远程消息缺失与重连响应积压 (#4184)

DavidShenXD0972a8bed885
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
index 960333fc4b..e76ab21258 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
@@ -105,6 +105,7 @@ import {
type DeviceLinkIpcDeps,
} from '../device-link/ipc';
import { DeviceLinkError } from '@cindy/device-link';
+import { invokeWithClosedLinkRecovery } from '../device-link/linkRecovery';
import { ServerApiError } from '../serverApiClient';
import {
__testing as settingsTesting,
@@ -898,6 +899,28 @@ describe('device-link controller handlers', () => {
);
});
+ it('invoke: a second peer reset stops retrying and becomes a disconnected IPC error', async () => {
+ const reset = new DeviceLinkError('PEER_RESET', 'peer reset during read');
+ reset.inFlight = true;
+ const invoke = vi.fn().mockRejectedValue(reset);
+ const reopen = vi.fn().mockResolvedValue(undefined);
+ const deps = makeDeps({ invoke: () => invokeWithClosedLinkRecovery(invoke, reopen) });
+ await expect(handleInvoke(deps, 'dev-2', 'local-db:messages:list', ['session'])).rejects.toMatchObject({
+ code: 'DEVICE_LINK_NOT_CONNECTED', message: '[DEVICE_LINK_NOT_CONNECTED] peer reset during read',
+ });
+ expect(invoke).toHaveBeenCalledTimes(2);
+ expect(reopen).toHaveBeenCalledTimes(1);
+ });
+
+ it('invoke: a peer reset result envelope uses the same IPC mapping', async () => {
+ const deps = makeDeps({ invoke: vi.fn().mockResolvedValue({
+ ok: false, error: { code: 'PEER_RESET', message: 'peer reset' },
+ }) });
+ await expect(handleInvoke(deps, 'dev-2', 'local-db:messages:list', ['session'])).rejects.toMatchObject({
+ code: 'DEVICE_LINK_NOT_CONNECTED', message: '[DEVICE_LINK_NOT_CONNECTED] peer reset',
+ });
+ });
+
it('invoke:出方向附件改写失败 → DEVICE_LINK_MEDIA_TRANSFER_FAILED,不发 invoke(整条不发)', async () => {
const invoke = vi.fn().mockResolvedValue({ ok: true, result: null });
const deps = makeDeps({
diff --git a/apps/desktop/src/main/device-link/__tests__/linkRecovery.test.ts b/apps/desktop/src/main/device-link/__tests__/linkRecovery.test.ts
index 1d3c35c544..e8e8a58631 100644
--- a/apps/desktop/src/main/device-link/__tests__/linkRecovery.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/linkRecovery.test.ts
@@ -37,6 +37,37 @@ describe('device-link closed link recovery', () => {
expect(reopen.mock.invocationCallOrder[0]).toBeLessThan(invoke.mock.invocationCallOrder[1]);
});
+ it('peer reset 的幂等读请求会 reopen 后只重试一次', async () => {
+ const peerReset = new DeviceLinkError('PEER_RESET', 'peer link reset');
+ peerReset.inFlight = true;
+ let invokeCount = 0;
+ const invoke = vi.fn(async () => {
+ invokeCount += 1;
+ if (invokeCount === 1) throw peerReset;
+ return { ok: true };
+ });
+ const reopen = vi.fn(async () => undefined);
+
+ await expect(invokeWithClosedLinkRecovery(invoke, reopen)).resolves.toEqual({ ok: true });
+ expect(reopen).toHaveBeenCalledTimes(1);
+ expect(invoke).toHaveBeenCalledTimes(2);
+ });
+
+ it('第二次 peer reset 不会开启第二轮自动重试', async () => {
+ const firstReset = new DeviceLinkError('PEER_RESET', 'first peer reset');
+ firstReset.inFlight = true;
+ const secondReset = new DeviceLinkError('PEER_RESET', 'second peer reset');
+ secondReset.inFlight = true;
+ const invoke = vi.fn()
+ .mockRejectedValueOnce(firstReset)
+ .mockRejectedValueOnce(secondReset);
+ const reopen = vi.fn(async () => undefined);
+
+ await expect(invokeWithClosedLinkRecovery(invoke, reopen)).rejects.toBe(secondReset);
+ expect(reopen).toHaveBeenCalledTimes(1);
+ expect(invoke).toHaveBeenCalledTimes(2);
+ });
+
it('已发出的请求即使标成 LINK_NOT_OPEN 也不重试', async () => {
const closed = new DeviceLinkError('LINK_NOT_OPEN', 'late close');
closed.inFlight = true;
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 544178237a..6495fbfdda 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -684,6 +684,9 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
// 下更激进的宽限会把「慢但活着」误判成死链,造成重连循环(mobile 用 10s×1 是因为
// 手机端 TCP 半开假活远比桌面常见,桌面不照搬)。
timing: { pingIntervalMs: 15_000 },
+ // peer ACK 耗尽时,幂等的 local-db 读请求交给 linkRecovery 快速重开并只重试一次;
+ // 写请求与长执行请求保持原有 in-flight 语义,避免重复副作用。
+ peerResetReadRetry: true,
});
responsivenessTracker = createResponsivenessTracker({
@@ -819,12 +822,13 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
// 入队与每次尝试都过同一个方向判据(见 hasOutboundControlIntent):只对本机
// 确实在控制的设备重建,被控端方向的入站帧自然忽略。
client.onReliableFrameBeforeLink((deviceId) => {
- if (!hasOutboundControlIntent(deviceId)) return;
- if (readDeviceLinkSettings().disabledControlDeviceIds.includes(deviceId)) return;
+ if (!hasOutboundControlIntent(deviceId)) return false;
+ if (readDeviceLinkSettings().disabledControlDeviceIds.includes(deviceId)) return false;
log.info(
`re-opening control link for ${deviceId.slice(0, 8)} after before-link reliable frame`,
);
transportTimeoutReopen.trigger(deviceId);
+ return true;
});
client.onPresenceChanged((snap: PresenceSnapshot) => {
markControllerPresenceFresh(controllerPresenceFreshness, snap.deviceId);
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index a19813f68e..390ebef573 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -205,6 +205,7 @@ const DEVICE_LINK_CODE_MAP: Record<string, IpcErrorCode> = {
VERSION_MISMATCH: 'DEVICE_LINK_VERSION_MISMATCH',
NOT_CONNECTED: 'DEVICE_LINK_NOT_CONNECTED',
LINK_NOT_OPEN: 'DEVICE_LINK_NOT_CONNECTED',
+ PEER_RESET: 'DEVICE_LINK_NOT_CONNECTED',
BACKPRESSURE: 'DEVICE_LINK_NOT_CONNECTED',
};
diff --git a/apps/desktop/src/main/device-link/linkRecovery.ts b/apps/desktop/src/main/device-link/linkRecovery.ts
index f25cd1b175..3f028ea02a 100644
--- a/apps/desktop/src/main/device-link/linkRecovery.ts
+++ b/apps/desktop/src/main/device-link/linkRecovery.ts
@@ -9,8 +9,9 @@ export function requiresSessionLink(topics: readonly string[]): boolean {
}
/**
- * LINK_NOT_OPEN 由 DeviceLinkClient 在真正发帧前抛出,因此可先重开链路再重试一次。
- * 已经发出的请求或其它错误绝不重试,避免 enqueue / send 等写操作重复执行。
+ * LINK_NOT_OPEN 由 DeviceLinkClient 在真正发帧前抛出;PEER_RESET 只用于已经
+ * 明确标记为幂等读的请求。两者都先重开链路再重试一次,已经发出的写请求或其它
+ * 错误绝不重试,避免 enqueue / send 等写操作重复执行。
*/
export async function invokeWithClosedLinkRecovery<T>(
invoke: () => Promise<T>,
@@ -21,11 +22,12 @@ export async function invokeWithClosedLinkRecovery<T>(
try {
return await invoke();
} catch (err) {
- if (
- !(err instanceof DeviceLinkError)
- || err.code !== 'LINK_NOT_OPEN'
- || err.inFlight === true
- ) {
+ const retryable = err instanceof DeviceLinkError
+ && (
+ (err.code === 'LINK_NOT_OPEN' && err.inFlight !== true)
+ || (err.code === 'PEER_RESET' && err.inFlight === true)
+ );
+ if (!retryable) {
throw err;
}
}
diff --git a/apps/desktop/src/main/maker-host/codex-global-plugins.ts b/apps/desktop/src/main/maker-host/codex-global-plugins.ts
index 6535cbb4bb..72c635e206 100644
--- a/apps/desktop/src/main/maker-host/codex-global-plugins.ts
+++ b/apps/desktop/src/main/maker-host/codex-global-plugins.ts
@@ -1,7 +1,7 @@
import os from 'node:os';
import path from 'node:path';
import { promises as fsp } from 'node:fs';
-import { createHash } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import { parse as parseToml, stringify as stringifyToml } from 'smol-toml';
import yaml from 'js-yaml';
import type { CapabilityRoutingPolicy } from '@cindy/maker-core';
@@ -1025,7 +1025,12 @@ export async function writeFileAtomicIfUnchanged(
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
}
- const tmp = `${file}.xdt-plugins-sync.tmp-${process.pid}-${Date.now()}`;
+ // Concurrent callers in the same process can reach this function during the
+ // same millisecond. A pid/timestamp name lets them share and delete one
+ // temporary file, which makes the winner's rename fail with ENOENT on
+ // Windows. Keep every attempt on its own path so the compare-and-rename
+ // protocol remains race-safe.
+ const tmp = `${file}.xdt-plugins-sync.tmp-${process.pid}-${randomUUID()}`;
await fsp.writeFile(tmp, content, { encoding: 'utf8', mode });
try {
await fsp.chmod(tmp, mode);
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
index b512381d5b..ebcfe9ecdb 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
@@ -86,6 +86,7 @@ function makeFakeHost(deviceId: string, deviceName: string) {
const messages = new Map<string, Message[]>();
let pushCb: ((p: RemotePush) => void) | null = null;
let historyViewEnabled = false;
+ let historyViewStreaming = false;
function meta(sid: string): Record<string, unknown> {
return {
@@ -101,7 +102,7 @@ function makeFakeHost(deviceId: string, deviceName: string) {
if (!historyViewEnabled) return null;
const rows = messages.get(args[0] as string) ?? [];
const before = (args[1] as { before?: string })?.before;
- const projected = projectHistoryView(before ? rows.slice(0, rows.findIndex((row) => row.id === before)) : rows, false);
+ const projected = projectHistoryView(before ? rows.slice(0, rows.findIndex((row) => row.id === before)) : rows, !before && historyViewStreaming);
const items = projected.slice(-20);
const first = items[0];
const hasMore = projected.length > items.length;
@@ -140,12 +141,9 @@ function makeFakeHost(deviceId: string, deviceName: string) {
return {
deviceId,
deviceName,
- enableHistoryView: () => { historyViewEnabled = true; },
+ enableHistoryView: (streaming = false) => { historyViewEnabled = true; historyViewStreaming = streaming; },
disableHistoryView: () => { historyViewEnabled = false; },
invoke,
- push(channel: string, payload: unknown): void {
- pushCb?.({ deviceId, channel, payload });
- },
/** 注册控制端 onRemotePush 回调(被控端经此向控制端转发广播)。 */
registerPush(cb: (p: RemotePush) => void): () => void {
pushCb = (push) => cb({ ...push, ownerStamp: push.ownerStamp ?? TEST_OWNER_STAMP });
@@ -153,6 +151,9 @@ function makeFakeHost(deviceId: string, deviceName: string) {
pushCb = null;
};
},
+ push(channel: string, payload: unknown): void {
+ pushCb?.({ deviceId, channel, payload });
+ },
seedSession(sid: string, m: Record<string, unknown> = {}, history: Message[] = []): void {
sessionsMeta.set(sid, m);
messages.set(sid, [...history]);
@@ -307,6 +308,8 @@ describe('device-link controller mirror — end-to-end scenarios', () => {
finish([durable]);
await flush();
await flush();
+ await flush();
+ await flush();
const row = makerChatStore.getSnapshot(s).messages.find((message) => message.clientId === 'live');
expect(row?.content).toBe(concurrent ? 'prefix newer' : 'prefix complete');
expect(row?.isStreaming).toBe(concurrent);
@@ -319,6 +322,199 @@ describe('device-link controller mirror — end-to-end scenarios', () => {
}
});
+ it.each(['resume', 'force', 'resync'] as const)('keeps live thinking receptive to deltas after HistoryView recovery (%s)', async (recovery) => {
+ const s = sid();
+ const startedAt = Date.parse('2026-09-08T00:00:01Z');
+ const user = dbMessage(s, 'question', 'question', '2026-09-08T00:00:00Z', 'user');
+ host.enableHistoryView(true);
+ host.seedSession(s, {}, [user]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ const leave = makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(); await flush();
+ const thinking = (data: Record<string, unknown>) => host.push('maker:event', {
+ sessionId: s, event: { type: 'thinking', source: 'claude-code', agentMeta: { parentUuid: 'toolu_worker' }, data: { blockId: 'live-thought', ...data } },
+ });
+ host.push('maker:event', { sessionId: s, event: { type: 'status', data: { status: 'Running', isRunning: true } } });
+ thinking({ stage: 'start', startedAt });
+ thinking({ stage: 'delta', text: 'current thought' });
+ const current = () => makerChatStore.getSnapshot(s).messages.find(row => row.clientId === 'live-thought');
+ expect(current()).toMatchObject({ content: 'current thought', isStreaming: true, thinkingStartedAt: startedAt });
+ // Child-agent thinking stays inline in the real Host projection. Its
+ // getSessionThinkingSnapshots() row is synthetic, with no terminal marker.
+ const liveSnapshot: Message = {
+ ...dbMessage(s, 'history-live:live-thought', '', new Date(startedAt).toISOString(), 'thinking'),
+ clientId: 'live-thought', agentMeta: { parentUuid: 'toolu_worker' },
+ content: { kind: 'thinking', text: 'current thought', durationMs: 0 },
+ };
+ host.seedSession(s, {}, [user, liveSnapshot]);
+ if (recovery === 'resume') { leave(); makerChatStore.enterView(s); }
+ else if (recovery === 'force') await makerChatStore.reconcileRemoteMessages(s, { force: true });
+ else host.push('maker:session-sync', { sessionId: s, resyncRequired: true });
+ await flush(); await flush();
+ expect(JSON.stringify(getRemoteHistoryView(s)!.getSnapshot().items)).toContain('history-live:live-thought');
+ expect(current()).toMatchObject({ content: 'current thought', isStreaming: true, thinkingStartedAt: startedAt });
+ thinking({ stage: 'delta', text: ' continues' });
+ expect(current()).toMatchObject({ content: 'current thought continues', isStreaming: true });
+ expect(makerChatStore.getSnapshot(s).messages.filter(row => row.clientId === 'live-thought')).toHaveLength(1);
+
+ // A lost final event is still healed once the Host returns a durable row.
+ host.seedSession(s, {}, [user, { ...liveSnapshot, id: 'stored-thought',
+ content: { kind: 'thinking', text: 'completed thought', durationMs: 2000, finishedAt: startedAt + 2000 } }]);
+ await makerChatStore.reconcileRemoteMessages(s, { force: true });
+ expect(current()).toMatchObject({ content: 'completed thought', isStreaming: false, thinkingDurationMs: 2000 });
+ makerChatStore.purgeSession(s);
+ });
+
+ it.each(['force', 'resync', 'snapshot-resync', 'newer-live'] as const)(
+ 'waits for expanded work details to heal a lost terminal row (%s)', async (recovery) => {
+ const s = sid();
+ host.enableHistoryView(true);
+ const startedAt = Date.parse('2026-09-08T00:00:01Z');
+ const user = dbMessage(s, 'question', 'question', '2026-09-08T00:00:00Z', 'user');
+ host.seedSession(s, {}, [user]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(); await flush();
+ host.push('maker:event', { sessionId: s, event: { type: 'status', data: { status: 'Running', isRunning: true } } });
+ const thinking = (data: Record<string, unknown>) => host.push('maker:event', {
+ sessionId: s, event: { type: 'thinking', data: { blockId: 'client-thought', ...data } },
+ });
+ thinking({ stage: 'start', startedAt });
+ thinking({ stage: 'delta', text: 'stale thought' });
+ const thought = () => makerChatStore.getSnapshot(s).messages.find(row => row.clientId === 'client-thought');
+ const durable = { ...dbMessage(s, 'thought', '', new Date(startedAt).toISOString(), 'thinking'),
+ content: { kind: 'thinking', text: 'sealed thought', durationMs: 2000, finishedAt: startedAt + 2000 } };
+ host.seedSession(s, {}, [user, durable, dbMessage(s, 'current', '# Current answer\nold text', '2026-09-08T00:00:04Z')]);
+ // The live current block is valid even if the same history page contains
+ // an older copy. No terminal event/persistence echo for the thought arrived.
+ const snapshot = (resyncRequired: boolean) => host.push('maker:session-sync', {
+ sessionId: s, persistId: 'client-current', resyncRequired,
+ event: { type: 'text', data: { text: 'current live snapshot', isFullText: true, isFinal: false } },
+ });
+ snapshot(false);
+ const view = getRemoteHistoryView(s)!;
+ await view.refresh();
+ const group = view.getSnapshot().items.find((item) => item.type === 'work');
+ if (!group) throw new Error('Expected an expanded work group');
+ const original = host.invoke.getMockImplementation()!;
+ let finish!: () => void;
+ host.invoke.mockImplementation(async (...args) => {
+ const value = await original(...args);
+ if (args[1] === 'local-db:messages:work-details') await new Promise<void>(resolve => { finish = resolve; });
+ return value;
+ });
+ view.setExpanded(group.key, true);
+ await flush();
+ expect(finish).toBeTypeOf('function');
+ expect(thought()).toMatchObject({ content: 'stale thought', isStreaming: true });
+ let completed = false;
+ let pending: Promise<unknown> | undefined;
+ if (recovery === 'force') pending = makerChatStore.reconcileRemoteMessages(s, { force: true }).then(() => { completed = true; });
+ else if (recovery === 'resync') host.push('maker:session-sync', { sessionId: s, resyncRequired: true });
+ else snapshot(true);
+ await flush(); await flush();
+ expect(completed).toBe(false);
+ expect(thought()).toMatchObject({ content: 'stale thought', isStreaming: true });
+ if (recovery === 'newer-live') thinking({ stage: 'delta', text: ' updated during fetch' });
+ finish();
+ await pending;
+ await flush(); await flush();
+ expect(view.getSnapshot().details.get(group.key)?.messages[0]).toMatchObject({ clientId: 'client-thought', content: 'sealed thought' });
+ expect(thought()).toMatchObject(recovery === 'newer-live'
+ ? { content: 'stale thought updated during fetch', isStreaming: true }
+ : { content: 'sealed thought', isStreaming: false, thinkingDurationMs: 2000 });
+ if (recovery === 'snapshot-resync' || recovery === 'newer-live') expect(makerChatStore.getSnapshot(s).messages.find((row) => row.clientId === 'client-current')).toMatchObject({
+ content: 'current live snapshot', isStreaming: true,
+ });
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:work-details')).toHaveLength(1);
+ expect(host.invoke).not.toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
+ makerChatStore.purgeSession(s);
+ });
+
+ it('falls back to the authoritative raw window when expanded details fail during force repair', async () => {
+ const s = sid();
+ host.enableHistoryView(true);
+ const user = dbMessage(s, 'question', 'question', '2026-09-08T00:00:00Z', 'user');
+ host.seedSession(s, {}, [user]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(); await flush();
+ host.push('maker:event', { sessionId: s, event: { type: 'status', data: { status: 'Running', isRunning: true } } });
+ host.push('maker:event', { sessionId: s, event: { type: 'thinking', data: { blockId: 'client-thought', stage: 'start', startedAt: Date.now() } } });
+ host.push('maker:event', { sessionId: s, event: { type: 'thinking', data: { blockId: 'client-thought', stage: 'delta', text: 'stale thought' } } });
+ const durable = { ...dbMessage(s, 'thought', '', '2026-09-08T00:00:01Z', 'thinking'),
+ content: { kind: 'thinking', text: 'sealed thought', durationMs: 2000, finishedAt: Date.parse('2026-09-08T00:00:03Z') } };
+ host.seedSession(s, {}, [user, durable]);
+ const view = getRemoteHistoryView(s)!;
+ await view.refresh();
+ const group = view.getSnapshot().items.find((item) => item.type === 'work');
+ if (!group) throw new Error('Expected an expanded work group');
+ const original = host.invoke.getMockImplementation()!;
+ host.invoke.mockImplementation(async (...args) => {
+ if (args[1] === 'local-db:messages:work-details') throw new Error('transient details timeout');
+ return original(...args);
+ });
+ view.setExpanded(group.key, true);
+ await flush();
+ await expect(makerChatStore.reconcileRemoteMessages(s, { force: true })).resolves.toBe(true);
+ expect(makerChatStore.getSnapshot(s).messages.find(row => row.clientId === 'client-thought'))
+ .toMatchObject({ content: 'sealed thought', isStreaming: false, thinkingDurationMs: 2000 });
+ expect(host.invoke).toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
+ makerChatStore.purgeSession(s);
+ });
+
+ it.each([false, true])('recovers cancelled work details without reporting incomplete force success (rawFails=%s)', async (rawFails) => {
+ const s = sid();
+ host.enableHistoryView(true);
+ const user = dbMessage(s, 'question', 'question', '2026-09-08T00:00:00Z', 'user');
+ host.seedSession(s, {}, [user]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(); await flush();
+ host.push('maker:event', { sessionId: s, event: { type: 'thinking', data: { blockId: 'client-thought', stage: 'start', startedAt: Date.parse('2026-09-08T00:00:01Z') } } });
+ host.push('maker:event', { sessionId: s, event: { type: 'thinking', data: { blockId: 'client-thought', stage: 'delta', text: 'stale thought' } } });
+ const durable = { ...dbMessage(s, 'thought', '', '2026-09-08T00:00:01Z', 'thinking'),
+ content: { kind: 'thinking', text: 'sealed thought', durationMs: 2000, finishedAt: Date.parse('2026-09-08T00:00:03Z') } };
+ host.seedSession(s, {}, [user, durable]);
+ const view = getRemoteHistoryView(s)!;
+ await view.refresh();
+ const group = view.getSnapshot().items.find((item) => item.type === 'work')!;
+ const original = host.invoke.getMockImplementation()!;
+ let finish!: () => void;
+ const pendingDetails = new Promise<void>(resolve => { finish = resolve; });
+ const detailReads = vi.spyOn(view, 'loadDetails');
+ host.invoke.mockImplementation(async (...args) => {
+ if (rawFails && args[1] === 'local-db:messages:list') throw new Error('raw history unavailable');
+ const value = await original(...args);
+ if (args[1] === 'local-db:messages:work-details') await pendingDetails;
+ return value;
+ });
+ view.setExpanded(group.key, true);
+ await flush();
+ const force = makerChatStore.reconcileRemoteMessages(s, { force: true });
+ const result = rawFails ? expect(force).rejects.toThrow('raw history unavailable') : expect(force).resolves.toBe(true);
+ await vi.waitFor(() => expect(detailReads).toHaveBeenCalledWith(expect.objectContaining({ key: group.key }), { allowCollapsed: true }));
+ view.setExpanded(group.key, false);
+ finish();
+ await result;
+ expect(view.getSnapshot().expanded.has(group.key)).toBe(false);
+ expect(view.getSnapshot().details.get(group.key)?.complete).toBe(false);
+ expect(host.invoke).toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
+ const thought = () => makerChatStore.getSnapshot(s).messages.find(row => row.clientId === 'client-thought');
+ if (rawFails) {
+ expect(thought()).toMatchObject({ content: 'stale thought', isStreaming: true });
+ host.invoke.mockImplementation(original);
+ await expect(makerChatStore.reconcileRemoteMessages(s, { force: true })).resolves.toBe(true);
+ }
+ expect(thought()).toMatchObject({ content: 'sealed thought', isStreaming: false });
+ detailReads.mockRestore();
+ makerChatStore.purgeSession(s);
+ });
+
it('resumes terminal handoff when the first projected page was not ready before leaving', async () => {
const s = sid();
host.enableHistoryView();
@@ -792,6 +988,96 @@ describe('device-link controller mirror — end-to-end scenarios', () => {
expect(host.invoke).toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
expect(makerChatStore.getSnapshot(s).messages.map((row) => row.clientId)).toEqual(['client-old', 'client-new']);
});
+ it.each(['resync', 'queued-resync', 'stall', 'newer-live', 'snapshot-repair'] as const)(
+ 'recovers HistoryView rows without losing expanded history (%s)', async (scenario) => {
+ const s = sid();
+ host.enableHistoryView();
+ const history = [
+ dbMessage(s, 'u', 'previous question', '2026-06-15T00:00:00.000Z', 'user'),
+ { ...dbMessage(s, 'thought', '', '2026-06-15T00:00:01.000Z', 'thinking'),
+ content: { kind: 'thinking', text: 'expanded history', durationMs: 500, isRedacted: false } },
+ dbMessage(s, 'previous', 'previous answer', '2026-06-15T00:00:02.000Z'),
+ dbMessage(s, 'question', 'current question', '2026-06-15T00:00:03.000Z', 'user'),
+ ];
+ host.seedSession(s, {}, history);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(); await flush();
+ const view = getRemoteHistoryView(s)!;
+ expect(view.getSnapshot().ready).toBe(true);
+ const group = view.getSnapshot().items.find((item) => item.type === 'work')!;
+ view.setExpanded(group.key, true);
+ await flush();
+ expect(view.getSnapshot().details.get(group.key)?.messages[0].content).toBe('expanded history');
+
+ host.push('maker:event', { sessionId: s, event: { type: 'status', source: 'claude-code',
+ data: { status: 'thinking', isRunning: true, tokenUsage: 0, contextTokens: 0, contextWindow: 0 } } });
+ const snapshot = (text: string, resyncRequired = false) => host.push('maker:session-sync', {
+ sessionId: s, persistId: 'client-answer', resyncRequired,
+ event: { type: 'text', source: 'claude-code', data: { text, isFullText: true, isFinal: false } },
+ });
+ snapshot('stale prefix');
+ const raw = () => makerChatStore.getSnapshot(s).messages;
+ expect(makerChatStore.getSnapshot(s).isStreaming).toBe(true);
+ expect(raw().find((row) => row.clientId === 'client-answer')).toMatchObject({ content: 'stale prefix', isStreaming: true });
+ const handoff = new HistoryViewHandoff<HistoryChatMessage>((row) => !!row.isStreaming);
+ const visible = () => handoff.reconcile(view.getSnapshot(), raw().map(row => ({
+ ...row, id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',
+ })));
+ expect(visible().pending.has('client-answer')).toBe(true);
+
+ const original = host.invoke.getMockImplementation()!;
+ let finish: (() => void) | undefined;
+ let delayNextPage = scenario === 'queued-resync' || scenario === 'newer-live';
+ host.invoke.mockImplementation(async (device, channel, args) => {
+ const value = await original(device, channel, args);
+ if (channel === 'local-db:messages:view' && delayNextPage) {
+ delayNextPage = false;
+ await new Promise<void>(resolve => { finish = resolve; });
+ }
+ return value;
+ });
+ let repair: Promise<boolean> | undefined;
+ if (scenario === 'queued-resync') {
+ repair = makerChatStore.reconcileRemoteMessages(s, { repair: true });
+ await flush();
+ expect(finish).toBeTypeOf('function');
+ }
+ // The final text and terminal push were both lost. The same persistId is
+ // now sealed in the Host DB; the controller still has the streaming prefix.
+ host.hostMessage(s, dbMessage(s, 'answer', 'authoritative sealed answer', '2026-06-15T00:00:04.000Z'), { lossy: true });
+ const readsBeforeRecovery = host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view').length;
+ let forced: Promise<boolean> | undefined;
+ if (scenario === 'stall') forced = makerChatStore.reconcileRemoteMessages(s, { force: true });
+ else if (scenario === 'snapshot-repair') snapshot('current live snapshot', true);
+ else host.push('maker:session-sync', { sessionId: s, resyncRequired: true });
+ await flush();
+ if (scenario === 'newer-live') {
+ expect(finish).toBeTypeOf('function');
+ snapshot('newer live text received during recovery');
+ }
+ finish?.();
+ await repair; await forced;
+ await flush(); await flush();
+
+ const stillLive = scenario === 'newer-live' || scenario === 'snapshot-repair';
+ const expected = scenario === 'newer-live' ? 'newer live text received during recovery'
+ : scenario === 'snapshot-repair' ? 'current live snapshot' : 'authoritative sealed answer';
+ expect(raw().filter((row) => row.clientId === 'client-answer')).toEqual([
+ expect.objectContaining({ content: expected, isStreaming: stillLive }),
+ ]);
+ expect(getRemoteHistoryView(s)).toBe(view);
+ expect(view.isActive()).toBe(true);
+ expect(view.getSnapshot().expanded.has(group.key)).toBe(true);
+ expect(view.getSnapshot().details.get(group.key)?.messages[0].content).toBe('expanded history');
+ expect(visible().messages.find((row) => row.clientId === 'client-answer')?.content).toBe(expected);
+ expect(visible().pending.has('client-answer')).toBe(stillLive);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(readsBeforeRecovery + 1);
+ expect(host.invoke).not.toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
+ makerChatStore.purgeSession(s);
+ },
+ );
+
it.each([false, true])('registers a fresh history page after ACK; reset during wait=%s', async (reset) => {
const s = sid();
host.enableHistoryView();
@@ -843,6 +1129,128 @@ describe('device-link controller mirror — end-to-end scenarios', () => {
view.setActive(false);
});
+ it('force reconciliation hydrates a terminal row from a collapsed work range', async () => {
+ const s = sid();
+ host.enableHistoryView();
+ const history = [dbMessage(s, 'u', 'question', '2026-06-15T00:00:00.000Z', 'user'),
+ { ...dbMessage(s, 'thought', '', '2026-06-15T00:00:01.000Z', 'thinking'), content: { kind: 'thinking', text: 'terminal body', durationMs: 500, isRedacted: false } },
+ dbMessage(s, 'answer', 'answer', '2026-06-15T00:00:02.000Z')];
+ host.seedSession(s, {}, history);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ await flush();
+ const view = getRemoteHistoryView(s)!;
+ const group = view.getSnapshot().items.find((item) => item.type === 'work')!;
+ expect(view.getSnapshot().expanded.has(group.key)).toBe(false);
+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.clientId)).toEqual([
+ 'client-u', 'client-answer',
+ ]);
+
+ await makerChatStore.reconcileRemoteMessages(s, { force: true });
+
+ expect(makerChatStore.getSnapshot(s).messages.map((row) => row.clientId)).toEqual([
+ 'client-u', 'client-thought', 'client-answer',
+ ]);
+ expect(view.getSnapshot().expanded.has(group.key)).toBe(false);
+ view.setActive(false);
+ });
+
+ it('coalesces concurrent force reconciliation while HistoryView reads its page', async () => {
+ const s = sid();
+ host.enableHistoryView();
+ host.seedSession(s, {}, [dbMessage(s, 'answer', 'answer', '2026-06-15T00:00:00.000Z')]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ await flush();
+
+ const original = host.invoke.getMockImplementation()!;
+ let releaseFirstPage!: () => void;
+ let pageCalls = 0;
+ let activePages = 0;
+ let maxActivePages = 0;
+ host.invoke.mockImplementation(async (device, channel, args) => {
+ if (channel !== 'local-db:messages:view') return original(device, channel, args);
+ pageCalls += 1;
+ activePages += 1;
+ maxActivePages = Math.max(maxActivePages, activePages);
+ try {
+ const result = await original(device, channel, args);
+ if (pageCalls === 1) await new Promise<void>((done) => { releaseFirstPage = done; });
+ return result;
+ } finally {
+ activePages -= 1;
+ }
+ });
+
+ const first = makerChatStore.reconcileRemoteMessages(s, { force: true });
+ await flush();
+ const second = makerChatStore.reconcileRemoteMessages(s, { force: true });
+ expect(second).toBe(first);
+ releaseFirstPage();
+ await first;
+ await flush();
+
+ // The duplicate force is coalesced into one in-flight read. A trailing
+ // refresh is allowed after it settles so a view replacement during the
+ // first read cannot leave the session on a stale snapshot.
+ expect(pageCalls).toBe(2);
+ expect(maxActivePages).toBe(1);
+ getRemoteHistoryView(s)?.setActive(false);
+ });
+
+ it.each([
+ ['view', 'none'], ['view', 'first'], ['view', 'second'],
+ ['raw-fallback', 'none'], ['raw-fallback', 'first'], ['raw-fallback', 'second'],
+ ] as const)('refreshes its own force hydration while protecting live updates (%s, live=%s)', async (path, live) => {
+ const s = sid();
+ host.enableHistoryView(path === 'raw-fallback');
+ const user = dbMessage(s, 'question', 'question', '2026-09-08T00:00:00Z', 'user');
+ const thought = { ...dbMessage(s, 'thought', '', '2026-09-08T00:00:01Z', 'thinking'),
+ content: { kind: 'thinking', text: 'sealed thought', durationMs: 2000, finishedAt: Date.parse('2026-09-08T00:00:03Z') } };
+ host.seedSession(s, {}, [user]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(); await flush();
+ const pushLive = (text: string) => host.push('maker:session-sync', { sessionId: s, persistId: 'client-answer',
+ event: { type: 'text', data: { text, isFullText: true, isFinal: false } } });
+ pushLive('initial live prefix');
+ const answer = (text: string) => dbMessage(s, 'answer', text, '2026-09-08T00:00:04Z');
+ host.seedSession(s, {}, [user, thought, answer('first persisted answer')]);
+ const original = host.invoke.getMockImplementation()!;
+ const releases: (() => void)[] = [];
+ const channelToHold = path === 'view' ? 'local-db:messages:view' : 'local-db:messages:list';
+ host.invoke.mockImplementation(async (...args) => {
+ if (path === 'raw-fallback' && args[1] === 'local-db:messages:work-details') throw new Error('details unavailable');
+ const value = await original(...args);
+ if (args[1] === channelToHold) await new Promise<void>(resolve => { releases.push(resolve); });
+ return value;
+ });
+ const first = makerChatStore.reconcileRemoteMessages(s, { force: true });
+ await vi.waitFor(() => expect(releases).toHaveLength(1));
+ const second = makerChatStore.reconcileRemoteMessages(s, { force: true });
+ expect(second).toBe(first);
+ if (live === 'first') pushLive('live during first read');
+ host.seedSession(s, {}, [user, thought, answer('latest persisted answer')]);
+ releases[0]();
+ await vi.waitFor(() => expect(releases).toHaveLength(2));
+ const current = () => makerChatStore.getSnapshot(s).messages.find(row => row.clientId === 'client-answer');
+ expect(current()?.content).toBe(live === 'first' ? 'live during first read' : 'first persisted answer');
+ if (live === 'second') host.push('local-db:messages:created', { sessionId: s, message: answer('live during second read') });
+ releases[1]();
+ await first;
+ expect(current()).toMatchObject({
+ content: live === 'none' ? 'latest persisted answer' : `live during ${live} read`,
+ isStreaming: live === 'first',
+ });
+ expect(releases).toHaveLength(2);
+ makerChatStore.purgeSession(s);
+ });
+
it('完整镜像回路:开会话见历史 → live push 追加 → 丢帧 reconcile heal → 设置变更镜像', async () => {
const s = sid();
// 被控端已有 1 条历史 + 注册到远程项目(getSessionDeviceId 命中 → 传输层走隧道)。
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 742a0e167d..8ce88be9be 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -1768,6 +1768,119 @@ describe('makerChatStore text delta batching', () => {
]);
});
+ it('replaces an in-flight prefix but preserves a durable item against a non-final snapshot', () => {
+ emitTextDelta('prefix', SESSION_ID, 'assistant-1');
+ vi.advanceTimersByTime(32);
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'text', source: 'codex',
+ data: { text: 'complete snapshot', isFinal: false, isFullText: true },
+ },
+ persistId: 'assistant-1',
+ });
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([
+ expect.objectContaining({ clientId: 'assistant-1', content: 'complete snapshot', isStreaming: true }),
+ ]);
+
+ onDbMessageCreated?.({
+ sessionId: SESSION_ID,
+ message: { clientId: 'assistant-2', role: 'assistant', content: 'durable text', createdAt: new Date().toISOString() },
+ });
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'text', source: 'codex',
+ data: { text: 'late streaming snapshot', isFinal: false, isFullText: true },
+ },
+ persistId: 'assistant-2',
+ });
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual(expect.arrayContaining([
+ expect.objectContaining({ clientId: 'assistant-2', content: 'durable text', isStreaming: false }),
+ ]));
+ });
+
+ it('merges current stream metadata from a remote full-text snapshot and preserves it when absent', () => {
+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);
+ const pushText = (channel: string, text: string, agentMeta?: Record<string, unknown>) => {
+ onRemotePush?.({
+ deviceId: 'device-1', channel,
+ payload: {
+ sessionId: SESSION_ID, persistId: 'assistant-1',
+ event: {
+ type: 'text', source: 'codex', agentMeta,
+ data: { text, isFinal: false, isFullText: channel === 'maker:session-sync' },
+ },
+ },
+ });
+ };
+ pushText('maker:event', 'prefix');
+ vi.advanceTimersByTime(32);
+ // Leave a delta queued so the snapshot also exercises the batching boundary.
+ pushText('maker:event', ' queued');
+ pushText('maker:session-sync', 'complete snapshot', { model: 'old-model', botPrivateReply: true });
+ const agentMeta = {
+ model: 'updated-model', parentUuid: 'parent-tool', turnCompleted: true, botPrivateReply: false,
+ };
+ // Metadata can change even when the authoritative text is identical.
+ pushText('maker:session-sync', 'complete snapshot', agentMeta);
+ expect(makerChatStore.getSnapshot(SESSION_ID)).toMatchObject({
+ streamingClientId: 'assistant-1', streamingText: 'complete snapshot', lastAgentMeta: agentMeta,
+ messages: [expect.objectContaining({
+ clientId: 'assistant-1', content: 'complete snapshot', isStreaming: true,
+ model: 'updated-model', parentToolUseId: 'parent-tool', turnCompleted: true, botPrivateReply: false,
+ })],
+ });
+
+ pushText('maker:session-sync', 'complete snapshot without metadata');
+ pushText('maker:event', ' tail');
+ vi.advanceTimersByTime(32);
+ expect(makerChatStore.getSnapshot(SESSION_ID)).toMatchObject({
+ streamingText: 'complete snapshot without metadata tail', lastAgentMeta: agentMeta,
+ messages: [expect.objectContaining({
+ content: 'complete snapshot without metadata tail', model: 'updated-model',
+ parentToolUseId: 'parent-tool', turnCompleted: true, botPrivateReply: false,
+ })],
+ });
+ });
+
+ it('preserves durable text and newer stream metadata when an older snapshot arrives', () => {
+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);
+ const pushText = (persistId: string, text: string, agentMeta: Record<string, unknown>, isFinal: boolean) => {
+ onRemotePush?.({
+ deviceId: 'device-1', channel: isFinal ? 'maker:event' : 'maker:session-sync',
+ payload: {
+ sessionId: SESSION_ID, persistId,
+ event: {
+ type: 'text', source: 'codex', agentMeta,
+ data: { text, isFinal, isFullText: true },
+ },
+ },
+ });
+ };
+ pushText('assistant-1', 'old answer', { model: 'old-model' }, true);
+ const currentMeta = { model: 'current-model', parentUuid: 'current-parent', botPrivateReply: false };
+ pushText('assistant-2', 'new answer', currentMeta, false);
+ pushText('assistant-2', 'new answer complete', currentMeta, false);
+ pushText('assistant-1', 'repaired old answer', {
+ model: 'repaired-model', parentUuid: 'old-parent', turnCompleted: true, botPrivateReply: true,
+ }, false);
+
+ expect(makerChatStore.getSnapshot(SESSION_ID)).toMatchObject({
+ streamingClientId: 'assistant-2', streamingText: 'new answer complete', lastAgentMeta: currentMeta,
+ messages: [
+ expect.objectContaining({
+ clientId: 'assistant-1', content: 'old answer', isStreaming: false,
+ model: 'old-model',
+ }),
+ expect.objectContaining({
+ clientId: 'assistant-2', content: 'new answer complete', isStreaming: true,
+ model: 'current-model', parentToolUseId: 'current-parent', botPrivateReply: false,
+ }),
+ ],
+ });
+ });
+
it('does not reset or duplicate thinking on a repeated start, including after its DB echo', () => {
const start = {
sessionId: SESSION_ID,
diff --git a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
index 6559a4010d..afc1617170 100644
--- a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
+++ b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
@@ -507,12 +507,24 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
expect(makerChatStore.getLastInboundEventAt(s)).toEqual(expect.any(Number));
});
- it('远程会话:对账找不到重叠时替换为权威最新窗口,避免跨断层合并', async () => {
+ it.each(['idle', 'force', 'session-sync'] as const)('远程会话:对账找不到重叠时替换为权威最新窗口,避免跨断层合并 (%s)', async (recovery) => {
const s = sid();
+ makerChatStore.initGlobalListeners();
await openRemoteWithHistory(s, [
dbMessage(s, 'old-cache', 'old cached text', '2026-06-15T00:00:00.000Z'),
dbMessage(s, 'cached-future', 'controller clock ahead text', '2026-06-16T00:00:00.000Z'),
]);
+ if (recovery !== 'idle') {
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s,
+ event: { type: 'status', source: 'claude-code', data: { status: 'thinking', isRunning: true } },
+ },
+ });
+ expect(makerChatStore.getSnapshot(s).isStreaming).toBe(true);
+ }
markSessionAutomaticHistoryLoadCompleted(s);
const completionAttemptsAtRebuildNotification: number[] = [];
const unsubscribe = makerChatStore.subscribe(s, () => {
@@ -533,11 +545,23 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
);
remoteListResolver = (args) => pageMessages(remoteHistory, args);
- makerChatStore.reconcileRemoteMessages(s);
+ invoke.mockClear();
+ if (recovery === 'session-sync') {
+ // A legacy Host has no HistoryView or in-flight text snapshot. This
+ // ingress combines force + repair while the controller is still streaming.
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:session-sync',
+ payload: { sessionId: s, resyncRequired: true },
+ });
+ } else {
+ await makerChatStore.reconcileRemoteMessages(s, { force: recovery === 'force' });
+ }
await flushMany(REMOTE_RECONCILE_FLUSH_TICKS);
unsubscribe();
const snapshot = makerChatStore.getSnapshot(s);
+ expect(invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list')).toHaveLength(10);
expect(snapshot.messages).toHaveLength(500);
expect(snapshot.messages.map((m) => m.clientId)).not.toContain('client-old-cache');
expect(snapshot.messages.map((m) => m.clientId)).not.toContain('client-cached-future');
@@ -545,6 +569,7 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
expect(snapshot.messages.at(-1)?.clientId).toBe('client-new-549');
expect(snapshot.oldestMessageId).toBe('new-50');
expect(snapshot.hasMoreMessages).toBe(true);
+ expect(snapshot.historyWindowIslands).toHaveLength(0);
expect(restoreSessionAutomaticHistoryLoadAttempts(s, 5)).toBe(0);
expect(completionAttemptsAtRebuildNotification).toContain(0);
});
@@ -1485,6 +1510,244 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
expect(makerChatStore.getSnapshot(s).isLoadingMore).toBe(false);
});
+ it('远程会话:streaming 期间的修复对账只追加缺失持久化消息', async () => {
+ const s = sid();
+ makerChatStore.initGlobalListeners();
+ await openRemoteWithHistory(s, [dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z')]);
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s,
+ event: {
+ type: 'status',
+ source: 'claude-code',
+ data: { status: 'thinking', isRunning: true, tokenUsage: 0, contextTokens: 0, contextWindow: 0 },
+ },
+ },
+ });
+ expect(makerChatStore.getSnapshot(s).isStreaming).toBe(true);
+
+ remoteList = [
+ dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z'),
+ dbMessage(s, 'repaired', 'message whose push was lost', '2026-06-15T00:00:02.000Z'),
+ ];
+ await makerChatStore.reconcileRemoteMessages(s, { repair: true });
+
+ expect(makerChatStore.getSnapshot(s).messages.map((m) => m.clientId)).toEqual([
+ 'client-seed',
+ 'client-repaired',
+ ]);
+ expect(makerChatStore.getSnapshot(s).isStreaming).toBe(true);
+ });
+
+ it.each(['direct', 'queued', 'queued-sealed'])('远程会话:session-sync 修复旧行且只保护当前快照 (%s)', async (mode) => {
+ const queued = mode !== 'direct';
+ const s = sid();
+ makerChatStore.initGlobalListeners();
+ await openRemoteWithHistory(s, [dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z')]);
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s,
+ event: {
+ type: 'status',
+ source: 'claude-code',
+ data: { status: 'thinking', isRunning: true, tokenUsage: 0, contextTokens: 0, contextWindow: 0 },
+ },
+ },
+ });
+
+ remotePush?.({
+ deviceId: DEVICE_ID, channel: 'maker:event', payload: { sessionId: s, event: {
+ type: 'thinking', data: { stage: 'start', blockId: 'client-previous-thought', startedAt: 1781481601000 },
+ } },
+ });
+ remotePush?.({
+ deviceId: DEVICE_ID, channel: 'maker:event', payload: { sessionId: s, event: {
+ type: 'thinking', data: { stage: 'delta', blockId: 'client-previous-thought', text: 'stale thought' },
+ } },
+ });
+ expect(makerChatStore.getSnapshot(s).messages.find(m => m.clientId === 'client-previous-thought'))
+ .toMatchObject({ content: 'stale thought', isStreaming: true });
+
+ remoteList = [
+ dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z'),
+ { ...dbMessage(s, 'previous-thought', '', '2026-06-15T00:00:01.000Z', 'thinking'),
+ content: { kind: 'thinking', text: 'sealed thought', durationMs: 500 } },
+ dbMessage(s, 'recovered-assistant', 'assistant row recovered from the host', '2026-06-15T00:00:02.000Z'),
+ { ...dbMessage(s, 'in-flight-assistant', 'older persisted text', '2026-06-15T00:00:03.000Z'), clientId: 'in-flight-assistant' },
+ ];
+
+ const firstRead = deferred<Message[]>();
+ let pending: Promise<boolean> | undefined;
+ if (queued) {
+ remoteListResolver = () => firstRead.promise;
+ pending = makerChatStore.reconcileRemoteMessages(s, { repair: true });
+ await flush();
+ }
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:session-sync',
+ payload: {
+ sessionId: s,
+ persistId: 'in-flight-assistant',
+ event: {
+ type: 'text',
+ data: { text: 'current in-flight text', isFinal: false, isFullText: true },
+ },
+ resyncRequired: true,
+ },
+ });
+ if (mode === 'queued-sealed') {
+ remoteList = remoteList.map(row => row.clientId === 'in-flight-assistant'
+ ? { ...row, content: 'sealed current text' } : row);
+ remotePush?.({ deviceId: DEVICE_ID, channel: 'maker:session-sync', payload: { sessionId: s, resyncRequired: true } });
+ }
+ if (queued) {
+ remoteListResolver = null;
+ firstRead.resolve(remoteList);
+ await pending;
+ }
+ await flushMany(REMOTE_RECONCILE_FLUSH_TICKS);
+
+ expect(makerChatStore.getSnapshot(s).messages.map((m) => m.clientId)).toContain(
+ 'client-recovered-assistant',
+ );
+ expect(makerChatStore.getSnapshot(s).messages.find((m) => m.clientId === 'in-flight-assistant'))
+ .toMatchObject(mode === 'queued-sealed'
+ ? { content: 'sealed current text', isStreaming: false }
+ : { content: 'current in-flight text', isStreaming: true });
+ expect(makerChatStore.getSnapshot(s).messages.find(m => m.clientId === 'client-previous-thought'))
+ .toMatchObject({ content: 'sealed thought', isStreaming: false, thinkingDurationMs: 500 });
+ });
+
+ it('远程会话:resyncRequired 强制对账可替换 streaming 中已封存消息的旧正文', async () => {
+ const s = sid();
+ makerChatStore.initGlobalListeners();
+ await openRemoteWithHistory(s, [dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z')]);
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s,
+ event: {
+ type: 'status', source: 'claude-code',
+ data: { status: 'thinking', isRunning: true, tokenUsage: 0, contextTokens: 0, contextWindow: 0 },
+ },
+ },
+ });
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s,
+ persistId: 'streaming-assistant',
+ event: {
+ type: 'text', source: 'claude-code',
+ data: { text: 'stale streaming text', isFinal: false },
+ },
+ },
+ });
+ expect(makerChatStore.getSnapshot(s).isStreaming).toBe(true);
+
+ remoteList = [
+ dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z'),
+ dbMessage(s, 'streaming-assistant', 'authoritative sealed text', '2026-06-15T00:00:02.000Z'),
+ ];
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:session-sync',
+ payload: { sessionId: s, resyncRequired: true },
+ });
+ await flushMany(REMOTE_RECONCILE_FLUSH_TICKS);
+
+ expect(makerChatStore.getSnapshot(s).messages).toEqual([
+ expect.objectContaining({
+ clientId: 'client-seed', content: 'seed row', isStreaming: false,
+ }),
+ expect.objectContaining({
+ clientId: 'client-streaming-assistant', content: 'authoritative sealed text', isStreaming: false,
+ }),
+ ]);
+ });
+
+ it('远程会话:单飞期间 force 触发会压过先到的 repair', async () => {
+ const s = sid();
+ makerChatStore.initGlobalListeners();
+ await openRemoteWithHistory(s, [dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z')]);
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s,
+ event: { type: 'status', source: 'claude-code', data: { status: 'thinking', isRunning: true, tokenUsage: 0, contextTokens: 0, contextWindow: 0 } },
+ },
+ });
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s, persistId: 'sealed-assistant',
+ event: { type: 'text', source: 'claude-code', data: { text: 'stale', isFinal: false } },
+ },
+ });
+ const firstRead = deferred<Message[]>();
+ remoteListResolver = () => firstRead.promise;
+ const repair = makerChatStore.reconcileRemoteMessages(s, { repair: true });
+ await flush();
+ remoteListResolver = null;
+ remoteList = [
+ dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z'),
+ dbMessage(s, 'sealed-assistant', 'sealed authoritative text', '2026-06-15T00:00:02.000Z'),
+ ];
+ const forced = makerChatStore.reconcileRemoteMessages(s, { force: true });
+ firstRead.resolve(remoteList);
+ await repair;
+ await forced;
+ await flushMany(REMOTE_RECONCILE_FLUSH_TICKS);
+ expect(makerChatStore.getSnapshot(s).messages).toEqual(expect.arrayContaining([
+ expect.objectContaining({ clientId: 'client-sealed-assistant', content: 'sealed authoritative text', isStreaming: false }),
+ ]));
+ });
+
+ it('远程会话:普通 streaming text delta 不周期性触发历史修复', async () => {
+ vi.useFakeTimers();
+ try {
+ const s = sid();
+ makerChatStore.initGlobalListeners();
+ await openRemoteWithHistory(s, [dbMessage(s, 'seed', 'seed row', '2026-06-15T00:00:00.000Z')]);
+ invoke.mockClear();
+
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s,
+ persistId: 'streaming-assistant',
+ event: {
+ type: 'text', source: 'claude-code',
+ data: { text: 'delta', isFinal: false },
+ },
+ },
+ });
+ await flush();
+ await vi.advanceTimersByTimeAsync(1_600);
+ expect(invoke).not.toHaveBeenCalledWith(
+ DEVICE_ID,
+ 'local-db:messages:list',
+ expect.anything(),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('远程会话:权威重建没保留任何晚到的行时,孤岛标记清零', async () => {
// review #676(codex P1):这种情况下新窗口**完全**由本次从最新连续翻回来的页组成,按构造
// 没有孤岛。留着标记的代价不是"多做一次补齐":标记只由整窗重建清零,而窗口内的目标比重建
@@ -1510,15 +1773,27 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
expect(makerChatStore.getSnapshot(s).historyWindowIslands.length).toBe(0);
});
- it('远程会话:权威重建作废在飞行中的跳转补齐,并释放分页锁', async () => {
+ it.each([false, true])('远程会话:权威重建作废在飞行中的跳转补齐,并释放分页锁 (force=%s)', async (force) => {
// review #676(codex P1):无重叠分支换掉整片窗口 + 改写 oldestMessageId,却不 bump
// 代际。此时一个在飞行中的搜索跳转补齐会带着**重建前**的游标返回,把脱离上下文的旧
// 历史接到新窗口上;若那一页里有跳转目标,补齐还会判 covered、连孤岛标记都不留,
// 退化成本 PR 要修的静默空洞。
const s = sid();
+ makerChatStore.initGlobalListeners();
await openRemoteWithHistory(s, [
dbMessage(s, 'stale-tail', 'stale cached tail', '2026-06-15T00:00:00.000Z'),
]);
+ if (force) {
+ remotePush?.({
+ deviceId: DEVICE_ID,
+ channel: 'maker:event',
+ payload: {
+ sessionId: s,
+ event: { type: 'status', source: 'claude-code', data: { status: 'thinking', isRunning: true } },
+ },
+ });
+ expect(makerChatStore.getSnapshot(s).isStreaming).toBe(true);
+ }
const target = dbMessage(s, 'jump-target', 'jump target', '2026-06-10T00:00:00.000Z');
// 跳转补齐用 limit=100 翻页(JUMP_BACKFILL_PAGE_SIZE),对账用 limit=50 —— 按 limit
@@ -1537,7 +1812,7 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
expect(makerChatStore.getSnapshot(s).isLoadingMore).toBe(true);
// 对账落地:与已有窗口没有重叠 → 权威重建。
- makerChatStore.reconcileRemoteMessages(s);
+ await makerChatStore.reconcileRemoteMessages(s, { force });
await flushMany(REMOTE_RECONCILE_FLUSH_TICKS);
expect(makerChatStore.getSnapshot(s).messages.map((m) => m.clientId)).toEqual(['client-auth-1']);
// 锁归本次重置释放:被作废的补齐不会代清。
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 30963ce004..41ffd74180 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -22,7 +22,7 @@ import { readBotAuthorizationCard } from '../../shared/botAuthorization';
* - User-initiated stopSession (NOT called on session switch anymore)
*/
-import { HistoryViewController, isHistoryViewUnavailable, mapHistoryViewMessages, historyViewLeaves, type HistoryViewPage, type HistoryDetailPage } from '@cindy/maker-shared/message-window';
+import { HistoryViewController, isHistoryViewUnavailable, mapHistoryViewMessages, historyViewLeaves, historyWorkSummaries, type HistoryViewPage, type HistoryDetailPage } from '@cindy/maker-shared/message-window';
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
import { SESSION_SYNC_CHANNEL } from '@cindy/device-link';
import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from '@cindy/maker-shared/message-window';
@@ -3923,7 +3923,7 @@ function enterView(sessionId: string): () => void {
if (resumingHistory) {
// A repair push may have arrived after leaveView, when refresh is inactive.
// Reuse the normal resume read to hand off unchanged streaming rows too.
- void reconcileRemoteMessages(sessionId, { repair: true }).then(() => {
+ void reconcileRemoteMessages(sessionId, { force: true, repair: true, freshHistory: false }).then(() => {
if (!view.getSnapshot().error) scheduleIdlePlanDiscoveryIfNeeded(sessionId);
}).catch(() => undefined);
} else scheduleIdlePlanDiscoveryIfNeeded(sessionId);
@@ -5301,6 +5301,30 @@ export function handleStreamEvent(
if (snapshot && event.persistId && state.messages.some((message) =>
message.clientId === event.persistId && message.role === 'assistant' && !message.isStreaming)) return state;
+ // A full-text snapshot can be non-final while the item is still streaming.
+ // It is authoritative for the current block and must replace the delta
+ // prefix rather than being appended as another delta.
+ if (
+ !isFinal &&
+ isFullText === true &&
+ event.persistId &&
+ event.persistId === state.streamingClientId &&
+ typeof text === 'string'
+ ) {
+ const id = state.streamingClientId;
+ return {
+ ...state,
+ streamingText: text,
+ lastAgentMeta: incomingMeta ?? state.lastAgentMeta,
+ messages: replaceMessage(
+ state.messages,
+ (message) => message.clientId === id,
+ (message) => ({ ...message, content: text, ...assistantMetaFields,
+ ...(snapshot?.createdAt ? { createdAt: snapshot.createdAt } : {}) }),
+ ),
+ };
+ }
+
// A DB/history snapshot can beat the first batched delta, or an old item's
// final event can arrive after a newer item starts. Identity, not tail
// position/content equality, decides whether this is a new bubble.
@@ -5311,7 +5335,28 @@ export function handleStreamEvent(
if (existing) {
// Persisted/finalized text already includes these late deltas. Only an
// explicitly authoritative full-text event may calibrate it again.
- if (!isFinal) return state;
+ if (!isFinal) {
+ if (isFullText !== true || typeof text !== 'string') return state;
+ const updated = {
+ ...existing,
+ content: text,
+ ...assistantMetaFields,
+ };
+ const isCurrentStream = state.streamingClientId === event.persistId;
+ const lastAgentMeta = state.streamingClientId
+ ? state.lastAgentMeta
+ : incomingMeta ?? state.lastAgentMeta;
+ const unchanged = shallowEqualChatMessage(existing, updated);
+ if (unchanged && !isCurrentStream && lastAgentMeta === state.lastAgentMeta) return state;
+ return {
+ ...state,
+ ...(isCurrentStream ? { streamingText: text } : {}),
+ lastAgentMeta,
+ messages: unchanged
+ ? state.messages
+ : replaceMessage(state.messages, (message) => message === existing, () => updated),
+ };
+ }
const updated = {
...existing,
...(isFullText === true && text ? { content: text } : {}),
@@ -6963,6 +7008,24 @@ const WAKE_BRIDGE_RECONCILE_MIN_AGE_MS = 10_000;
const backgroundTaskReconcileTimers = new Map<string, ReturnType<typeof setTimeout>>();
const backgroundTaskReconcileEpoch = new Map<string, number>();
+// A remote `messages:created` push can be lost while the controlled session
+// keeps streaming. Keep a small, per-session repair debounce so any later
+// remote event can heal the missing durable row without turning the live
+// stream into a polling loop.
+const REMOTE_MESSAGE_REPAIR_DELAY_MS = 1_500;
+const remoteMessageRepairTimers = new Map<string, ReturnType<typeof setTimeout>>();
+
+function scheduleRemoteMessageRepair(sessionId: string): void {
+ if (!sessionId || remoteMessageRepairTimers.has(sessionId)) return;
+ remoteMessageRepairTimers.set(
+ sessionId,
+ setTimeout(() => {
+ remoteMessageRepairTimers.delete(sessionId);
+ void reconcileRemoteMessages(sessionId, { repair: true }).catch(() => undefined);
+ }, REMOTE_MESSAGE_REPAIR_DELAY_MS),
+ );
+}
+
function invalidateBackgroundTaskReconcile(sessionId: string): number {
const next = (backgroundTaskReconcileEpoch.get(sessionId) ?? 0) + 1;
backgroundTaskReconcileEpoch.set(sessionId, next);
@@ -8469,20 +8532,48 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
// 可能仍在持续抵达,但 maker:event 重 topic 已经断流;若这里也刷新会掩盖卡死。
if (push.channel === SESSION_SYNC_CHANNEL
&& (!inboundSid || remoteProjectsStore.getSessionDeviceId(inboundSid) !== push.deviceId)) return;
+ const inboundHasPersistId =
+ typeof (push.payload as { persistId?: unknown } | null)?.persistId === 'string';
+ const isDurableMessagePush =
+ push.channel === 'local-db:messages:created' ||
+ (push.channel === 'maker:event' && inboundHasPersistId);
+ const inboundEvent = (push.payload as { event?: unknown } | null)?.event as
+ | { type?: unknown; data?: { isFinal?: unknown; isFullText?: unknown } }
+ | null
+ | undefined;
+ const isOrdinaryStreamingTextDelta =
+ push.channel === 'maker:event' &&
+ inboundEvent?.type === 'text' &&
+ inboundEvent.data?.isFinal === false &&
+ inboundEvent.data?.isFullText !== true;
+ if (push.deviceId && inboundSid && isDurableMessagePush && !isOrdinaryStreamingTextDelta) {
+ scheduleRemoteMessageRepair(inboundSid);
+ }
if (inboundSid && isRemoteHeavyInboundChannel(push.channel)) _markInboundEvent(inboundSid);
if (inboundSid) {
const view = getRemoteHistoryView(inboundSid);
if (view && ['maker:history-view-changed', 'local-db:messages:created', 'maker:status-changed'].includes(push.channel)) view.invalidate();
}
switch (push.channel) {
- case SESSION_SYNC_CHANNEL:
+ case SESSION_SYNC_CHANNEL: {
+ let preserveClientIds: ReadonlySet<string> | undefined;
consumeRemoteSessionSync(push.payload, {
- applyEvent: (event) => handleMakerEventRaw(event, remoteIngress),
+ applyEvent: (event) => {
+ handleMakerEventRaw(event, remoteIngress);
+ const row = sessions.get(event.sessionId as string)?.messages.find(
+ (message) => message.clientId === event.persistId && message.isStreaming,
+ );
+ if (row) preserveClientIds = new Set([row.clientId]);
+ },
invalidateHistory: (sessionId) => {
const state = sessions.get(sessionId);
if (!state) return;
if (getRemoteHistoryView(sessionId)) {
- void reconcileRemoteMessages(sessionId, { repair: true, freshHistory: true });
+ // resyncRequired also repairs unrelated durable rows; a full
+ // text snapshot only protects its own live block.
+ void reconcileRemoteMessages(sessionId, {
+ force: true, repair: true, freshHistory: true, preserveClientIds,
+ });
return;
}
if (!state.historyLoaded) {
@@ -8492,10 +8583,13 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
ensureInitialMessages(sessionId);
return;
}
- void reconcileRemoteMessages(sessionId, { repair: true });
+ void reconcileRemoteMessages(sessionId, {
+ force: true, repair: true, preserveClientIds,
+ });
},
});
break;
+ }
case 'maker:event':
handleMakerEventRaw(push.payload, remoteIngress);
break;
@@ -9080,6 +9174,8 @@ function __teardownGlobalListeners(): void {
pendingTextDeltaBatches.clear();
for (const timer of backgroundTaskReconcileTimers.values()) clearTimeout(timer);
backgroundTaskReconcileTimers.clear();
+ for (const timer of remoteMessageRepairTimers.values()) clearTimeout(timer);
+ remoteMessageRepairTimers.clear();
clearDeferredStateNotificationTimer();
pendingDeferredStateNotifications.clear();
pendingMessageCreatedPatches.clear();
@@ -11602,51 +11698,177 @@ function reconcileOpenSessionOrigins(): void {
*/
const _remoteReconcileInFlight = new Map<
string,
- { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean }
+ { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean; preserveClientIds: Set<string> }
>();
-function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean; freshHistory?: boolean; repair?: boolean }): Promise<boolean> {
+type HistoryViewForceFlight = {
+ run: Promise<boolean>;
+ rerun: boolean;
+ rowsAtStart: Map<string, ChatMessage>;
+ latestOpts: {
+ force?: boolean;
+ repair?: boolean;
+ freshHistory?: boolean;
+ preserveClientIds?: ReadonlySet<string>;
+ };
+};
+
+const _historyViewForceInFlight = new Map<string, HistoryViewForceFlight>();
+
+function reconcileRemoteMessages(sessionId: string, opts?: {
+ force?: boolean;
+ repair?: boolean;
+ freshHistory?: boolean;
+ preserveClientIds?: ReadonlySet<string>;
+}): Promise<boolean> {
const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
if (deviceId && isRemoteDeviceMarkedDisconnected(deviceId)) return Promise.resolve(false);
const view = getRemoteHistoryView(sessionId);
- const repairRows = opts?.repair && view
- ? new Map(sessions.get(sessionId)?.messages.map((row) => [row.clientId, row])) : undefined;
- if (view && (view.getSnapshot().ready || opts?.freshHistory || opts?.repair)) return Promise.all([view.refresh(false, opts?.freshHistory), reconcilePendingInteractions(sessionId)]).then(() => {
- if (getRemoteHistoryView(sessionId) !== view || !view.isActive()) return false;
- if (isHistoryViewUnavailable(view.getSnapshot().error)) {
- releaseRemoteHistoryView(sessionId, view);
- return reconcileRemoteMessages(sessionId, { force: true });
- }
- if (view.getSnapshot().error) throw view.getSnapshot().error;
- if (repairRows && view.getSnapshot().ready) {
- const snapshot = view.getSnapshot();
- const available = historyViewLeaves(snapshot.items).flatMap((item) => item.type === 'messages' ? item.messages : []);
- // The projection's add-only subscription preserves live rows. Complete
- // this repair only for unchanged assistant streams. Cached work details
- // refresh separately and cannot prove that their contents are current.
- setState(sessionId, (state) => ({ ...state, messages: mergeMessages(available, state.messages, {
- addOnly: true,
- addOnlyExcept: new Set(state.messages.filter((row) => row.role === 'assistant'
- && row.isStreaming === true && repairRows.get(row.clientId) === row).map((row) => row.clientId)),
- }) }));
+ if (view && (view.getSnapshot().ready || opts?.freshHistory || opts?.repair)) {
+ const runHistoryView = (flight?: HistoryViewForceFlight) => {
+ const rowsAtStart = new Map((sessions.get(sessionId)?.messages ?? []).map((row) => [row.clientId, row]));
+ const epochAtStart = _messagesEpoch.get(sessionId) ?? 0;
+ const noteHydration = (before: readonly ChatMessage[], after: readonly ChatMessage[]) => {
+ if (!flight) return;
+ const previous = new Map(before.map((row) => [row.clientId, row]));
+ for (const row of after) {
+ // Advance only our own writes. A row changed by live ingress must
+ // keep its old baseline so the trailing read still protects it.
+ if (flight.rowsAtStart.get(row.clientId) === previous.get(row.clientId)) {
+ flight.rowsAtStart.set(row.clientId, row);
+ }
+ }
+ };
+ // Force needs a post-signal page, even when a normal repair is in flight.
+ // Keep this view and its expansion state instead of falling back to raw history.
+ return Promise.all([
+ view.refresh(false, opts?.freshHistory ?? opts?.force),
+ reconcilePendingInteractions(sessionId),
+ ]).then(async () => {
+ if (getRemoteHistoryView(sessionId) !== view || !view.isActive()) return false;
+ if (isHistoryViewUnavailable(view.getSnapshot().error)) {
+ releaseRemoteHistoryView(sessionId, view);
+ return runRemoteReconcile(sessionId, { ...opts, force: true }, noteHydration);
+ }
+ if (opts?.force) {
+ // readPage starts expanded details without awaiting them. Join those
+ // same reads before hydrating; their cached display may still be old.
+ await Promise.all(historyWorkSummaries(view.getSnapshot().items)
+ .map((summary) => view.loadDetails(summary, { allowCollapsed: true })));
+ if (getRemoteHistoryView(sessionId) !== view || !view.isActive()
+ || (_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return false;
+ const detailsSnapshot = view.getSnapshot();
+ const incompleteDetails = historyWorkSummaries(detailsSnapshot.items).some((summary) => {
+ const detail = detailsSnapshot.details.get(summary.key);
+ return !detail?.complete || !!detail.error || detail.revision !== summary.revision;
+ });
+ if (incompleteDetails) {
+ // Collapse can cancel a joined detail read without rejecting it.
+ // Missing, partial, failed or stale details cannot certify recovery.
+ // Use the same authoritative fallback as a transient read failure;
+ // if that read also fails, preserve rejection.
+ return runRemoteReconcile(sessionId, opts, noteHydration);
+ }
+ }
+ if (getRemoteHistoryView(sessionId) !== view || !view.isActive()) return false;
+ const snapshot = view.getSnapshot();
+ if (snapshot.error) throw snapshot.error;
+ if ((_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return false;
+ if (opts?.force && snapshot.ready) {
+ // Host thinking snapshots use synthetic IDs and carry no terminal
+ // marker. Only durable rows may seal an existing live row; provisional
+ // rows already participate in the ordinary add-only subscription.
+ const details = historyWorkSummaries(snapshot.items).flatMap((summary) => {
+ const detail = snapshot.details.get(summary.key);
+ return detail?.complete
+ && !detail.error && detail.revision === summary.revision ? detail.messages : [];
+ });
+ const available = details.concat(historyViewLeaves(snapshot.items)
+ .flatMap((item) => item.type === 'messages' ? item.messages : []))
+ .filter((row) => !row.id.startsWith('history-live:')
+ && !opts?.preserveClientIds?.has(row.clientId));
+ setState(sessionId, (state) => {
+ // The ordinary view subscriber is add-only. Explicit recovery must
+ // hydrate stale live shells, or their handoff keeps masking sealed rows.
+ // Preserve rows changed by live events while this read was pending.
+ const untouched = new Set(state.messages.filter((row) => rowsAtStart.get(row.clientId) === row).map((row) => row.clientId));
+ const messages = mergeMessages(available, state.messages, { addOnly: true, addOnlyExcept: untouched });
+ noteHydration(state.messages, messages);
+ return messages === state.messages ? state : { ...state, messages };
+ });
+ }
+ return snapshot.ready;
+ });
+ };
+ if (!opts?.force) return runHistoryView();
+ const existing = _historyViewForceInFlight.get(sessionId);
+ if (existing) {
+ existing.rerun = true;
+ existing.latestOpts = opts;
+ return existing.run;
}
- return view.getSnapshot().ready;
- });
+ const entry: HistoryViewForceFlight = {
+ run: Promise.resolve(false),
+ rerun: false,
+ rowsAtStart: new Map((sessions.get(sessionId)?.messages ?? []).map((row) => [row.clientId, row])),
+ latestOpts: opts,
+ };
+ _historyViewForceInFlight.set(sessionId, entry);
+ entry.run = (async () => {
+ try {
+ let applied: boolean;
+ try {
+ applied = await runHistoryView(entry);
+ } catch (error) {
+ // Replacing the view while its page is in flight rejects the old
+ // controller read. A coalesced force signal still needs to retry on
+ // the replacement view; without a pending force, preserve the
+ // original error for callers that explicitly await this promise.
+ if (!entry.rerun || !sessions.has(sessionId)) throw error;
+ applied = false;
+ }
+ if (entry.rerun && sessions.has(sessionId)) {
+ _historyViewForceInFlight.delete(sessionId);
+ const preserveClientIds = new Set(entry.latestOpts.preserveClientIds);
+ for (const row of sessions.get(sessionId)?.messages ?? []) {
+ if (entry.rowsAtStart.has(row.clientId) && entry.rowsAtStart.get(row.clientId) !== row) {
+ preserveClientIds.add(row.clientId);
+ }
+ }
+ applied = await reconcileRemoteMessages(sessionId, {
+ ...entry.latestOpts,
+ preserveClientIds,
+ });
+ }
+ return applied;
+ } finally {
+ if (_historyViewForceInFlight.get(sessionId) === entry) _historyViewForceInFlight.delete(sessionId);
+ }
+ })();
+ void entry.run.catch(() => undefined);
+ return entry.run;
+ }
// 返回完成 promise 供调用方需要时等待;既有调用方均按 fire-and-forget 使用。
if (!sessionId || !isRemoteSession(sessionId)) return Promise.resolve(false);
const inFlight = _remoteReconcileInFlight.get(sessionId);
if (inFlight) {
inFlight.rerun = true;
- if (opts?.force) inFlight.rerunForce = true;
+ if (opts?.force) {
+ inFlight.rerunForce = true;
+ // The latest forced signal identifies the current live block. A later
+ // snapshot-less resync can authoritatively seal the previous block.
+ inFlight.preserveClientIds = new Set(opts.preserveClientIds);
+ }
if (opts?.repair) inFlight.rerunRepair = true;
void reconcilePendingInteractions(sessionId).catch(() => undefined);
return inFlight.run;
}
- const entry: { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean } = {
+ const entry: { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean; preserveClientIds: Set<string> } = {
run: Promise.resolve(false),
rerun: false,
rerunForce: false,
rerunRepair: false,
+ preserveClientIds: new Set(),
};
_remoteReconcileInFlight.set(sessionId, entry);
entry.run = (async () => {
@@ -11656,10 +11878,14 @@ function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean; fr
} finally {
const rerun = entry.rerun;
const rerunForce = entry.rerunForce;
+ const rerunRepair = entry.rerunRepair;
// 先摘掉在飞标记,再补跑 —— 补跑会自己建新的 entry,期间来的触发继续被那一份合并。
_remoteReconcileInFlight.delete(sessionId);
if (rerun && sessions.has(sessionId)) {
- applied = await reconcileRemoteMessages(sessionId, { force: rerunForce, repair: entry.rerunRepair });
+ applied = await reconcileRemoteMessages(
+ sessionId,
+ { force: rerunForce, repair: rerunRepair, preserveClientIds: entry.preserveClientIds },
+ );
}
}
return applied;
@@ -11672,7 +11898,11 @@ function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean; fr
return entry.run;
}
-function runRemoteReconcile(sessionId: string, opts?: { force?: boolean; repair?: boolean }): Promise<boolean> {
+function runRemoteReconcile(sessionId: string, opts?: {
+ force?: boolean;
+ repair?: boolean;
+ preserveClientIds?: ReadonlySet<string>;
+}, noteHydration?: (before: readonly ChatMessage[], after: readonly ChatMessage[]) => void): Promise<boolean> {
// 挂起交互面板重建**无条件先行**,不受下方 isStreaming 守卫约束:turn 内弹出的
// permission / ask / plan 正是 isStreaming=true 的常见态(pendingPermission 与
// isRunning 共存),断连重连 / 聚焦时若被守卫吞掉,交互面板不重建、用户无法回应,
@@ -11680,6 +11910,9 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean; repair?
// 未读的 passive 远程回执必须等提示真实重建后才放行。
const interactionsSync = reconcilePendingInteractions(sessionId);
const state = sessions.get(sessionId);
+ // A repair without force started while streaming is deliberately additive: it may insert
+ // durable rows whose push was lost, but it must never hydrate or replace the
+ // live row that the stream is still producing.
if (!state || !state.historyLoaded || (state.isStreaming && !opts?.force && !opts?.repair)) {
// 消息对账被守卫挡下,但交互重建照跑。为它单独开一代:turn 进行中的
// needs-interaction 未读,其「内容」就是权限 / ask / plan 提示本身——提示真实
@@ -11771,7 +12004,9 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean; repair?
return;
}
if (collected.length === 0) return;
- const mapped = mapServerMessages(collected);
+ const mapped = mapServerMessages(collected).filter(
+ (message) => !opts?.preserveClientIds?.has(message.clientId),
+ );
// 翻满上限仍没接回已知区段 → 下面走权威重建分支:整片旧窗口被换掉、oldestMessageId
// 也被改写。这是第八条"整体重建窗口"的路径,必须 bump epoch 作废 in-flight 的翻页 /
// 跳转补齐 —— 否则那些请求会带着**重建前**的游标返回,把一段脱离上下文的旧历史接到
@@ -11793,7 +12028,15 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean; repair?
// force 时(stall 看门狗已确认被控端 not-running)放行:此处 isStreaming 是卡死残留。
// 丢弃合并 = 拉回的窗口没进 UI:置 windowApplied=false,本次不得上报同步完成
// (否则挂起的远程已读回执会在缺帧内容尚未展示时被放行),等 turn 结束的下一轮。
- if (s.isStreaming && !opts?.force && !opts?.repair) {
+ // Snapshot repairs are additive; force recovery instead uses the
+ // reference-guarded authoritative merge below, including when a
+ // force signal was coalesced with an earlier repair.
+ if (s.isStreaming && opts?.repair && !opts.force) {
+ const repaired = mergeMessages(mapped, s.messages, { addOnly: true }, 'newest-first');
+ if (repaired === s.messages) return s;
+ return { ...s, messages: repaired };
+ }
+ if (s.isStreaming && !opts?.force) {
windowApplied = false;
return s;
}
@@ -11822,6 +12065,7 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean; repair?
'newest-first',
)
: mergeAuthoritativeRemoteWindow(mapped, lateArrivals, 'newest-first');
+ noteHydration?.(s.messages, messages);
// 无缺失且无权威字段变化 → 不换引用(视同已应用)。
if (messages === s.messages) return s;
if (isContiguous) return { ...s, messages };
@@ -16360,7 +16604,8 @@ export const makerChatStore = {
/**
* device-link:对账打开的远程会话消息(重拉最近一页 + 合并去重,补回 push 丢失的消息)。
* 由 useRemoteSessionSync 在重连 / 被控端回在线 / turn 结束 / 聚焦 / 手动同步时调用。
- * `opts.force` 仅供 stall 看门狗在确认被控端 not-running 后放行 isStreaming 守卫。
+ * `opts.force` 仅供 stall 看门狗在确认被控端 not-running 后放行 isStreaming 守卫;
+ * `opts.repair` 仅供 durable message push 丢失后的限频补读,streaming 时只追加缺失行。
*/
reconcileRemoteMessages,
/** stall 看门狗:读某 session 最近入站事件时刻(ms),判「卡死 Generating 但久未收 push」。 */
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 617e0e36c9..5eeffd9750 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1110,6 +1110,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
));
clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
if (shouldRecover) void rehydrateWithClient(client, deviceId);
+ return shouldRecover;
});
client.start();
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 02182babdd..7f8596fe86 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -16,6 +16,8 @@ import {
DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,
DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
MAX_TRANSPORT_PENDING_MESSAGES,
+ MAX_TRANSPORT_REASSEMBLIES,
+ MAX_TRANSPORT_REASSEMBLY_BYTES,
MAX_TRANSPORT_CHUNK_BYTES,
MAX_TRANSPORT_WEBSOCKET_BUFFERED_BYTES,
TRANSPORT_PENDING_PUSH_MAX_AGE_MS,
@@ -85,6 +87,7 @@ function makeHarness(opts?: {
timing?: ConstructorParameters<typeof DeviceLinkClient>[0]['timing'];
logger?: ConstructorParameters<typeof DeviceLinkClient>[0]['logger'];
peerFailurePolicy?: ConstructorParameters<typeof DeviceLinkClient>[0]['peerFailurePolicy'];
+ peerResetReadRetry?: ConstructorParameters<typeof DeviceLinkClient>[0]['peerResetReadRetry'];
}): Harness {
const sockets: FakeWs[] = [];
const client = new DeviceLinkClient({
@@ -104,6 +107,7 @@ function makeHarness(opts?: {
return ws;
},
peerFailurePolicy: opts?.peerFailurePolicy,
+ peerResetReadRetry: opts?.peerResetReadRetry,
timing: {
reconnectBaseMs: 5,
reconnectMaxMs: 40,
@@ -409,7 +413,7 @@ describe('DeviceLinkClient', () => {
const host = makeRelayClient(relay, 'desktop');
const a = makeRelayClient(relay, 'viewer-a');
const b = makeRelayClient(relay, 'viewer-b');
- const pump = () => relay.settle(() => vi.advanceTimersByTimeAsync(1));
+ const pump = () => relay.settle(async () => { await vi.advanceTimersByTimeAsync(1); });
let finishConfig!: (value: unknown) => void;
const config = new Promise<unknown>((resolve) => { finishConfig = resolve; });
const fetchConfig = vi.fn(() => config);
@@ -731,6 +735,101 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('buffers a resumed 64-message window including a fragmented result without waiting for its retry', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 1_000 } });
+ try {
+ h.client.start();
+ await tick();
+ h.current().ack();
+ const streamId = 'resumed-host-stream';
+ const base = 7_176;
+ await establishInboundReliableLink(h, streamId, base);
+ await establishInboundReliableLink(h, 'healthy-stream', 1, 'dev-c');
+ const received: number[] = [];
+ h.client.onFrame((env) => {
+ if (env.kind === 'push' && env.src === 'dev-b') {
+ received.push((env.payload as { payload: { seq: number } }).payload.seq);
+ }
+ });
+ const result = h.client.invoke('dev-b', { channel: 'local-db:sessions:list', args: [] });
+ const request = h.current().sent.filter((env) => env.kind === 'invoke' && env.dst === 'dev-b').at(-1)!;
+ const response = { ok: true, result: 'x'.repeat(188_000) };
+ const resultSeq = base + 33;
+ const frames = (seq: number) => encodeReliableFrames(seq === resultSeq ? {
+ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-b', id: request.id, payload: response,
+ } : {
+ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b',
+ payload: { channel: 'maker:event', payload: { seq } },
+ }, streamId, seq, base);
+ const deliver = (seq: number) => frames(seq).forEach((frame) => h.current().push(frame));
+ // XD-PC: the first recovery pass sends 8. Fresh snapshots overtake the
+ // next 8 retained entries, followed by a two-fragment sessions response.
+ for (let seq = base; seq < base + 8; seq++) deliver(seq);
+ await tick();
+ for (let seq = base + 16; seq < base + MAX_TRANSPORT_PENDING_MESSAGES; seq++) deliver(seq);
+ await tick();
+ expect(received).toHaveLength(8);
+
+ // The same socket continues serving a second peer while the gap remains.
+ const healthy = h.client.invoke('dev-c', { channel: 'local-db:sessions:list', args: [] });
+ const healthyRequest = h.current().sent.filter((env) => env.kind === 'invoke' && env.dst === 'dev-c').at(-1)!;
+ encodeReliableFrames({
+ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-c', id: healthyRequest.id,
+ payload: { ok: true, result: ['healthy'] },
+ }, 'healthy-stream', 1).forEach((frame) => h.current().push(frame));
+ await expect(healthy).resolves.toMatchObject({ result: ['healthy'] });
+
+ // Deliver only the missing old prefix; never resend the large response.
+ for (let seq = base + 8; seq < base + 16; seq++) deliver(seq);
+ await expect(result).resolves.toEqual(response);
+ await tick();
+ expect(received).toEqual(Array.from({ length: MAX_TRANSPORT_PENDING_MESSAGES }, (_, i) => base + i)
+ .filter((seq) => seq !== resultSeq));
+ expect(h.current().sent.map(parseTransportAck).filter((ack) => ack?.streamId === streamId).at(-1))
+ .toMatchObject({ ackSeq: base + MAX_TRANSPORT_PENDING_MESSAGES - 1 });
+ expect(h.sockets).toHaveLength(1);
+ expect(h.current().closed).toBeNull();
+ } finally { h.client.stop(); }
+ });
+
+ it('keeps the unfinished-assembly limit while admitting complete messages into the sequence window', async () => {
+ const warn = vi.fn();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 }, logger: { warn, info: vi.fn(), debug: vi.fn(), error: vi.fn() } });
+ try {
+ h.client.start();
+ await tick();
+ h.current().ack();
+ const streamId = 'bounded-assemblies';
+ await establishInboundReliableLink(h, streamId);
+ const received: number[] = [];
+ h.client.onFrame((env) => {
+ if (env.kind === 'push') received.push((env.payload as { payload: { seq: number } }).payload.seq);
+ });
+ const make = (seq: number, text = '') => encodeReliableFrames({
+ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b',
+ payload: { channel: 'maker:event', payload: { seq, text } },
+ }, streamId, seq);
+ const unfinished = Array.from({ length: MAX_TRANSPORT_REASSEMBLIES + 1 }, (_, i) => make(i + 2, 'x'.repeat(140_000)));
+ for (const parts of unfinished.slice(0, MAX_TRANSPORT_REASSEMBLIES)) h.current().push(parts[0]);
+ const overflow = unfinished.at(-1)!;
+ overflow.forEach((part) => h.current().push(part));
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('reason=receive_capacity_exceeded'));
+ const tail = MAX_TRANSPORT_REASSEMBLIES + 3;
+ make(tail).forEach((part) => h.current().push(part));
+ make(1).forEach((part) => h.current().push(part));
+ await tick();
+ // Complete the 16 admitted assemblies. The 17th still needs retransmission.
+ for (const parts of unfinished.slice(0, MAX_TRANSPORT_REASSEMBLIES)) {
+ parts.slice(1).forEach((part) => h.current().push(part));
+ await tick();
+ }
+ expect(received).toEqual(Array.from({ length: MAX_TRANSPORT_REASSEMBLIES + 1 }, (_, i) => i + 1));
+ overflow.forEach((part) => h.current().push(part));
+ await tick();
+ expect(received).toEqual(Array.from({ length: tail }, (_, i) => i + 1));
+ } finally { h.client.stop(); }
+ });
+
it('接收缓存被未来 seq 占满时,队头 skip 仍可进入并解除永久堵塞', async () => {
const h = makeHarness({ timing: { pingIntervalMs: 1_000 } });
h.client.start();
@@ -756,7 +855,7 @@ describe('DeviceLinkClient', () => {
expect(firstFrames.length).toBeGreaterThan(1);
h.current().push(firstFrames[0]);
- for (let seq = 2; seq <= 16; seq++) {
+ for (let seq = 2; seq <= MAX_TRANSPORT_PENDING_MESSAGES; seq++) {
h.current().push(encodeReliableFrames({
v: PROTOCOL_VERSION,
kind: 'push',
@@ -774,16 +873,52 @@ describe('DeviceLinkClient', () => {
}, streamId, 1)[0]);
await tick();
- expect(received).toEqual(Array.from({ length: 15 }, (_, index) => index + 2));
+ expect(received).toEqual(Array.from({ length: MAX_TRANSPORT_PENDING_MESSAGES - 1 }, (_, index) => index + 2));
expect(h.current().sent.filter((env) => (
env.kind === 'push'
&& (env.payload as { channel?: string }).channel === DEVICE_LINK_TRANSPORT_ACK_CHANNEL
)).at(-1)).toMatchObject({
- payload: { payload: { ackSeq: 16 } },
+ payload: { payload: { ackSeq: MAX_TRANSPORT_PENDING_MESSAGES } },
});
h.client.stop();
});
+ it('bounds receive bytes across complete messages and assemblies while reserving progress for the head', async () => {
+ const warn = vi.fn();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 }, logger: { warn, info: vi.fn(), debug: vi.fn(), error: vi.fn() } });
+ try {
+ h.client.start();
+ await tick();
+ h.current().ack();
+ const streamId = 'bounded-receive-bytes';
+ await establishInboundReliableLink(h, streamId);
+ const received: number[] = [];
+ h.client.onFrame((env) => {
+ if (env.kind === 'push') received.push((env.payload as { payload: { seq: number } }).payload.seq);
+ });
+ // Four complete 3.2MB messages fit, a fifth exceeds the unchanged 16MB
+ // byte cap once JSON overhead is included. No unfinished-assembly limit
+ // is involved: each logical message is delivered as a complete burst.
+ const text = 'x'.repeat(Math.floor(MAX_TRANSPORT_REASSEMBLY_BYTES / 5));
+ const deliver = (seq: number) => encodeReliableFrames({
+ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b',
+ payload: { channel: 'maker:event', payload: { seq, text } },
+ }, streamId, seq).forEach((frame) => h.current().push(frame));
+ for (let seq = 2; seq <= 6; seq++) deliver(seq);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('reason=receive_capacity_exceeded'));
+ expect(received).toEqual([]);
+ deliver(1); // Must evict a future entry to fit; cannot deadlock the head.
+ await tick();
+ expect(received).toEqual([1, 2, 3, 4]);
+ deliver(5);
+ deliver(6);
+ await tick();
+ expect(received).toEqual([1, 2, 3, 4, 5, 6]);
+ expect(h.current().sent.map(parseTransportAck).filter((ack) => ack?.streamId === streamId).at(-1))
+ .toMatchObject({ ackSeq: 6 });
+ } finally { h.client.stop(); }
+ });
+
it('distinguishes receive capacity from declared size and recovers the missing head in order', async () => {
const warn = vi.fn();
const h = makeHarness({ timing: { pingIntervalMs: 60_000 }, logger: { warn, debug: vi.fn(), info: vi.fn(), error: vi.fn() } });
@@ -800,7 +935,7 @@ describe('DeviceLinkClient', () => {
v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', id: `request-${seq}`,
payload: { channel: 'maker:event', payload: { seq, text: large ? 'PRIVATE'.repeat(30_000) : '' } },
}, streamId, seq);
- for (let seq = 2; seq <= 17; seq++) h.current().push(frames(seq)[0]);
+ for (let seq = 2; seq <= 17; seq++) h.current().push(frames(seq, true)[0]);
h.current().push(frames(18, true)[0]);
expect(warn).toHaveBeenCalledWith(expect.stringContaining('reason=receive_capacity_exceeded'));
const line = warn.mock.calls.at(-1)?.[0];
@@ -813,7 +948,9 @@ describe('DeviceLinkClient', () => {
// The full cache still makes room for the missing segmented head.
for (const frame of frames(1, true)) h.current().push(frame);
await tick();
- for (const frame of frames(17)) h.current().push(frame);
+ for (let seq = 2; seq <= 17; seq++) {
+ for (const frame of frames(seq, true)) h.current().push(frame);
+ }
for (const frame of frames(18, true)) h.current().push(frame);
await tick();
expect(received).toEqual(Array.from({ length: 18 }, (_, i) => i + 1));
@@ -924,6 +1061,125 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it.each([{ prefix: 2, bytes: 0 }, { prefix: 1, bytes: 300_000 }])(
+ 'ACKs a completed prefix ($prefix messages, $bytes bytes) before a slow tail, without affecting another peer',
+ async ({ prefix, bytes }) => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ let releaseTail: (() => void) | undefined;
+ try {
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ const streamId = 'batched-ack-stream';
+ await establishInboundReliableLink(h, streamId);
+ await establishInboundReliableLink(h, 'healthy-ack-stream', 1, 'dev-c');
+ const seen: number[] = [];
+ h.client.onFrame((env) => {
+ if (env.kind !== 'push' || env.src !== 'dev-b') return;
+ const seq = (env.payload as { payload: { seq: number } }).payload.seq;
+ seen.push(seq);
+ if (seq === prefix + 1) {
+ return new Promise<void>((resolve) => { releaseTail = resolve; });
+ }
+ });
+ const deliver = (seq: number) => encodeReliableFrames({
+ v: PROTOCOL_VERSION,
+ kind: 'push' as const,
+ src: 'dev-b',
+ payload: { channel: 'maker:event', payload: { seq, text: 'x'.repeat(seq === 1 ? bytes : 0) } },
+ }, streamId, seq).forEach(frame => h.current().push(frame));
+
+ for (let seq = 1; seq <= prefix + 1; seq++) deliver(seq);
+ await tick();
+
+ expect(releaseTail).toBeTypeOf('function');
+ expect(h.current().sent.map(parseTransportAck).filter((ack) => ack?.streamId === streamId).at(-1))
+ .toMatchObject({ ackSeq: prefix });
+ deliver(1); // An early ACK must not make duplicate delivery execute twice.
+ encodeReliableFrames({
+ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-c',
+ payload: { channel: 'maker:event', payload: {} },
+ }, 'healthy-ack-stream', 1).forEach(frame => h.current().push(frame));
+ await tick();
+ expect(h.current().sent.map(parseTransportAck).filter(ack => ack?.streamId === 'healthy-ack-stream').at(-1))
+ .toMatchObject({ ackSeq: 1 });
+
+ releaseTail!();
+ await tick();
+ expect(h.current().sent.map(parseTransportAck).filter((ack) => ack?.streamId === streamId).at(-1))
+ .toMatchObject({ ackSeq: prefix + 1 });
+ expect(seen).toEqual(Array.from({ length: prefix + 1 }, (_, i) => i + 1));
+ expect(h.sockets).toHaveLength(1);
+ expect(h.current().closed).toBeNull();
+ } finally { releaseTail?.(); h.client.stop(); }
+ });
+
+ it.each(['failure', 'closed', 'ack-write-failure'])('keeps ACK batch boundaries safe during %s', async (mode) => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ try {
+ h.client.start(); await tick(); h.current().ack();
+ const streamId = 'ack-boundary';
+ await establishInboundReliableLink(h, streamId);
+ h.client.onFrame(env => {
+ if (env.kind !== 'push') return;
+ const seq = (env.payload as { payload: { seq: number } }).payload.seq;
+ if (seq !== 2) return;
+ if (mode === 'failure') throw new Error('handler did not finish');
+ if (mode === 'closed') h.client.closeLink('dev-b', 'user');
+ });
+ const send = h.current().send.bind(h.current());
+ let failed = false;
+ h.current().send = (data) => {
+ if (mode === 'ack-write-failure' && !failed && parseTransportAck(JSON.parse(data))) {
+ failed = true;
+ throw new Error('socket write failed once');
+ }
+ send(data);
+ };
+ for (let seq = 1; seq <= 2; seq++) {
+ encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b',
+ payload: { channel: 'maker:event', payload: { seq } },
+ }, streamId, seq).forEach(frame => h.current().push(frame));
+ }
+ await tick();
+ const acks = h.current().sent.map(parseTransportAck).filter(ack => ack?.streamId === streamId);
+ if (mode === 'closed') expect(acks).toEqual([]);
+ else expect(acks.at(-1)).toMatchObject({ ackSeq: mode === 'failure' ? 1 : 2 });
+ } finally { h.client.stop(); }
+ });
+
+ it('bounds recovery stage logs, measures with monotonic time and records a fresh outbound handshake', async () => {
+ const debug = vi.fn();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 },
+ logger: { debug, info: vi.fn(), warn: vi.fn(), error: vi.fn() } });
+ let now = 100;
+ const clock = vi.spyOn(h.client as unknown as { monotonicNow(): number }, 'monotonicNow').mockImplementation(() => now);
+ try {
+ h.client.start(); await tick(); h.current().ack();
+ const open = h.client.openLink('dev-b', { controllerName: 'Test', protocolVersion: 1, appVersion: '1' });
+ const sent = h.current().sent.find(env => env.kind === 'link-open')!;
+ now += 25;
+ h.current().push({ v: PROTOCOL_VERSION, kind: 'link-accept', src: 'dev-b', id: sent.id,
+ payload: { appVersion: '1', allowlistHash: 'h', transportStreamId: 'trace-stream',
+ capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT] } });
+ await open;
+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('stage=link-accept-received elapsedMs=25.0'));
+ for (let seq = 1; seq <= 32; seq++) {
+ encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b',
+ payload: { channel: 'maker:event', payload: { text: 'PRIVATE-PAYLOAD' } },
+ }, 'trace-stream', seq).forEach(frame => h.current().push(frame));
+ }
+ await tick();
+ expect(debug.mock.calls.filter(([line]) => String(line).includes('stage=ack-sent'))).toHaveLength(8);
+ expect(debug.mock.calls.flat().join(' ')).not.toContain('PRIVATE-PAYLOAD');
+ const count = debug.mock.calls.length;
+ now += 30_001;
+ h.client.sendInvokeResult('dev-b', 'after-trace-expiry', { ok: true, result: 'done' });
+ expect(debug.mock.calls).toHaveLength(count);
+ } finally { h.client.stop(); clock.mockRestore(); }
+ });
+
it('慢可靠业务 handler 不阻塞 pong,避免把本地处理拥塞误判成断网', async () => {
const h = makeHarness({
timing: {
@@ -2111,6 +2367,60 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('peer reset 后幂等读请求立即返回 PEER_RESET,交给 host 做一次重开重试', async () => {
+ const logs: unknown[][] = [];
+ const h = makeHarness({
+ peerResetReadRetry: true,
+ logger: {
+ debug: (...args) => logs.push(args),
+ info: (...args) => logs.push(args),
+ warn: (...args) => logs.push(args),
+ error: (...args) => logs.push(args),
+ },
+ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 5_000 },
+ });
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ const open = h.client.openLink(
+ 'dev-b',
+ { controllerName: 'Test', protocolVersion: 1, appVersion: '1' },
+ 100,
+ );
+ const openFrame = h.current().sent.find((env) => env.kind === 'link-open')!;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'link-accept',
+ id: openFrame.id,
+ src: 'dev-b',
+ payload: {
+ appVersion: '1',
+ allowlistHash: 'hash',
+ capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT],
+ transportStreamId: 'read-reset-stream',
+ },
+ });
+ await open;
+
+ const invoke = h.client.invoke('dev-b', { channel: 'local-db:sessions:list', args: [] });
+ const sent = h.current().sent.find((env) => env.kind === 'invoke')!;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'link-close',
+ src: 'dev-b',
+ payload: { reason: 'transport-timeout' },
+ });
+
+ await expect(invoke).rejects.toMatchObject({ code: 'PEER_RESET', inFlight: true });
+ expect(h.current().sent.filter((env) => env.kind === 'invoke')).toHaveLength(1);
+ expect(logs.flat().some((value) => (
+ typeof value === 'string' && value.includes('peer-reset fast-fail read request')
+ ))).toBe(true);
+ expect(sent.id).toBeTruthy();
+ h.client.stop();
+ });
+
it('对端显式关闭 link 时终止可靠 pending,不留到未来重放', async () => {
const h = makeHarness({ timing: { pingIntervalMs: 1_000 } });
h.client.start();
@@ -5988,6 +6298,54 @@ describe('DeviceLinkClient', () => {
await Promise.allSettled([pending, linkPending, reopen]);
});
+ it('C1: stale frame without outbound intent does not consume the throttle window', async () => {
+ const proto = DeviceLinkClient.prototype as unknown as { monotonicNow(): number };
+ const nowMs = 3_000_000;
+ const clock = vi.spyOn(proto, 'monotonicNow').mockImplementation(() => nowMs);
+ try {
+ const h = makeHarness({
+ timing: { reconnectBaseMs: 5, reconnectMaxMs: 10, requestTimeoutMs: 60_000, pingIntervalMs: 60_000 },
+ });
+ const handled: string[] = [];
+ h.client.onReliableFrameBeforeLink((deviceId) => {
+ if (!h.client.hasPendingRequestsTo(deviceId)) return false;
+ handled.push(deviceId);
+ return true;
+ });
+ h.client.start();
+ await makeLinkDownPeer(h, 'dev-stale');
+
+ const staleFrame = encodeReliableFrames(
+ {
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'dev-stale',
+ dst: 'dev-self',
+ payload: { channel: 'sessions', payload: {} },
+ },
+ 'stream-dev-stale',
+ 1,
+ 1,
+ )[0]!;
+ h.current().push({ ...staleFrame, src: 'dev-stale' });
+ await tick();
+ expect(handled).toEqual([]);
+
+ const pending = h.client.invoke('dev-stale', {
+ channel: 'local-db:sessions:list',
+ args: [],
+ });
+ h.current().push({ ...staleFrame, src: 'dev-stale' });
+ await tick();
+ expect(handled).toEqual(['dev-stale']);
+
+ h.client.stop();
+ await expect(pending).rejects.toBeDefined();
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
it('C2:link 恢复即清节流 —— 恢复后 30s 内再次丢 link 时新帧立刻再通知一次', async () => {
const proto = DeviceLinkClient.prototype as unknown as { monotonicNow(): number };
let nowMs = 4_000_000;
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 51be081fec..f70d9359a0 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -109,6 +109,14 @@ const HANDSHAKE_TIMEOUT_WIDEN_AFTER = 2;
/** 「link 未就绪收到可靠帧」通知的 per-peer 节流(见 onReliableFrameBeforeLink)。 */
const STALE_LINK_NOTIFY_THROTTLE_MS = 30_000;
const SLOW_REQUEST_WARN_MS = 1_000;
+/**
+ * 接收端累计 ACK 的推进粒度。整批 drain 完成前完全不 ACK 会让发送端把
+ * 已成功处理的前缀也等在慢 handler 后面。小批量 ACK 让发送端及时释放
+ * 窗口;不提前确认尚未处理的消息,也不改变发送端的重试间隔与预算。
+ */
+const RELIABLE_ACK_BATCH_MESSAGES = 2;
+const RELIABLE_ACK_BATCH_BYTES = 256 * 1024;
+const RECOVERY_TRACE_WINDOW_MS = 30_000;
// Allow slow relay -> controller delivery before duplicating an entire message.
// With the default 2s tick this allows 8KiB/s, capped at 30s per attempt. Small
// messages retain their existing retry cadence; dead peers still exhaust retries.
@@ -213,6 +221,11 @@ export interface DeviceLinkClientOptions {
* 这是 additive、host opt-in 的本地策略;Desktop 不传时行为完全不变。
*/
peerFailurePolicy?: DeviceLinkPeerFailurePolicy;
+ /**
+ * Peer 可靠传输复位时,是否让幂等的本地数据库读请求快速失败给 host,
+ * 由 host 重开 link 后最多重试一次。写请求和长执行请求不走这条路径。
+ */
+ peerResetReadRetry?: boolean;
/** 测试注入:覆盖重连/心跳的时间参数 */
timing?: Partial<DeviceLinkTiming>;
}
@@ -468,6 +481,36 @@ interface PendingRequest {
reliableDst?: string;
/** 请求真正发出时所属的 peer link 代次,供迟到 relay-error 归属。 */
linkGeneration?: number;
+ /** peer reset 时让 host 快速结束本次等待,由 host 重开后决定是否重试。 */
+ retryAfterPeerReset?: () => void;
+}
+
+const PEER_RESET_RETRYABLE_READ_CHANNELS = new Set([
+ 'local-db:sessions:list',
+ 'local-db:sessions:get',
+ 'local-db:conversations:search',
+ 'local-db:history:messages',
+ 'local-db:messages:list',
+ 'local-db:messages:view',
+ 'local-db:messages:work-details',
+ 'local-db:messages:around',
+ 'local-db:messages:around-client-id',
+ 'local-db:messages:estimatedSessionValue',
+ 'local-db:recent-workdirs:list',
+ 'local-db:subagent-runs:list',
+ 'local-db:subagent-runs:detail',
+ 'local-db:subagent-runs:transcript',
+ 'local-db:bots:list',
+ 'local-db:bots:get',
+ 'local-db:orca-workflows:get-by-lead',
+ 'local-db:orca-workflows:get-by-worker-session',
+ 'local-db:orca-workflows:list-workers-by-lead',
+]);
+
+function isPeerResetRetryableRead(env: Omit<Envelope, 'id'>): boolean {
+ if (env.kind !== 'invoke') return false;
+ const channel = (env.payload as InvokePayload | undefined)?.channel;
+ return typeof channel === 'string' && PEER_RESET_RETRYABLE_READ_CHANNELS.has(channel);
}
interface PendingReliableMessage {
@@ -508,6 +551,16 @@ interface OutboundLinkConfirmationAck {
timer: ReturnType<typeof setTimeout> | null;
}
+/** Bounded, per-link diagnostics only; never used to decide delivery or retries. */
+interface RecoveryTrace {
+ startedAt: number;
+ connectionEpoch: number;
+ requestId: string;
+ stages: Set<string>;
+ ackProgressLogs: number;
+ replayThroughSeq: number | null;
+}
+
interface PeerTransportState {
streamId: string;
remoteStreamId: string | null;
@@ -566,6 +619,7 @@ interface PeerTransportState {
recoveryNeedsAck: boolean;
/** 本轮恢复探测已写出的帧数(含 replay 与恢复期内首发)。 */
recoveryFramesSent: number;
+ recoveryTrace: RecoveryTrace | null;
/** latest-wins 腾位驱逐的聚合计数(自上次告警起),仅服务日志聚合。 */
pushAdmissionDropCount: number;
/** 上次输出 latest-wins 驱逐告警的单调时刻;0 表示从未输出。 */
@@ -678,7 +732,7 @@ export class DeviceLinkClient {
// —— host 订阅 ——
private statusHandlers = new Set<(s: DeviceLinkStatus) => void>();
/** 收到「link 未就绪」可靠帧的通知(30s/peer 节流);host 据此主动重建控制链路。 */
- private staleLinkHandlers = new Set<(deviceId: string) => void>();
+ private staleLinkHandlers = new Set<(deviceId: string) => unknown>();
private staleLinkNotifiedAt = new Map<string, number>();
private presenceHandlers = new Set<(snap: PresenceSnapshot) => void>();
private frameHandlers = new Set<InboundFrameHandler>();
@@ -1096,8 +1150,10 @@ export class DeviceLinkClient {
* 两套节流参数)。刻意只报 deviceId、不附带 peer 的 explicitlyClosed:那是双向
* 共享位(互控时对端仅关闭它控制本机的方向也会置位),不能用来判断本机的出站
* 方向该不该恢复 —— 方向判据在 host 侧(是否持有该设备的出站订阅)。
+ * Return false when the host has no recovery intent; ignored notifications
+ * do not consume the per-peer throttle. Other return values mean handled.
*/
- onReliableFrameBeforeLink(cb: (deviceId: string) => void): () => void {
+ onReliableFrameBeforeLink(cb: (deviceId: string) => unknown): () => void {
this.staleLinkHandlers.add(cb);
return () => this.staleLinkHandlers.delete(cb);
}
@@ -1107,14 +1163,20 @@ export class DeviceLinkClient {
const now = this.monotonicNow();
const last = this.staleLinkNotifiedAt.get(deviceId);
if (last !== undefined && now - last < STALE_LINK_NOTIFY_THROTTLE_MS) return;
- this.staleLinkNotifiedAt.set(deviceId, now);
+ // A stale frame may arrive before the host has any outbound intent (for
+ // example while a fresh owner is taking over). Do not consume the
+ // per-peer throttle in that case: a later invoke/subscribe would
+ // otherwise be unable to wake the host until the full throttle window
+ // elapsed and could time out while the peer's reliable result is held.
+ let handled = false;
for (const cb of this.staleLinkHandlers) {
try {
- cb(deviceId);
+ if (cb(deviceId) !== false) handled = true;
} catch (err) {
this.log.error('reliable-frame-before-link handler threw', err);
}
}
+ if (handled) this.staleLinkNotifiedAt.set(deviceId, now);
}
// ─── 出站 API ───────────────────────────────────────────────────────────────
@@ -1303,6 +1365,7 @@ export class DeviceLinkClient {
if (peerSupportsReliable) {
this.dropDiscardablePendingPrefix(dst, peer, false, 'before link re-establishment replay');
}
+ this.beginRecoveryTrace(dst, requestId);
const linkGeneration = peer.linkGeneration + 1;
const linkAcceptId = this.sendRoutedEnvelope({
v: PROTOCOL_VERSION,
@@ -1326,6 +1389,7 @@ export class DeviceLinkClient {
},
}, linkGeneration);
this.markPeerRouteOnline(dst, linkGeneration);
+ this.logRecoveryStage(dst, 'link-accept-sent');
if (!peerSupportsLinkConfirm && linkAcceptId) {
// 旧端没有可等待的 confirmation;accept 是不可重放的单次控制帧,发送后
// 不把它变成永久历史配额;近期迟到错误仍可按原代次归属。
@@ -1395,6 +1459,7 @@ export class DeviceLinkClient {
env: Omit<Envelope, 'id'>,
expectKind: 'invoke-result' | 'link-accept',
timeoutMs?: number,
+ allowPeerResetRetry = true,
): Promise<Envelope> {
if (this.status !== 'online') {
return Promise.reject(new DeviceLinkError('NOT_CONNECTED', 'not connected to relay'));
@@ -1432,7 +1497,7 @@ export class DeviceLinkClient {
reject(new DeviceLinkError('INVOKE_TIMEOUT', `no ${expectKind} within ${timeout}ms`));
}, timeout);
- this.pending.set(id, {
+ const pendingRequest: PendingRequest = {
resolve: (frame) => {
clearTimeout(timer);
logFinished('ok');
@@ -1447,10 +1512,36 @@ export class DeviceLinkClient {
expectKind,
dst: env.dst,
linkGeneration: env.dst ? this.getPeerLinkGeneration(env.dst) : undefined,
- });
+ };
+ this.pending.set(id, pendingRequest);
+ if (
+ allowPeerResetRetry
+ && this.opts.peerResetReadRetry === true
+ && env.dst
+ && isPeerResetRetryableRead(env)
+ ) {
+ pendingRequest.retryAfterPeerReset = () => {
+ if (this.pending.get(id) !== pendingRequest) return;
+ this.pending.delete(id);
+ clearTimeout(timer);
+ this.settleOutboundRouteAttemptsForId(env.dst!, id);
+ this.dropReliablePendingForRequest(env.dst!, id);
+ this.log.info(
+ `device-link request peer-reset fast-fail ${requestDescription}`
+ + ` action=host-retry-once previousRequest=${id.slice(0, 8)}`,
+ );
+ const err = new DeviceLinkError(
+ 'PEER_RESET',
+ `peer link reset before ${expectKind}; host may retry this read once`,
+ );
+ err.inFlight = true;
+ pendingRequest.reject(err);
+ };
+ }
try {
const outbound = { ...env, id };
+ if (outbound.kind === 'link-open' && outbound.dst) this.beginRecoveryTrace(outbound.dst, id);
if (outbound.kind === 'invoke' && outbound.dst) {
const reliable = this.sendPeerEnvelope(outbound);
if (reliable) {
@@ -1459,6 +1550,7 @@ export class DeviceLinkClient {
}
} else {
this.sendRoutedEnvelope(outbound);
+ if (outbound.kind === 'link-open' && outbound.dst) this.logRecoveryStage(outbound.dst, 'link-open-sent');
}
} catch (err) {
this.pending.delete(id);
@@ -1497,6 +1589,32 @@ export class DeviceLinkClient {
}
}
+ /**
+ * ACK 耗尽 / transport-timeout 只说明当前 peer link 不再可用;对幂等读请求,
+ * 继续等原 requestTimeoutMs 会把恢复阶段前的 12 秒完整暴露给用户。先结束旧
+ * request,再由 Desktop 的既有 link recovery 重开并最多提交一次新 request id。
+ */
+ private retryReadRequestsAfterPeerReset(dst: string, seq: number): void {
+ const candidates = [...this.pending.values()].filter((pending) => (
+ pending.dst === dst
+ && pending.expectKind === 'invoke-result'
+ && pending.retryAfterPeerReset
+ ));
+ if (candidates.length === 0) {
+ this.log.debug(
+ `device-link peer-reset no retryable read request dst=${dst.slice(0, 8)} seq=${seq}`,
+ );
+ return;
+ }
+ for (const pending of candidates) {
+ this.log.info(
+ `device-link peer-reset fast-fail read request dst=${dst.slice(0, 8)}`
+ + ` seq=${seq} action=retry-once`,
+ );
+ pending.retryAfterPeerReset?.();
+ }
+ }
+
private dropReliablePendingForRequest(dst: string, requestId: string): void {
const peer = this.peerTransport.get(dst);
if (!peer) return;
@@ -2116,6 +2234,7 @@ export class DeviceLinkClient {
);
const peer = this.getPeerTransport(env.src);
const acceptedLinkGeneration = this.markPeerRouteOnline(env.src);
+ this.logRecoveryStage(env.src, 'link-accept-received', ` baseSeq=${peer.remoteBaseSeq}`);
// 这是本机先发送 link-open、对端收到后才可能返回的 accept。relay 对同一
// 来源连接严格按发送顺序处理,因此任何更早物理发送若会产生 route error,
// 错误必然排在这次 accept 之前;走到这里仍无错误的旧代记录就是已成功路由
@@ -2146,6 +2265,7 @@ export class DeviceLinkClient {
}
if (p.dst && env.id) this.discardOutboundRouteAttemptsForId(p.dst, env.id);
this.pending.delete(env.id!);
+ if (env.kind === 'invoke-result' && env.src) this.logRecoveryStage(env.src, 'first-response-received');
p.resolve(env);
return true;
}
@@ -2293,6 +2413,7 @@ export class DeviceLinkClient {
// desktop 控制端据此立即重新 openLink(见各自 link-close 处理)。
const peer = this.getPeerTransport(env.src);
this.markPeerLinkDown(peer);
+ this.retryReadRequestsAfterPeerReset(env.src, 0);
if (peer.retryTimer) {
clearInterval(peer.retryTimer);
peer.retryTimer = null;
@@ -2376,6 +2497,7 @@ export class DeviceLinkClient {
}
if (!peer.remoteStreamId) peer.remoteStreamId = parsed.meta.streamId;
const { meta } = parsed;
+ this.logRecoveryStage(env.src, 'first-reliable-receive', ` seq=${meta.seq} baseSeq=${meta.baseSeq ?? 1}`);
const stream = this.getReceiveStream(
peer,
meta.streamId,
@@ -2471,7 +2593,7 @@ export class DeviceLinkClient {
const bytes = byteLength(parsed.data);
const rejection = bytes > MAX_TRANSPORT_CHUNK_BYTES ? 'chunk_too_large'
: assembly.bytes + bytes > assembly.totalBytes ? 'declared_size_exceeded'
- : !this.ensureReceiveCapacity(stream, meta.seq, bytes) ? 'receive_capacity_exceeded' : null;
+ : !this.ensureReceiveCapacity(stream, meta.seq, bytes, true) ? 'receive_capacity_exceeded' : null;
if (rejection) {
this.log.warn(`dropping reliable payload reason=${rejection} ${describeRejectedFrame()}`
+ ` incomingBytes=${bytes} assembledBytes=${assembly.bytes} declaredBytes=${assembly.totalBytes}`
@@ -2513,6 +2635,10 @@ export class DeviceLinkClient {
return stream.drain;
}
const drain = async (): Promise<void> => {
+ let deliveredSinceAck = 0;
+ let deliveredBytesSinceAck = 0;
+ let lastAckSentSeq = stream.lastDeliveredSeq;
+ let sentAck = false;
do {
stream.drainRequested = false;
this.applyReceiveStreamBase(stream);
@@ -2545,12 +2671,30 @@ export class DeviceLinkClient {
break;
}
stream.ready.delete(nextSeq);
- stream.bufferedBytes -= byteLength(ready.json);
+ const deliveredBytes = byteLength(ready.json);
+ stream.bufferedBytes -= deliveredBytes;
stream.lastDeliveredSeq = nextSeq;
this.applyReceiveStreamBase(stream);
+ deliveredSinceAck += 1;
+ deliveredBytesSinceAck += deliveredBytes;
+ if (
+ (deliveredSinceAck >= RELIABLE_ACK_BATCH_MESSAGES
+ || deliveredBytesSinceAck >= RELIABLE_ACK_BATCH_BYTES)
+ && this.isReceiveStreamActive(src, streamId, stream)
+ ) {
+ if (this.sendTransportAck(src, streamId, stream.lastDeliveredSeq)) {
+ lastAckSentSeq = stream.lastDeliveredSeq;
+ sentAck = true;
+ }
+ deliveredSinceAck = 0;
+ deliveredBytesSinceAck = 0;
+ }
}
} while (stream.drainRequested);
- if (this.isReceiveStreamActive(src, streamId, stream)) {
+ if (
+ this.isReceiveStreamActive(src, streamId, stream)
+ && (!sentAck || stream.lastDeliveredSeq !== lastAckSentSeq)
+ ) {
this.sendTransportAck(src, streamId, stream.lastDeliveredSeq);
}
};
@@ -2596,19 +2740,27 @@ export class DeviceLinkClient {
}
/**
- * 接收缓存满时优先保住当前队头。否则未来 seq 占满 16 个槽位或字节预算后,
+ * Complete messages occupy the bounded sequence window, not unfinished
+ * reassembly slots. Recovery can deliver a full window before a missing
+ * prefix; sharing the 16-assembly limit drops valid replies until their
+ * byte-paced retry (often after the invoke timeout).
+ * 接收缓存满时优先保住当前队头。否则未来 seq 占满槽位或字节预算后,
* 用来补缺口的分片/skip 也进不来,累计 ACK 将永久停住。
*/
private ensureReceiveCapacity(
stream: ReceiveStreamState,
seq: number,
additionalBytes: number,
+ assembling = false,
): boolean {
const fits = (): boolean => {
const hasSlot = stream.ready.has(seq) || stream.assemblies.has(seq);
const slots = stream.ready.size + stream.assemblies.size + (hasSlot ? 0 : 1);
+ const assemblies = stream.assemblies.size
+ + (assembling && !stream.assemblies.has(seq) ? 1 : 0);
return (
- slots <= MAX_TRANSPORT_REASSEMBLIES
+ slots <= MAX_TRANSPORT_SEQUENCE_WINDOW
+ && assemblies <= MAX_TRANSPORT_REASSEMBLIES
&& stream.bufferedBytes + additionalBytes <= MAX_TRANSPORT_REASSEMBLY_BYTES
);
};
@@ -2839,6 +2991,10 @@ export class DeviceLinkClient {
pending.sent = true;
pending.attempts++;
pending.lastSentAt = Date.now();
+ this.logRecoveryStage(pending.envelope.dst!, 'first-reliable-write', ` seq=${pending.seq} frames=${sent}`);
+ if (pending.envelope.kind === 'invoke-result') {
+ this.logRecoveryStage(pending.envelope.dst!, 'first-response-write', ` seq=${pending.seq} frames=${sent}`);
+ }
}
}
return sent;
@@ -3179,6 +3335,7 @@ export class DeviceLinkClient {
lastReplayRemoteStreamId: null,
recoveryNeedsAck: false,
recoveryFramesSent: 0,
+ recoveryTrace: null,
pushAdmissionDropCount: 0,
pushAdmissionDropLogAt: 0,
linkGeneration: 0,
@@ -3354,7 +3511,7 @@ export class DeviceLinkClient {
streamId: string,
ackSeq: number,
linkRequestId?: string,
- ): void {
+ ): boolean {
const pendingConfirmation = this.peerTransport.get(dst)?.outboundLinkConfirmationAck;
const effectiveLinkRequestId = linkRequestId ?? (
pendingConfirmation?.streamId === streamId
@@ -3365,12 +3522,15 @@ export class DeviceLinkClient {
this.sendBestEffortRoutedEnvelope(
makeTransportAck(dst, streamId, ackSeq, effectiveLinkRequestId),
);
+ this.logRecoveryStage(dst, 'ack-sent', ` receiveStream=${streamId.slice(0, 8)} ack=${ackSeq}`, false);
+ return true;
} catch (err) {
this.log.debug(
`reliable transport ACK send failed dst=${dst.slice(0, 8)}`
+ ` stream=${streamId.slice(0, 8)} ack=${ackSeq} conn=${this.connEpoch}`,
err,
);
+ return false;
}
}
@@ -3447,6 +3607,7 @@ export class DeviceLinkClient {
+ ` stream=${peer.streamId.slice(0, 8)} request=${confirmation.requestId.slice(0, 8)}`
+ ` ack=${ackSeq} conn=${this.connEpoch}`,
);
+ this.logRecoveryStage(src, 'link-confirm-received', ` ack=${ackSeq}`);
// 新版入站重建的带 request id ACK 是 local → remote 的因果屏障:对端已经
// 收到本代 link-accept,旧代成功路由却未 ACK 的尝试不会再产生 relay-error。
// 必须在重放前淘汰旧代记录,否则当前重放真实失败会 FIFO 消费旧代并被当
@@ -3461,6 +3622,7 @@ export class DeviceLinkClient {
// 不错误推进状态;高于 nextSeq-1 的未知 ACK 与倒退的 ACK 直接忽略。
if (ackSeq > peer.nextSeq - 1 || ackSeq <= peer.highestAckSeq) return;
peer.highestAckSeq = ackSeq;
+ this.logRecoveryStage(src, 'ack-received', ` ack=${ackSeq}`, false);
for (const [seq, pending] of peer.pending) {
if (seq > ackSeq) break;
if (pending.envelope.id) {
@@ -3472,12 +3634,18 @@ export class DeviceLinkClient {
if (peer.recoveryNeedsAck) {
peer.recoveryNeedsAck = false;
peer.recoveryFramesSent = 0;
+ this.logRecoveryStage(src, 'recovery-probe-acked', ` ack=${ackSeq}`);
this.retryPending(src, { ignoreInterval: true });
} else {
// Release locally queued first sends promptly, without replaying already
// in-flight large responses every time a partial ACK arrives.
this.retryPending(src, { ignoreInterval: false, onlyUnsent: true });
}
+ if (peer.recoveryTrace?.replayThroughSeq !== null
+ && peer.recoveryTrace?.replayThroughSeq !== undefined
+ && ackSeq >= peer.recoveryTrace.replayThroughSeq) {
+ this.logRecoveryStage(src, 'replay-backlog-acked', ` ack=${ackSeq}`);
+ }
if (peer.pending.size === 0 && peer.retryTimer) {
clearInterval(peer.retryTimer);
peer.retryTimer = null;
@@ -3493,6 +3661,43 @@ export class DeviceLinkClient {
return performance.now();
}
+ private beginRecoveryTrace(dst: string, requestId: string): void {
+ this.getPeerTransport(dst).recoveryTrace = {
+ startedAt: this.monotonicNow(),
+ connectionEpoch: this.connEpoch,
+ requestId,
+ stages: new Set(),
+ ackProgressLogs: 0,
+ replayThroughSeq: null,
+ };
+ }
+
+ /** Stage names and details are local transport metadata, never business payloads. */
+ private logRecoveryStage(dst: string, stage: string, detail = '', once = true): void {
+ const peer = this.peerTransport.get(dst);
+ const trace = peer?.recoveryTrace;
+ if (!peer || !trace) return;
+ const elapsedMs = Math.max(0, this.monotonicNow() - trace.startedAt);
+ if (trace.connectionEpoch !== this.connEpoch || elapsedMs > RECOVERY_TRACE_WINDOW_MS) {
+ peer.recoveryTrace = null;
+ return;
+ }
+ if (once) {
+ if (trace.stages.has(stage)) return;
+ trace.stages.add(stage);
+ } else {
+ // ACKs in steady traffic must not become a per-frame logging stream.
+ if (trace.ackProgressLogs >= 8) return;
+ trace.ackProgressLogs++;
+ }
+ this.log.debug(
+ `device-link recovery-stage dst=${dst.slice(0, 8)} stage=${stage}`
+ + ` elapsedMs=${elapsedMs.toFixed(1)} request=${trace.requestId.slice(0, 8)}`
+ + ` conn=${this.connEpoch} link=${peer.linkGeneration}`
+ + ` pending=${peer.pending.size}/${peer.pendingBytes}${detail}`,
+ );
+ }
+
/**
* 可丢弃帧判据(重连重放与 invoke-result 腾位两条路径共用的不变量;
* push latest-wins 腾位用更窄的白名单判据,见
@@ -3824,6 +4029,7 @@ export class DeviceLinkClient {
private commitReliableReceiveReady(dst: string, peer: PeerTransportState): void {
peer.receiveReady = true;
+ this.logRecoveryStage(dst, 'receive-ready', ` baseSeq=${peer.remoteBaseSeq}`);
this.staleLinkNotifiedAt.delete(dst);
this.resumeReceiveStreams(dst, peer);
}
@@ -3895,6 +4101,7 @@ export class DeviceLinkClient {
}
peer.sendPhase = 'ready';
peer.pendingLinkConfirmation = null;
+ this.logRecoveryStage(dst, 'send-ready');
this.cancelTimeoutCloseNotify(dst);
if (resume.duplicateOpen) {
// 同连接同 stream 的重复 open 仍可能带着未确认的可靠帧。确认阶段
@@ -3946,7 +4153,9 @@ export class DeviceLinkClient {
pending.lastSentAt = 0;
}
}
+ if (peer.recoveryTrace) peer.recoveryTrace.replayThroughSeq = peer.nextSeq - 1;
this.retryPending(dst, { ignoreInterval: true });
+ this.logRecoveryStage(dst, 'first-replay-pass', ` frames=${peer.recoveryFramesSent}`);
this.ensureRetryTimer(dst);
this.logRecoverySend(dst, peer, 'link-replay', false);
}
@@ -3997,6 +4206,7 @@ export class DeviceLinkClient {
+ ` ${this.describeReliableTimeout(dst, seq, peer)}`,
);
this.markPeerLinkDown(peer);
+ this.retryReadRequestsAfterPeerReset(dst, seq);
if (peer.retryTimer) {
clearInterval(peer.retryTimer);
peer.retryTimer = null;
diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.ts
index f4da269228..54f59d381a 100644
--- a/packages/device-link/src/protocol.ts
+++ b/packages/device-link/src/protocol.ts
@@ -58,6 +58,7 @@ export type DeviceLinkErrorCode = RelayErrorCode
| 'CHANNEL_NOT_ALLOWED' // channel 不在远程调用白名单
| 'ACCESS_REVOKED' // 被控端已撤销该控制端的访问权限(逐设备黑名单,被控端本地强制)
| 'INVOKE_TIMEOUT' // 控制端等待 invoke-result 超时
+ | 'PEER_RESET' // peer 传输复位;仅用于可安全重试的幂等读请求
| 'LINK_NOT_OPEN' // 控制链路未建立
| 'NOT_CONNECTED' // 本端尚未连上 relay
| 'BACKPRESSURE' // 本端可靠传输缓冲已满,拒绝继续制造积压
diff --git a/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts
index 8bb575fed7..839bad27b6 100644
--- a/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts
@@ -118,6 +118,9 @@ describe('Feishu parent-chat file reuse', () => {
expect(mocks.createMessage).toHaveBeenCalledTimes(2);
});
+ // Windows starts a fresh PowerShell process and compiles the native helper
+ // for each containment proof. Keep this security regression independent of
+ // the default 5s Vitest timeout on slower hosted runners.
it('proves a Unicode file only through the same pinned directory object chain', async () => {
const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-chain-allowed-'));
const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-chain-outside-'));
@@ -149,7 +152,7 @@ describe('Feishu parent-chat file reuse', () => {
fsSync.closeSync(allowedFd);
fsSync.closeSync(rootFd);
}
- });
+ }, 30_000);
it('rejects a source reached only through an intermediate directory link', async () => {
const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-chain-link-'));
diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.ts
index e9f64aee54..827661d1ce 100644
--- a/packages/lizi-im/src/feishu/outbound.ts
+++ b/packages/lizi-im/src/feishu/outbound.ts
@@ -43,7 +43,10 @@ import type { BotCredentials } from './internal-types.js';
const FEISHU_FILE_SIZE_LIMIT = 30 * 1024 * 1024;
/** 10 MB per image when sending as `msg_type:image`. */
const FEISHU_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
-const HANDLE_PATH_HELPER_TIMEOUT_MS = 5_000;
+// PowerShell's first Add-Type invocation can be slow on hosted Windows
+// runners (Defender scans the generated compiler artifacts). Keep the helper
+// bounded and fail closed, but allow that one-time startup to finish.
+const HANDLE_PATH_HELPER_TIMEOUT_MS = 15_000;
const HANDLE_PATH_HELPER_MAX_BYTES = 256 * 1024;
/**
diff --git a/packages/maker-core/src/memory/manager.scope.test.ts b/packages/maker-core/src/memory/manager.scope.test.ts
index b4d0c9c5fe..2cfd56e627 100644
--- a/packages/maker-core/src/memory/manager.scope.test.ts
+++ b/packages/maker-core/src/memory/manager.scope.test.ts
@@ -14,7 +14,7 @@ import path from 'node:path';
import DatabaseCtor from 'better-sqlite3';
import type Database from 'better-sqlite3';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MakerMemoryManager } from './manager.js';
import { buildBotMemoryScopeKey, memoryScopeDirName } from './storage.js';
@@ -29,6 +29,12 @@ const WORKDIR = 'D:/repo/workdir';
const SCOPE_DIR = memoryScopeDirName(WORKDIR); // Windows: 'D--repo-workdir'
const memoryDirFor = (root: string) => path.join(root, 'maker-memory', SCOPE_DIR);
+// This file opens real better-sqlite3 databases and rebuilds FTS indexes. On
+// Windows runners, Defender can make that synchronous file work exceed
+// Vitest's default 5s timeout; keep the migration assertions unchanged while
+// giving the test the same bounded Windows allowance as the contacts tests.
+vi.setConfig({ testTimeout: process.platform === 'win32' ? 30_000 : 5_000 });
+
let rootA: string;
let rootB: string;
diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.ts
index 0346d862ef..d1975ec65b 100644
--- a/packages/maker-shared/src/__tests__/historyView.test.ts
+++ b/packages/maker-shared/src/__tests__/historyView.test.ts
@@ -243,6 +243,43 @@ describe('shared history view lifecycle', () => {
expect(view.getSnapshot().expanded.size).toBe(0);
});
+ it.each([false, true])('joins an expanded detail read through its latest revision (changed=%s)', async (changed) => {
+ let rows = [row(1, 'thinking', 'old')];
+ const replies: Array<(page: { version: 1; messages: HistoryMessageSource[]; hasMore: false; nextCursor: null }) => void> = [];
+ const details = vi.fn(() => new Promise<Parameters<typeof replies[number]>[0]>(resolve => { replies.push(resolve); }));
+ const view = new HistoryViewController<HistoryMessageSource>({
+ page: async () => ({ version: 1, items: projectHistoryView(rows, true), hasMore: false, nextCursor: null }),
+ details, expanded: async () => undefined,
+ });
+ await view.refresh();
+ const group = view.getSnapshot().items[0];
+ if (group.type !== 'work') throw new Error('Expected a work group');
+ view.setExpanded(group.key, true);
+ let completed = false;
+ const joined = view.loadDetails(group.summary).then(() => { completed = true; });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(completed).toBe(false);
+ expect(details).toHaveBeenCalledTimes(1);
+ if (changed) {
+ rows = [row(1, 'thinking', 'corrected'), row(2, 'thinking', 'appended')];
+ await view.refresh();
+ expect(details).toHaveBeenCalledTimes(1);
+ }
+ replies[0]({ version: 1, messages: [row(1, 'thinking', 'old')], hasMore: false, nextCursor: null });
+ if (changed) {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(completed).toBe(false);
+ expect(details).toHaveBeenCalledTimes(2);
+ replies[1]({ version: 1, messages: rows, hasMore: false, nextCursor: null });
+ }
+ await joined;
+ expect(view.getSnapshot().details.get(group.key)).toMatchObject({ complete: true, loading: false, messages: rows });
+ const latest = view.getSnapshot().items[0];
+ if (latest.type !== 'work') throw new Error('Expected the current work group');
+ await view.loadDetails(latest.summary);
+ expect(details).toHaveBeenCalledTimes(changed ? 2 : 1);
+ });
+
it('reloads an edited prefix when new rows arrive in the same revision', async () => {
let rows = [row(1, 'thinking', 'old'), row(2, 'thinking', 'tail')];
const cursors: Array<string | undefined> = [];
@@ -408,6 +445,28 @@ describe('shared history view lifecycle', () => {
isLive: () => true, build: (rows) => rows.map((item) => item.content), structure: ungroupedStructure });
expect(rendered).toEqual(['complete thinking', 'latest answer']);
});
+
+ it('loads a collapsed work range for recovery without changing expansion state', async () => {
+ const target = row(1, 'thinking', 'authoritative terminal');
+ const details = vi.fn(async () => ({ version: 1 as const, messages: [target], hasMore: false, nextCursor: null }));
+ const view = new HistoryViewController<HistoryMessageSource>({
+ page: async () => ({ version: 1, items: projectHistoryView([target], false), hasMore: false, nextCursor: null }),
+ details,
+ expanded: async () => undefined,
+ });
+ await view.refresh();
+ const group = view.getSnapshot().items[0];
+ if (group.type !== 'work') throw new Error('Expected a work group');
+
+ await view.loadDetails(group.summary, { allowCollapsed: true });
+
+ expect(details).toHaveBeenCalledOnce();
+ expect(view.getSnapshot().expanded).toEqual(new Set());
+ expect(view.getSnapshot().details.get(group.key)).toMatchObject({
+ complete: true,
+ messages: [target],
+ });
+ });
});
diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.ts
index 5f3d02edce..70de136545 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -43,7 +43,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
private generation = 0;
// Transport changes invalidate remote reads, not local disk restoration.
private cacheGeneration = 0;
- private detailRuns = new Map<string, object>();
+ private detailRuns = new Map<string, { promise: Promise<void> }>();
private active = true;
private networkAvailable = true;
private pagePromise: Promise<void> | null = null;
@@ -208,15 +208,19 @@ export class HistoryViewController<T extends HistoryMessageSource> {
});
}
- async loadDetails(summary: HistoryWorkSummary): Promise<void> {
- if (!this.isActive() || !this.state.expanded.has(summary.key) || this.detailRuns.has(summary.key)) return;
+ async loadDetails(summary: HistoryWorkSummary, options?: { allowCollapsed?: boolean }): Promise<void> {
+ const allowCollapsed = options?.allowCollapsed === true;
+ if (!this.isActive() || (!allowCollapsed && !this.state.expanded.has(summary.key))) return;
+ const inFlight = this.detailRuns.get(summary.key);
+ if (inFlight) return inFlight.promise;
const existing = this.state.details.get(summary.key);
if (existing?.complete && existing.revision === summary.revision) return;
- const token = {};
+ const token = { promise: Promise.resolve() };
const generation = this.generation;
this.detailRuns.set(summary.key, token);
const current = () => this.active && generation === this.generation
- && this.detailRuns.get(summary.key) === token && this.state.expanded.has(summary.key);
+ && this.detailRuns.get(summary.key) === token
+ && (allowCollapsed || this.state.expanded.has(summary.key));
// A changed revision may include late edits anywhere in the range, even
// when its endpoint also advances. Keep the old display while rereading.
let collected: T[] = [];
@@ -229,27 +233,30 @@ export class HistoryViewController<T extends HistoryMessageSource> {
this.publish({ details });
};
update({});
- try {
- await readHistoryWorkDetails({
- readPage: (cursor) => this.transport.details(summary, cursor ?? undefined),
- isCurrent: current,
- onPage: (rows) => {
- const incoming = new Set(rows.map((row) => row.clientId));
- collected = [...collected.filter((row) => !incoming.has(row.clientId)), ...rows];
- update({});
- },
- });
- if (current()) update({ loading: false, complete: true });
- } catch (error) {
- if (current()) update({ loading: false, error });
- } finally {
- if (this.detailRuns.get(summary.key) === token) {
- const stillCurrent = current();
- this.detailRuns.delete(summary.key);
- const latest = historyWorkSummaries(this.state.items).find((item) => item.key === summary.key);
- if (stillCurrent && latest && latest.revision !== summary.revision) void this.loadDetails(latest);
+ token.promise = (async () => {
+ try {
+ await readHistoryWorkDetails({
+ readPage: (cursor) => this.transport.details(summary, cursor ?? undefined),
+ isCurrent: current,
+ onPage: (rows) => {
+ const incoming = new Set(rows.map((row) => row.clientId));
+ collected = [...collected.filter((row) => !incoming.has(row.clientId)), ...rows];
+ update({});
+ },
+ });
+ if (current()) update({ loading: false, complete: true });
+ } catch (error) {
+ if (current()) update({ loading: false, error });
+ } finally {
+ if (this.detailRuns.get(summary.key) === token) {
+ const stillCurrent = current();
+ this.detailRuns.delete(summary.key);
+ const latest = historyWorkSummaries(this.state.items).find((item) => item.key === summary.key);
+ if (stillCurrent && latest && latest.revision !== summary.revision) await this.loadDetails(latest);
+ }
}
- }
+ })();
+ return token.promise;
}
/** Locate by visible pages, preserving the original folded aggregate focus behavior. */