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): 断链后恢复远程控制链路 (#1408)
Dashd372a3f9fdb9
diff --git a/apps/desktop/src/main/device-link/__tests__/linkRecovery.test.ts b/apps/desktop/src/main/device-link/__tests__/linkRecovery.test.tsnew file mode 100644index 0000000000..1d3c35c544--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/linkRecovery.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it, vi } from 'vitest';+import { DeviceLinkError } from '@cindy/device-link';+import {+ invokeWithClosedLinkRecovery,+ requiresSessionLink,+} from '../linkRecovery.js';++describe('device-link closed link recovery', () => {+ it('正常成功或不可重试错误不会触发 reopen', async () => {+ const successInvoke = vi.fn().mockResolvedValue({ ok: true });+ const reopen = vi.fn();++ await expect(invokeWithClosedLinkRecovery(successInvoke, reopen)).resolves.toEqual({ ok: true });+ expect(successInvoke).toHaveBeenCalledTimes(1);+ expect(reopen).not.toHaveBeenCalled();++ for (const code of ['NOT_CONNECTED', 'INVOKE_TIMEOUT', 'BACKPRESSURE'] as const) {+ const err = new DeviceLinkError(code, code);+ const failedInvoke = vi.fn().mockRejectedValue(err);+ await expect(invokeWithClosedLinkRecovery(failedInvoke, reopen)).rejects.toBe(err);+ expect(failedInvoke).toHaveBeenCalledTimes(1);+ }+ expect(reopen).not.toHaveBeenCalled();+ });++ it('发送前 LINK_NOT_OPEN 会先 reopen,再且只再 invoke 一次', async () => {+ const closed = new DeviceLinkError('LINK_NOT_OPEN', 'control link is closed');+ const invoke = vi.fn()+ .mockRejectedValueOnce(closed)+ .mockResolvedValueOnce({ ok: true });+ const reopen = vi.fn().mockResolvedValue(undefined);++ await expect(invokeWithClosedLinkRecovery(invoke, reopen)).resolves.toEqual({ ok: true });+ expect(reopen).toHaveBeenCalledTimes(1);+ expect(invoke).toHaveBeenCalledTimes(2);+ expect(invoke.mock.invocationCallOrder[0]).toBeLessThan(reopen.mock.invocationCallOrder[0]);+ expect(reopen.mock.invocationCallOrder[0]).toBeLessThan(invoke.mock.invocationCallOrder[1]);+ });++ it('已发出的请求即使标成 LINK_NOT_OPEN 也不重试', async () => {+ const closed = new DeviceLinkError('LINK_NOT_OPEN', 'late close');+ closed.inFlight = true;+ const invoke = vi.fn().mockRejectedValue(closed);+ const reopen = vi.fn();++ await expect(invokeWithClosedLinkRecovery(invoke, reopen)).rejects.toBe(closed);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(reopen).not.toHaveBeenCalled();+ });++ it('reopen 的撤权错误原样返回,不发送第二次业务 invoke', async () => {+ const closed = new DeviceLinkError('LINK_NOT_OPEN', 'control link is closed');+ const revoked = new DeviceLinkError('ACCESS_REVOKED', 'access revoked');+ const invoke = vi.fn().mockRejectedValue(closed);+ const reopen = vi.fn().mockRejectedValue(revoked);++ await expect(invokeWithClosedLinkRecovery(invoke, reopen)).rejects.toBe(revoked);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(reopen).toHaveBeenCalledTimes(1);+ });++ it('第二次 invoke 失败时不循环 reopen', async () => {+ const firstClosed = new DeviceLinkError('LINK_NOT_OPEN', 'first close');+ const secondClosed = new DeviceLinkError('LINK_NOT_OPEN', 'second close');+ const invoke = vi.fn()+ .mockRejectedValueOnce(firstClosed)+ .mockRejectedValueOnce(secondClosed);+ const reopen = vi.fn().mockResolvedValue(undefined);++ await expect(invokeWithClosedLinkRecovery(invoke, reopen)).rejects.toBe(secondClosed);+ expect(invoke).toHaveBeenCalledTimes(2);+ expect(reopen).toHaveBeenCalledTimes(1);+ });++ it('reopen 后守卫失败会清理链路且不发送第二次 invoke', async () => {+ const closed = new DeviceLinkError('LINK_NOT_OPEN', 'control link is closed');+ const disabled = new Error('[DEVICE_LINK_CONTROL_DISABLED] disabled while reopening');+ const invoke = vi.fn().mockRejectedValueOnce(closed);+ const reopen = vi.fn().mockResolvedValue(undefined);+ const beforeRetry = vi.fn(() => {+ throw disabled;+ });+ const cleanup = vi.fn();++ await expect(+ invokeWithClosedLinkRecovery(invoke, reopen, beforeRetry, cleanup),+ ).rejects.toBe(disabled);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(reopen).toHaveBeenCalledTimes(1);+ expect(beforeRetry).toHaveBeenCalledTimes(1);+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it('只把具体会话或有效文件树 topic 识别为需要 streaming link', () => {+ expect(requiresSessionLink(['sessions'])).toBe(false);+ expect(requiresSessionLink(['session:'])).toBe(false);+ expect(requiresSessionLink(['fs-watch:'])).toBe(false);+ expect(requiresSessionLink(['sessions', 'session:s1'])).toBe(true);+ expect(requiresSessionLink(['fs-watch:C:\\repo'])).toBe(true);+ });+});diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 6674987baa..2b8082955c 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -87,6 +87,10 @@ import {pollContactsDeviceSyncSettingChange,setContactsDeviceLinkOwnerActive,} from '../contacts-sync/driver';+import {+ invokeWithClosedLinkRecovery,+ requiresSessionLink,+} from './linkRecovery';// register.ts 从 device-link/index 导入 setBusyProbe;改用 busyReporter 后在此 re-export 保持其导入不变。export { setBusyProbe };@@ -873,9 +877,17 @@ function assertNotStandby(): void {}}+/** 本机主动关闭对某设备的控制后,所有新建链路与业务调用都必须继续 fail closed。 */+function assertRemoteControlTargetEnabled(deviceId: string): void {+ if (readDeviceLinkSettings().disabledControlDeviceIds.includes(deviceId)) {+ throw new Error('[DEVICE_LINK_CONTROL_DISABLED] device control is disabled locally');+ }+}+/** 控制端:向目标设备发起控制链路(link-open → link-accept) */export async function openRemoteLink(deviceId: string): Promise<LinkAcceptPayload> {assertNotStandby();+ assertRemoteControlTargetEnabled(deviceId);if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');const existing = openLinkInFlight.get(deviceId);if (existing) return existing;@@ -900,6 +912,16 @@ export function closeRemoteLink(deviceId: string): void {client?.closeLink(deviceId, 'user');}+/** 重开期间本地撤权时,撤销已成功建立的临时控制链路,保持 fail-closed。 */+function assertRemoteControlTargetEnabledAfterReopen(deviceId: string): void {+ try {+ assertRemoteControlTargetEnabled(deviceId);+ } catch (err) {+ closeRemoteLink(deviceId);+ throw err;+ }+}+/*** 本机在 device-link 网络中的设备 id(relay ack 下发);未连接 / 未 ack 时 null。* 供会话引用解析等消费方识别「指向本机自己的 deviceId」——深链是可复制的字符串,@@ -918,8 +940,17 @@ export async function remoteInvoke(args: unknown[],): Promise<InvokeResultPayload> {assertNotStandby();- if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');- return client.invoke(deviceId, { channel, args }, INVOKE_TIMEOUT_OVERRIDES_MS[channel]);+ assertRemoteControlTargetEnabled(deviceId);+ const invoke = (): Promise<InvokeResultPayload> => {+ if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');+ return client.invoke(deviceId, { channel, args }, INVOKE_TIMEOUT_OVERRIDES_MS[channel]);+ };+ return invokeWithClosedLinkRecovery(+ invoke,+ () => openRemoteLink(deviceId),+ () => assertRemoteControlTargetEnabled(deviceId),+ () => closeRemoteLink(deviceId),+ );}/**@@ -931,6 +962,12 @@ export async function remoteSubscribe(topics: string[],): Promise<InvokeResultPayload> {assertNotStandby();+ assertRemoteControlTargetEnabled(deviceId);+ if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');+ if (requiresSessionLink(topics) && !client.isLinkReady(deviceId)) {+ await openRemoteLink(deviceId);+ }+ assertRemoteControlTargetEnabledAfterReopen(deviceId);if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');return client.invoke(deviceId, {channel: DL_SUBSCRIBE_CHANNEL,diff --git a/apps/desktop/src/main/device-link/linkRecovery.ts b/apps/desktop/src/main/device-link/linkRecovery.tsnew file mode 100644index 0000000000..f25cd1b175--- /dev/null+++ b/apps/desktop/src/main/device-link/linkRecovery.ts@@ -0,0 +1,45 @@+import { DeviceLinkError, parseFsWatchTopic } from '@cindy/device-link';++/** 打开具体远程会话或文件树监听时必须先建立 streaming link;轻量 sessions 列表订阅不依赖。 */+export function requiresSessionLink(topics: readonly string[]): boolean {+ return topics.some((topic) => (+ (topic.startsWith('session:') && topic.length > 'session:'.length)+ || parseFsWatchTopic(topic) !== null+ ));+}++/**+ * LINK_NOT_OPEN 由 DeviceLinkClient 在真正发帧前抛出,因此可先重开链路再重试一次。+ * 已经发出的请求或其它错误绝不重试,避免 enqueue / send 等写操作重复执行。+ */+export async function invokeWithClosedLinkRecovery<T>(+ invoke: () => Promise<T>,+ reopen: () => Promise<unknown>,+ beforeRetry?: () => void,+ onRetryGuardFailure?: () => void,+): Promise<T> {+ try {+ return await invoke();+ } catch (err) {+ if (+ !(err instanceof DeviceLinkError)+ || err.code !== 'LINK_NOT_OPEN'+ || err.inFlight === true+ ) {+ throw err;+ }+ }++ await reopen();+ try {+ beforeRetry?.();+ } catch (err) {+ try {+ onRetryGuardFailure?.();+ } catch {+ // 清理是 best-effort;保留撤权守卫错误作为调用方可见结果。+ }+ throw err;+ }+ return invoke();+}diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 107272d8c9..61059790a6 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -894,7 +894,18 @@ describe('DeviceLinkClient', () => {},});await open;+ expect(h.client.isLinkReady('dev-b')).toBe(true);h.client.closeLink('dev-b', 'user');+ expect(h.client.isLinkReady('dev-b')).toBe(false);++ const sentBeforeBlockedInvoke = h.current().sent.length;+ const blockedInvoke = await h.client.invoke(+ 'dev-b',+ { channel: 'maker:send', args: [] },+ ).catch((err: unknown) => err);+ expect(blockedInvoke).toMatchObject({ code: 'LINK_NOT_OPEN' });+ expect((blockedInvoke as DeviceLinkError).inFlight).not.toBe(true);+ expect(h.current().sent).toHaveLength(sentBeforeBlockedInvoke);const listing = h.client.invoke('dev-b', { channel: 'local-db:sessions:list', args: [] });const sentListing = h.current().sent.at(-1)!;@@ -916,6 +927,54 @@ describe('DeviceLinkClient', () => {h.client.stop();});+ it('显式 close 后只放行已接收的 legacy listing invoke-result 回程', async () => {+ const h = makeHarness({ timing: { pingIntervalMs: 1_000 } });+ h.client.start();+ await tick();+ h.current().ack();+ await establishInboundReliableLink(h, 'controller-stream');+ h.client.closeLink('dev-b', 'toggle-off');++ h.client.onFrame((env) => {+ if (+ env.kind !== 'invoke'+ || env.id !== 'listing-after-close'+ || env.src !== 'dev-b'+ ) return;+ h.client.sendInvokeResult(env.src, env.id, {+ ok: true,+ result: ['session-after-close'],+ });+ });+ h.current().push({+ v: PROTOCOL_VERSION,+ kind: 'invoke',+ id: 'listing-after-close',+ src: 'dev-b',+ payload: { channel: 'local-db:sessions:list', args: [] },+ });+ await tick();++ const response = h.current().sent.find((env) => (+ env.kind === 'invoke-result' && env.id === 'listing-after-close'+ ));+ expect(response).toMatchObject({+ kind: 'invoke-result',+ dst: 'dev-b',+ payload: { ok: true, result: ['session-after-close'] },+ });+ expect(parseTransportPayload(response?.payload)).toBeNull();+ expect(() => h.client.sendInvokeResult('dev-b', 'unknown-request', {+ ok: true,+ result: null,+ })).toThrow(expect.objectContaining({ code: 'LINK_NOT_OPEN' }));+ expect(() => h.client.sendInvokeResult('dev-b', 'listing-after-close', {+ ok: true,+ result: null,+ })).toThrow(expect.objectContaining({ code: 'LINK_NOT_OPEN' }));+ h.client.stop();+ });+it('对端进程重启后按握手给出的 transportBaseSeq 接续,不等待已确认旧 seq', async () => {const h = makeHarness({ timing: { pingIntervalMs: 1_000 } });h.client.start();diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex a84e9a5eb1..f3e107f10d 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -45,6 +45,7 @@ const SLOW_REQUEST_WARN_MS = 1_000;const MAX_LEGACY_INBOUND_FRAMES = 128;const MAX_LEGACY_INBOUND_BYTES = 16 * 1024 * 1024;const MAX_PENDING_INBOUND_LINK_OFFERS = 64;+const MAX_UNLINKED_LEGACY_RESPONSE_IDS = 128;type DeviceLinkCrypto = {randomUUID?: () => string;@@ -262,6 +263,8 @@ interface PeerTransportState {reliable: boolean;linkReady: boolean;explicitlyClosed: boolean;+ /** 显式关闭后收到的 allowlisted legacy invoke;只放行与 requestId 配对的一次回程。 */+ unlinkedLegacyResponseIds: Set<string>;pending: Map<number, PendingReliableMessage>;pendingBytes: number;retryTimer: ReturnType<typeof setInterval> | null;@@ -462,6 +465,11 @@ export class DeviceLinkClient {return this.status;}+ /** 目标设备是否已完成 link-open / link-accept,可安全进入 streaming tier。 */+ isLinkReady(dst: string): boolean {+ return this.peerTransport.get(dst)?.linkReady === true;+ }+onStatusChange(cb: (s: DeviceLinkStatus) => void): () => void {this.statusHandlers.add(cb);return () => this.statusHandlers.delete(cb);@@ -550,6 +558,7 @@ export class DeviceLinkClient {if (peer) {peer.linkReady = false;peer.explicitlyClosed = true;+ peer.unlinkedLegacyResponseIds.clear();// 显式关闭只撤掉 streaming 可靠层。listing / topic 控制帧仍不依赖// link-open,后续应回退到 legacy,而不是被统一挡成 LINK_NOT_OPEN。peer.reliable = false;@@ -586,7 +595,13 @@ export class DeviceLinkClient {/** 被控端:回 invoke-result(对应入站 invoke 的 id) */sendInvokeResult(dst: string, requestId: string, payload: InvokeResultPayload): void {- this.sendPeerEnvelope({ v: PROTOCOL_VERSION, kind: 'invoke-result', id: requestId, dst, payload });+ const peer = this.peerTransport.get(dst);+ const allowClosedLegacyResponse = peer?.unlinkedLegacyResponseIds.has(requestId) === true;+ this.sendPeerEnvelope(+ { v: PROTOCOL_VERSION, kind: 'invoke-result', id: requestId, dst, payload },+ allowClosedLegacyResponse,+ );+ if (allowClosedLegacyResponse) peer?.unlinkedLegacyResponseIds.delete(requestId);}/** 被控端:回 link-accept */@@ -1355,6 +1370,7 @@ export class DeviceLinkClient {const peer = this.getPeerTransport(env.src);peer.linkReady = false;peer.explicitlyClosed = true;+ peer.unlinkedLegacyResponseIds.clear();// 对端关闭与本地 closeLink 语义对称:撤掉 streaming 可靠层,// 后续不依赖 link-open 的 listing/control invoke 可回退 legacy。peer.reliable = false;@@ -1362,6 +1378,16 @@ export class DeviceLinkClient {peer.remoteBaseSeq = 1;peer.receive.clear();this.abandonReliablePending(env.src, 'control link closed by peer');+ } else if (+ env.kind === 'invoke'+ && env.src+ && env.id+ && isUnlinkedLegacyEnvelope(env)+ ) {+ const peer = this.getPeerTransport(env.src);+ if (peer.explicitlyClosed && !peer.linkReady) {+ this.rememberUnlinkedLegacyResponse(peer, env.id);+ }}return this.emitFrame(env);}@@ -1668,13 +1694,18 @@ export class DeviceLinkClient {);}- private sendPeerEnvelope(env: Envelope): boolean {+ private sendPeerEnvelope(env: Envelope, allowClosedLegacyResponse = false): boolean {if (!env.dst || !isReliableKind(env.kind)) {this.sendEnvelope(env);return false;}const peer = this.getPeerTransport(env.dst);- if (peer.explicitlyClosed && !peer.linkReady && !isUnlinkedLegacyEnvelope(env)) {+ if (+ peer.explicitlyClosed+ && !peer.linkReady+ && !isUnlinkedLegacyEnvelope(env)+ && !allowClosedLegacyResponse+ ) {throw new DeviceLinkError('LINK_NOT_OPEN', 'control link is closed');}if (!peer.reliable) {@@ -1848,6 +1879,7 @@ export class DeviceLinkClient {reliable: false,linkReady: false,explicitlyClosed: false,+ unlinkedLegacyResponseIds: new Set(),pending: new Map(),pendingBytes: 0,retryTimer: null,@@ -1860,6 +1892,16 @@ export class DeviceLinkClient {return peer;}+ private rememberUnlinkedLegacyResponse(peer: PeerTransportState, requestId: string): void {+ peer.unlinkedLegacyResponseIds.delete(requestId);+ peer.unlinkedLegacyResponseIds.add(requestId);+ while (peer.unlinkedLegacyResponseIds.size > MAX_UNLINKED_LEGACY_RESPONSE_IDS) {+ const oldest = peer.unlinkedLegacyResponseIds.values().next().value as string | undefined;+ if (!oldest) break;+ peer.unlinkedLegacyResponseIds.delete(oldest);+ }+ }+private getReceiveStream(peer: PeerTransportState,streamId: string,