Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 被控端弱网收尾——link-accept 重试 + outbox 事件驱动 + 逐 channel TTL (#1477)
Dashacac14a6b1c5
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.tsnew file mode 100644index 0000000000..54ac196c05--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts@@ -0,0 +1,238 @@+/**+ * dispatchWeakNetwork.test.ts — 被控端弱网收尾行为契约。+ * -------------------------------------------------------------------------+ * 三条不变量(2026-08-03 弱网实测暴露):+ * 1. link-accept 发送失败(WS 背压)不再静默放弃:短退避有限重试,重试前+ * 复验开关/连接,成功才提交订阅;耗尽/断线/新 open 都会终止旧重试。+ * 2. invoke-result outbox 在 relay 离线期间不自旋:不 trySend、不刷日志,+ * 只做慢速 TTL 出清;ws-online 事件触发立即投递。+ * 3. outbox 条目保留时长按 channel 的控制端等待预算收窄(×2,封顶全局+ * 120s):控制端早已超时放弃的回包不再白占两分钟配额。+ * mock 面与 dispatchSendSafety.test.ts 一致:只 mock electron + settings。+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { DeviceLinkError } from '@cindy/device-link';++vi.mock('electron', () => ({+ app: {+ getAppPath: () => '/tmp/xdt-maker-test/app',+ getPath: () => '/tmp/xdt-maker-test',+ getVersion: () => '0.0.0-test',+ },+ powerSaveBlocker: { start: () => 0, stop: () => {}, isStarted: () => false },+ nativeImage: { createFromPath: () => ({ isEmpty: () => true }) },+}));+const deviceLinkSettings = vi.hoisted(() => ({+ value: {+ remoteControlEnabled: true,+ revokedControllers: [] as string[],+ },+}));++vi.mock('../settings-store', () => ({+ readDeviceLinkSettings: () => deviceLinkSettings.value,+}));++import { __testing, flushRemoteInvokeResultOutboxOnReconnect } from '../dispatch';++function mkClient(+ over: Partial<{+ getStatus: ReturnType<typeof vi.fn>;+ sendInvokeResult: ReturnType<typeof vi.fn>;+ sendLinkAccept: ReturnType<typeof vi.fn>;+ }> = {},+) {+ return {+ getStatus: over.getStatus ?? vi.fn(() => 'online'),+ sendInvokeResult: over.sendInvokeResult ?? vi.fn(),+ sendLinkAccept: over.sendLinkAccept ?? vi.fn(),+ closeLink: vi.fn(),+ onFrame: vi.fn(),+ sendPush: vi.fn(),+ };+}++const backpressure = () => new DeviceLinkError('BACKPRESSURE', 'websocket send buffer is full');+const notConnected = () => new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');++beforeEach(() => {+ vi.useFakeTimers();+ deviceLinkSettings.value = {+ remoteControlEnabled: true,+ revokedControllers: [],+ };+ __testing.reset();+});++afterEach(() => {+ vi.useRealTimers();+});++describe('[1] link-accept 发送失败的有限重试', () => {+ it('背压首发失败 → 不提交订阅;500ms 重试成功后才提交', () => {+ const sendLinkAccept = vi.fn().mockImplementationOnce(() => {+ throw backpressure();+ });+ const client = mkClient({ sendLinkAccept });+ __testing.setActiveClient(client as never);++ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-1', undefined);+ expect(sendLinkAccept).toHaveBeenCalledTimes(1);+ // 失败即返回:订阅未提交(幽灵订阅防护),留下一个待触发的重试+ expect(__testing.getActiveControllers()).toHaveLength(0);+ expect(__testing.pendingLinkAcceptRetryCount()).toBe(1);++ vi.advanceTimersByTime(500);+ expect(sendLinkAccept).toHaveBeenCalledTimes(2);+ expect(sendLinkAccept).toHaveBeenLastCalledWith('ctrl-a', 'open-1', expect.anything());+ // 第二次成功:订阅提交,无遗留重试+ expect(__testing.getActiveControllers().map((c) => c.deviceId)).toEqual(['ctrl-a']);+ expect(__testing.pendingLinkAcceptRetryCount()).toBe(0);+ });++ it('持续背压:按 500ms/1s/2s 重试三次后放弃,回到「等控制端重开」', () => {+ const sendLinkAccept = vi.fn(() => {+ throw backpressure();+ });+ const client = mkClient({ sendLinkAccept });+ __testing.setActiveClient(client as never);++ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-1', undefined);+ expect(sendLinkAccept).toHaveBeenCalledTimes(1);+ vi.advanceTimersByTime(500);+ expect(sendLinkAccept).toHaveBeenCalledTimes(2);+ vi.advanceTimersByTime(1_000);+ expect(sendLinkAccept).toHaveBeenCalledTimes(3);+ vi.advanceTimersByTime(2_000);+ expect(sendLinkAccept).toHaveBeenCalledTimes(4);+ // 耗尽:不再有排期+ expect(__testing.pendingLinkAcceptRetryCount()).toBe(0);+ vi.advanceTimersByTime(60_000);+ expect(sendLinkAccept).toHaveBeenCalledTimes(4);+ expect(__testing.getActiveControllers()).toHaveLength(0);+ });++ it('重试等待期间新 link-open 到达:旧重试被顶掉,只按新 requestId 回 accept', () => {+ const sendLinkAccept = vi+ .fn()+ .mockImplementationOnce(() => {+ throw backpressure();+ });+ const client = mkClient({ sendLinkAccept });+ __testing.setActiveClient(client as never);++ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-old', undefined);+ expect(__testing.pendingLinkAcceptRetryCount()).toBe(1);+ // 控制端超时重发:新 requestId 立即处理成功+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-new', undefined);+ expect(sendLinkAccept).toHaveBeenLastCalledWith('ctrl-a', 'open-new', expect.anything());+ expect(__testing.pendingLinkAcceptRetryCount()).toBe(0);+ // 旧重试不再触发+ vi.advanceTimersByTime(10_000);+ expect(sendLinkAccept).toHaveBeenCalledTimes(2);+ });++ it('重试触发时 relay 已断线 / 开关已关闭:放弃,不发 accept', () => {+ // 首发路径不查询连接状态;第一次 getStatus 调用发生在重试回调的世代校验里+ const getStatus = vi.fn(() => 'connecting');+ const sendLinkAccept = vi.fn(() => {+ throw backpressure();+ });+ const client = mkClient({ sendLinkAccept, getStatus: getStatus as never });+ __testing.setActiveClient(client as never);+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-1', undefined);+ expect(sendLinkAccept).toHaveBeenCalledTimes(1);+ vi.advanceTimersByTime(500); // 触发时 getStatus() = 'connecting' → 放弃+ expect(sendLinkAccept).toHaveBeenCalledTimes(1);++ // 开关关闭场景:重试走完整 handleLinkOpen,复验后拒绝+ __testing.reset();+ const sendLinkAccept2 = vi.fn(() => {+ throw backpressure();+ });+ const client2 = mkClient({ sendLinkAccept: sendLinkAccept2 });+ __testing.setActiveClient(client2 as never);+ __testing.handleLinkOpen(client2 as never, 'ctrl-b', 'open-2', undefined);+ deviceLinkSettings.value = { remoteControlEnabled: false, revokedControllers: [] };+ vi.advanceTimersByTime(500);+ expect(sendLinkAccept2).toHaveBeenCalledTimes(1); // 复验失败,不再尝试发送+ });+});++describe('[2] outbox 离线不自旋,上线事件驱动投递', () => {+ it('relay 离线期间 flush 不 trySend;ws-online 触发立即投递', () => {+ let status = 'connecting';+ const sendInvokeResult = vi.fn().mockImplementationOnce(() => {+ throw notConnected();+ });+ const client = mkClient({+ sendInvokeResult,+ getStatus: vi.fn(() => status) as never,+ });+ __testing.setActiveClient(client as never);++ // 首发失败入 outbox(此时 relay 离线)+ expect(+ __testing.sendInvokeResultSafe(+ client as never,+ 'ctrl-a',+ 'req-1',+ { ok: true, result: 1 },+ 'local-db:sessions:list',+ ),+ ).toBe(true);+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);+ expect(sendInvokeResult).toHaveBeenCalledTimes(1);++ // 离线期间多轮慢扫描:不再尝试发送(无 NOT_CONNECTED 自旋)+ vi.advanceTimersByTime(20_000);+ expect(sendInvokeResult).toHaveBeenCalledTimes(1);+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);++ // 上线事件:立即投递成功+ status = 'online';+ flushRemoteInvokeResultOutboxOnReconnect();+ expect(sendInvokeResult).toHaveBeenCalledTimes(2);+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(0);+ });+});++describe('[3] outbox 保留时长按 channel 收窄', () => {+ it('默认 channel = 60s;放宽表 channel ×2 封顶 120s', () => {+ expect(__testing.outboxEntryMaxAgeMs('local-db:sessions:list')).toBe(60_000);+ expect(__testing.outboxEntryMaxAgeMs(undefined)).toBe(60_000);+ expect(__testing.outboxEntryMaxAgeMs('worktree:create')).toBe(120_000);+ });++ it('离线慢扫描按逐条 TTL 出清:默认 channel 61s 被丢,长任务 channel 保留', () => {+ const sendInvokeResult = vi.fn(() => {+ throw notConnected();+ });+ const client = mkClient({+ sendInvokeResult,+ getStatus: vi.fn(() => 'connecting') as never,+ });+ __testing.setActiveClient(client as never);+ __testing.sendInvokeResultSafe(+ client as never,+ 'ctrl-a',+ 'req-listing',+ { ok: true, result: 1 },+ 'local-db:sessions:list',+ );+ __testing.sendInvokeResultSafe(+ client as never,+ 'ctrl-a',+ 'req-worktree',+ { ok: true, result: 2 },+ 'worktree:create',+ );+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(2);++ vi.advanceTimersByTime(61_000);+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1); // listing 出清,worktree 保留++ vi.advanceTimersByTime(60_000);+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(0); // 121s:worktree 也到期+ });+});diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 01bac14057..c6e85a66f9 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -414,12 +414,31 @@ const REMOTE_INVOKE_RESULT_OUTBOX_PER_CONTROLLER_LIMIT = 16;const REMOTE_INVOKE_RESULT_OUTBOX_BYTES = 16 * 1024 * 1024;const REMOTE_INVOKE_RESULT_OUTBOX_PER_CONTROLLER_BYTES = 4 * 1024 * 1024;const REMOTE_INVOKE_RESULT_OUTBOX_RETRY_MS = 500;+/**+ * relay 离线期间 outbox 不再按 500ms 盲自旋(每轮对每个 peer trySend → 必然抛+ * NOT_CONNECTED,空转最长两分钟、日志噪音掩盖真问题):离线时只按慢节奏做 TTL+ * 出清,真正的投递由事件驱动 —— ws-online 全量 flush(index.ts 接线)、link-open /+ * subscribe 定向 flush(已有)。+ */+const REMOTE_INVOKE_RESULT_OUTBOX_OFFLINE_SWEEP_MS = 5_000;const REMOTE_INVOKE_MAX_CLIENT_WAIT_MS = Math.max(30_000,...Object.values(INVOKE_TIMEOUT_OVERRIDES_MS),);-/** 再保留一轮同等重连窗口后才放弃无人等待的回包。 */+/** 再保留一轮同等重连窗口后才放弃无人等待的回包(全局上限;逐条按 channel 收窄)。 */const REMOTE_INVOKE_RESULT_OUTBOX_MAX_AGE_MS = REMOTE_INVOKE_MAX_CLIENT_WAIT_MS * 2;++/**+ * outbox 条目的逐 channel 保留时长:控制端对该 channel 的等待预算(两端共享+ * INVOKE_TIMEOUT_OVERRIDES_MS,缺省 30s)× 2(再留一轮重连窗口),封顶全局上限。+ * 控制端超时后不会再认领旧 requestId 的回包(重发用新 id),listing 类回包在+ * 弱网时段最多占 outbox 两分钟纯属浪费配额;长任务 channel(60s 预算)自动保留+ * 更久。控制端可能配置更短的超时(mobile 15s),推断值只偏保守、不早丢。+ */+function outboxEntryMaxAgeMs(channel: string | undefined): number {+ const budgetMs = (channel && INVOKE_TIMEOUT_OVERRIDES_MS[channel]) || 30_000;+ return Math.min(budgetMs * 2, REMOTE_INVOKE_RESULT_OUTBOX_MAX_AGE_MS);+}/*** ipcMain handler 没有统一 AbortSignal,不能在 30s 客户端超时时假装取消副作用。* 这里只在远超控制端等待窗后回收本地 bookkeeping;底层 Promise 仍带 catch 并允许自行收尾。@@ -864,6 +883,7 @@ export function dropAllControllers(acceptedLinkControllers.clear();offlinePushQueue.clear();clearAllSessionActivityStages();+ cancelAllLinkAcceptRetries();syncForwarding();}@@ -876,6 +896,7 @@ export function dropAllControllers(export function handleControllerOffline(deviceId: string): void {acceptedLinkControllers.delete(deviceId);clearSessionActivityStage(deviceId);+ cancelLinkAcceptRetry(deviceId);if (subscriptions.clearController(deviceId)) {syncForwarding();}@@ -890,6 +911,7 @@ export function forgetControllerInvokeState(deviceId: string): void {export function purgeRevokedController(deviceId: string): void {offlinePushQueue.clear(deviceId);clearSessionActivityStage(deviceId);+ cancelLinkAcceptRetry(deviceId);subscriptions.forgetKnownController(deviceId);topicSubscriptionControllers.delete(deviceId);acceptedLinkControllers.delete(deviceId);@@ -935,6 +957,7 @@ async function handleFrame(client: DeviceLinkClient, env: Envelope): Promise<voiclearRemoteInvokeStateFor(src);offlinePushQueue.clear(src);clearSessionActivityStage(src);+ cancelLinkAcceptRetry(src);acceptedLinkControllers.delete(src);// Keep the protocol-capability marker, but discard all remembered routing.// A modern controller must reconnect and explicitly subscribe; restoring the@@ -959,12 +982,65 @@ function isControllerRevoked(deviceId: string): boolean {return readDeviceLinkSettings().revokedControllers.includes(deviceId);}+/**+ * link-accept 发送失败(WS 背压 / 瞬时 socket 竞态)的有限重试。+ *+ * 控制端的 openLink 正拿着 30s 预算干等 accept;此前发送失败直接静默放弃,+ * 控制端必然等满超时再靠订阅重放/熔断恢复兜底重开(2026-08-03 线上现场:+ * 被控端上行拥塞时反复出现 no link-accept within 30000ms)。背压是瞬时状态,+ * 短退避内发送缓冲大概率已排空;重试走完整 handleLinkOpen(复验开关/撤权),+ * 每 src 只保留最新一次(新 link-open 顶掉旧重试)。耗尽后回到原语义:+ * 等控制端重发 link-open。+ */+const LINK_ACCEPT_RETRY_DELAYS_MS: readonly number[] = [500, 1_000, 2_000];+const linkAcceptRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();++function cancelLinkAcceptRetry(src: string): void {+ const timer = linkAcceptRetryTimers.get(src);+ if (!timer) return;+ clearTimeout(timer);+ linkAcceptRetryTimers.delete(src);+}++function cancelAllLinkAcceptRetries(): void {+ for (const src of [...linkAcceptRetryTimers.keys()]) cancelLinkAcceptRetry(src);+}++/** @param failedAttempts 已失败的发送次数(≥1);第 n 次失败用 delays[n-1] 档退避。 */+function scheduleLinkAcceptRetry(+ client: DeviceLinkClient,+ src: string,+ requestId: string,+ payload: LinkOpenPayload | undefined,+ failedAttempts: number,+): void {+ if (failedAttempts > LINK_ACCEPT_RETRY_DELAYS_MS.length) {+ log.warn(+ `link-accept to ${shortId(src)} gave up after ${failedAttempts} attempts; waiting for controller to re-open`,+ );+ return;+ }+ cancelLinkAcceptRetry(src);+ const timer = setTimeout(() => {+ linkAcceptRetryTimers.delete(src);+ // 世代/连接校验:client 已更换或 relay 已断线时放弃——断线会 fail 掉控制端+ // 的 pending openLink,它必然重发 link-open,旧 requestId 的 accept 已无意义。+ if (activeClient !== client || client.getStatus() !== 'online') return;+ handleLinkOpen(client, src, requestId, payload, failedAttempts);+ }, LINK_ACCEPT_RETRY_DELAYS_MS[failedAttempts - 1]);+ (timer as unknown as { unref?: () => void }).unref?.();+ linkAcceptRetryTimers.set(src, timer);+}+function handleLinkOpen(client: DeviceLinkClient,src: string,requestId: string,payload: LinkOpenPayload | undefined,+ acceptAttempt = 0,): void {+ // 同 src 的新 link-open / 本轮执行顶掉遗留的 accept 重试(requestId 已过时)+ cancelLinkAcceptRetry(src);// 第二道开关校验(server 已是第一道)if (!readDeviceLinkSettings().remoteControlEnabled) {// server 正常不会转发到这里;真到了说明状态不一致,静默不 accept@@ -992,10 +1068,20 @@ function handleLinkOpen(|| rememberedModernTopics;// 先确认 link-accept 已经进入 socket/可靠层,再提交本地订阅状态。弱网背压下// accept 发送失败时不能留下“控制端未连上、被控端却显示已受控”的幽灵订阅。- client.sendLinkAccept(src, requestId, {- appVersion: app.getVersion(),- allowlistHash: computeAllowlistHash(),- });+ try {+ client.sendLinkAccept(src, requestId, {+ appVersion: app.getVersion(),+ allowlistHash: computeAllowlistHash(),+ });+ } catch (err) {+ // 背压等瞬时失败:短退避重试(见 LINK_ACCEPT_RETRY_DELAYS_MS 注释),+ // 订阅状态不提交(幽灵订阅防护语义保持不变)。+ log.warn(+ `link-accept send failed for ${shortId(src)} (attempt ${acceptAttempt + 1}): ${String(err)}`,+ );+ scheduleLinkAcceptRetry(client, src, requestId, payload, acceptAttempt + 1);+ return;+ }acceptedLinkControllers.add(src);if (knownModernController) {subscriptions.updateControllerMetadata(src, name, capabilities);@@ -1527,24 +1613,37 @@ function clearRemoteInvokeResultOutboxTimer(): void {function scheduleRemoteInvokeResultOutboxFlush(): void {if (remoteInvokeResultOutboxTimer || remoteInvokeResultOutbox.size === 0) return;+ // relay 在线才值得 500ms 快重试;离线只保留慢节奏 TTL 出清,投递由事件驱动+ // (ws-online 全量 / link-open、subscribe 定向)。+ const delayMs = activeClient?.getStatus() === 'online'+ ? REMOTE_INVOKE_RESULT_OUTBOX_RETRY_MS+ : REMOTE_INVOKE_RESULT_OUTBOX_OFFLINE_SWEEP_MS;remoteInvokeResultOutboxTimer = setTimeout(() => {remoteInvokeResultOutboxTimer = null;flushRemoteInvokeResultOutbox();- }, REMOTE_INVOKE_RESULT_OUTBOX_RETRY_MS);+ }, delayMs);(remoteInvokeResultOutboxTimer as unknown as { unref?: () => void }).unref?.();}+/** ws-online 等连接级事件的全量 flush 入口(index.ts 接线);挂起的慢扫描立即换快挡。 */+export function flushRemoteInvokeResultOutboxOnReconnect(): void {+ if (remoteInvokeResultOutbox.size === 0) return;+ clearRemoteInvokeResultOutboxTimer();+ flushRemoteInvokeResultOutbox();+}+function flushRemoteInvokeResultOutbox(onlySrc?: string): void {const client = activeClient;if (!client) {scheduleRemoteInvokeResultOutboxFlush();return;}+ const relayOnline = client.getStatus() === 'online';const now = Date.now();const blockedPeers = new Set<string>();for (const [key, queued] of remoteInvokeResultOutbox) {if (onlySrc && queued.src !== onlySrc) continue;- if (now - queued.queuedAt >= REMOTE_INVOKE_RESULT_OUTBOX_MAX_AGE_MS) {+ if (now - queued.queuedAt >= outboxEntryMaxAgeMs(queued.channel)) {log.warn(`dropping expired invoke-result outbox entry for ${queued.channel ?? '?'} ` +`to ${shortId(queued.src)}`,@@ -1552,6 +1651,8 @@ function flushRemoteInvokeResultOutbox(onlySrc?: string): void {removeRemoteInvokeResultOutboxEntry(key);continue;}+ // 离线轮只做上面的 TTL 出清:trySend 必然 NOT_CONNECTED,不空转、不刷日志。+ if (!relayOnline) continue;if (blockedPeers.has(queued.src)) continue;const attempt = trySendInvokeResult(client,@@ -2138,6 +2239,7 @@ export const __testing = {activeClient = null;offlinePushQueue.clear();clearAllSessionActivityStages();+ cancelAllLinkAcceptRetries();setBroadcastTapListener(null);},getActiveControllers,@@ -2154,6 +2256,9 @@ export const __testing = {remoteInvokeResultOutboxPerControllerLimit: REMOTE_INVOKE_RESULT_OUTBOX_PER_CONTROLLER_LIMIT,remoteInvokeResultOutboxSize: () => remoteInvokeResultOutbox.size,flushRemoteInvokeResultOutbox,+ outboxEntryMaxAgeMs,+ linkAcceptRetryDelaysMs: LINK_ACCEPT_RETRY_DELAYS_MS,+ pendingLinkAcceptRetryCount: () => linkAcceptRetryTimers.size,forwardPush,queuedPushesFor(deviceId: string) {return offlinePushQueue.snapshot(deviceId);diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 3cc29c801b..c4c66555de 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -60,6 +60,7 @@ import {setControllersChangedListener,setRemoteInvokeBusyChangedListener,dropAllControllers,+ flushRemoteInvokeResultOutboxOnReconnect,forgetControllerInvokeState,handleControllerOffline,purgeRevokedController,@@ -390,7 +391,12 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vif (status !== 'online') presenceOnlineByDevice.clear();broadcast(DEVICE_LINK_PUSH.STATUS_CHANGED, { status });handleContactsDeviceLinkStatusChanged(status === 'online');- if (status === 'online') replayActiveSubscriptions('ws-online');+ if (status === 'online') {+ replayActiveSubscriptions('ws-online');+ // 重连即投递被控端积压的 invoke-result:离线期间 outbox 只做慢速 TTL 出清,+ // 不再自旋重试,上线事件是它的主投递触发点。+ flushRemoteInvokeResultOutboxOnReconnect();+ }});// 连接问题(鉴权失效/被顶号/超限/版本不符)→ 推给 renderer,让设置页与// 远程会话 banner 能把「一直重连」的真实原因说清楚,而不是笼统的 connecting。