Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(device-link): add direct-first routing with relay fallback
MagicLizi09b99a31b937
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex c44f3be941..3789927413 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -108,6 +108,32 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即一起打掉线,由 #1405 收窄止损半径修复。协议兼容、allowlist、单测三层防线对这类问题全部免疫,只有 review 时点名问「半径」才拦得住。+### 直连优先、中继兜底(同账号设备)++产品要求:Device Link 的设备间功能(含手机)在两端已授权、网络实际可达时优先直连,+直连失败、超时或中途断开时自动改走 relay,不能让功能卡住,也不能重复执行命令。+选路与兜底在 `packages/device-link` 统一实现(`directPath.ts` 与 `DeviceLinkClient`),+平台只负责建立通道并调用 `attachDirectPath`。++- **分工**:relay 仍是控制面——登录、在线状态、账号归属、link-open/accept/close、+ 链路确认 ACK 都只走 relay。直连只承载已建立可靠链路上的 reliable-transport 帧+ (invoke / invoke-result / push)及普通累计 ACK。可靠层按 seq 去重、按序交付,+ 同一条消息经两条路径各到一次也只执行一次。+- **授权**:直连帧的来源取自通道绑定的设备,不信任帧内 `src`;被控端照常逐条复验+ 被控开关、撤权名单与 allowlist。共享任务、供应商分享等跨账号范围不走直连,逐帧+ 授权仍由 relay 执行。relay 报告对端离线(含被移出账号)、链路被关闭或撤权、客户端+ 停止时立即撤下直连。ACK 原路返回,单向失效时发送端不会被困在直连上。+- **故障半径三问**:① 故障层级是单个 peer 的直连通道(通道关闭、写入失败、经直连+ 发出的帧过了重发期限仍未确认);② 动作只撤下这一台设备的直连,把它仍未确认的帧+ 恢复为未发送、按 relay 既有恢复预算(先探测一批、收到 ACK 再继续)重发,不重连+ relay、不重建链路,直连的失败不消耗 relay 的重试次数;③ 回归见+ `packages/device-link/src/__tests__/client.test.ts`「直连优先、中继兜底」:两个控制端+ 共用同一被控端,其中一个的直连静默,断言命令只执行一次、结果经 relay 送达,另一个+ 控制端仍走直连、在途请求与 relay 连接不受影响。+- **范围**:本阶段只有连接层选路与兜底,没有平台接入通道时行为与改动前完全相同,+ 也没有 wire 变更。relay 断线期间链路随之复位,直连暂不单独维持链路。Desktop 与+ Mobile 经已授权信令建立 WebRTC 直连、手机局域网权限等平台接入另行实现。+## 远程 Agent 的拉取与恢复(`maker:remote-agent:v1`)协议见 [`protocol-compatibility.md`](protocol-compatibility.md)「远程 Agent」。恢复策略按故障半径三问:diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 2ed609c4ac..c8116bd74b 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -39,6 +39,11 @@ import { resolveRemoteInvokeTimeoutMs } from '../invokePolicy.js';import { SESSION_ACTIVITY_CHANNEL } from '../topics.js';import { resolveDesktopIceServers, REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS } from '../remoteDesktopIceConfig.js';import { REMOTE_DESKTOP_ICE_SERVERS } from '../remoteDesktopIce.js';+import type {+ DeviceLinkDirectChannel,+ DeviceLinkDirectPathHandle,+ DeviceLinkPeerPathChanged,+} from '../directPath.js';type Handler = (...args: unknown[]) => void;@@ -10482,3 +10487,185 @@ it('stops automatic reconnect after device removal and permits a new login lifecexpect(h.client.getConnectionIssue()).toBeNull();h.client.stop();});++/**+ * 两台设备之间的内存直连通道(模拟 WebRTC DataChannel)。每个方向可单独静默丢帧,+ * 模拟直连半死;任一端关闭后另一端随即收到 closed()。+ */+function connectDirect(+ left: { id: string; client: DeviceLinkClient },+ right: { id: string; client: DeviceLinkClient },+) {+ const drop = { toLeft: false, toRight: false };+ const failSend = { left: false, right: false };+ const frames = { toLeft: [] as Envelope[], toRight: [] as Envelope[] };+ const closeReasons: string[] = [];+ let open = true;+ const handles: { left?: DeviceLinkDirectPathHandle; right?: DeviceLinkDirectPathHandle } = {};+ const channel = (from: 'left' | 'right'): DeviceLinkDirectChannel => {+ const direction = from === 'left' ? 'toRight' : 'toLeft';+ const target = from === 'left' ? 'right' : 'left';+ return {+ send(text) {+ if (!open || failSend[from]) throw new Error('direct channel unavailable');+ frames[direction].push(JSON.parse(text) as Envelope);+ if (!drop[direction]) setTimeout(() => handles[target]?.receive(text), 0);+ },+ close(reason) {+ closeReasons.push(reason);+ if (!open) return;+ open = false;+ setTimeout(() => { handles.left?.closed(); handles.right?.closed(); }, 0);+ },+ };+ };+ handles.left = left.client.attachDirectPath(right.id, channel('left'));+ handles.right = right.client.attachDirectPath(left.id, channel('right'));+ return { drop, failSend, frames, closeReasons, handles, isOpen: () => open };+}++const reliableKinds = (envs: readonly Envelope[] | undefined, kind: Envelope['kind'], src?: string): number =>+ (envs ?? []).filter(env => env.kind === kind && parseTransportPayload(env.payload) && (!src || env.src === src)).length;++describe('直连优先、中继兜底(Device Link direct path)', () => {+ it('falls back to relay on a stalled direct path without re-running the command or disturbing another controller', async () => {+ vi.useFakeTimers();+ const relay = new MemoryRelay();+ const sockets = vi.spyOn(relay, 'makeWebSocket');+ const timing = { transportRetryIntervalMs: 1_000, requestTimeoutMs: 30_000 };+ // The controller's own ACK deadline must be what detects the stall, not the host's.+ const host = makeRelayClient(relay, 'desktop', { ...timing, transportRetryIntervalMs: 10_000 });+ const a = makeRelayClient(relay, 'viewer-a', timing);+ const b = makeRelayClient(relay, 'viewer-b', timing);+ const pump = () => relay.settle(async () => { await vi.advanceTimersByTimeAsync(1); });+ const executed: string[] = [];+ host.onFrame((env) => {+ if (env.kind === 'link-open') host.sendLinkAccept(env.src!, env.id!, { appVersion: '1', allowlistHash: 'hash' });+ if (env.kind !== 'invoke') return;+ executed.push(`${env.src}:${env.id}`);+ host.sendInvokeResult(env.src!, env.id!, { ok: true, result: `done-${executed.length}` });+ });+ const pathChanges: DeviceLinkPeerPathChanged[] = [];+ a.onPeerPathChanged(change => pathChanges.push(change));+ try {+ for (const client of [host, a, b]) client.start();+ await pump();+ for (const client of [a, b]) {+ const opening = client.openLink('desktop', { controllerName: 'Viewer', protocolVersion: 1, appVersion: '1' });+ await pump(); await opening;+ }+ const directA = connectDirect({ id: 'viewer-a', client: a }, { id: 'desktop', client: host });+ const directB = connectDirect({ id: 'viewer-b', client: b }, { id: 'desktop', client: host });+ const relayInvokesBefore = reliableKinds(relay.deliveredTo.get('desktop'), 'invoke');++ // Healthy direct path: the request, its result and both ACK streams bypass the relay.+ const first = a.invoke('desktop', { channel: 'local-db:sessions:get', args: ['s1'] });+ await pump();+ await expect(first).resolves.toMatchObject({ ok: true });+ expect(reliableKinds(directA.frames.toRight, 'invoke')).toBe(1);+ expect(reliableKinds(directA.frames.toLeft, 'invoke-result')).toBe(1);+ expect(reliableKinds(relay.deliveredTo.get('desktop'), 'invoke')).toBe(relayInvokesBefore);+ expect(reliableKinds(relay.deliveredTo.get('viewer-a'), 'invoke-result')).toBe(0);++ // Host -> viewer-a goes silent: the command reaches the host, but its ACK and result vanish.+ directA.drop.toLeft = true;+ let second: unknown;+ void a.invoke('desktop', { channel: 'local-db:sessions:get', args: ['s2'] }).then(v => { second = v; });+ await pump();+ expect(executed).toHaveLength(2);+ expect(second).toBeUndefined();+ // Just past the controller's 1s ACK deadline, then let the relay deliver the fallback copy.+ await vi.advanceTimersByTimeAsync(1_100);+ await pump();++ expect(second).toMatchObject({ ok: true, result: 'done-2' });+ // The relay copy of the same seq is acknowledged, never dispatched a second time.+ expect(reliableKinds(relay.deliveredTo.get('desktop'), 'invoke', 'viewer-a')).toBe(1);+ expect(executed.filter(entry => entry.startsWith('viewer-a:'))).toHaveLength(2);+ expect(pathChanges.at(-1)).toMatchObject({ deviceId: 'desktop', path: 'relay', reason: 'ack-timeout', resent: 1 });+ expect(a.getPeerPath('desktop')).toBe('relay');+ expect(host.getPeerPath('viewer-a')).toBe('relay');+ expect(directA.isOpen()).toBe(false);++ // Only that peer's direct path changed: no relay reconnect, other controller stays direct.+ const third = b.invoke('desktop', { channel: 'local-db:sessions:get', args: ['s3'] });+ await pump();+ await expect(third).resolves.toMatchObject({ ok: true });+ expect(reliableKinds(directB.frames.toRight, 'invoke')).toBe(1);+ expect(reliableKinds(relay.deliveredTo.get('desktop'), 'invoke', 'viewer-b')).toBe(0);+ expect(host.getPeerPath('viewer-b')).toBe('direct');+ expect(a.isLinkReady('desktop')).toBe(true);+ expect(b.isLinkReady('desktop')).toBe(true);+ expect(sockets).toHaveBeenCalledTimes(3);+ for (const result of sockets.mock.results) expect(result.value.closed).toBeNull();+ } finally {+ for (const client of [host, a, b]) client.stop();+ vi.useRealTimers();+ }+ });++ it('keeps link control, scopes and peer identity under relay authority', async () => {+ vi.useFakeTimers();+ const relay = new MemoryRelay();+ const sockets = vi.spyOn(relay, 'makeWebSocket');+ const timing = { transportRetryIntervalMs: 1_000, requestTimeoutMs: 30_000 };+ const host = makeRelayClient(relay, 'desktop', timing);+ const a = makeRelayClient(relay, 'viewer-a', timing);+ const pump = () => relay.settle(async () => { await vi.advanceTimersByTimeAsync(1); });+ const hostFrames: Envelope[] = [];+ host.onFrame((env) => {+ if (env.kind === 'link-open') host.sendLinkAccept(env.src!, env.id!, { appVersion: '1', allowlistHash: 'hash' });+ if (env.kind === 'invoke' || env.kind === 'link-close') hostFrames.push(env);+ if (env.kind === 'invoke') host.sendInvokeResult(env.src!, env.id!, { ok: true, result: 'ok' });+ });+ try {+ host.start(); a.start();+ await pump();+ const opening = a.openLink('desktop', { controllerName: 'Viewer', protocolVersion: 1, appVersion: '1' });+ await pump(); await opening;++ const scopedClose = vi.fn();+ const scoped = host.attachDirectPath(sharedTaskHostPeer('task-a', 'viewer-a'), { send: vi.fn(), close: scopedClose });+ expect(scoped.isActive()).toBe(false);+ expect(scopedClose).toHaveBeenCalledWith('not-eligible');++ const direct = connectDirect({ id: 'viewer-a', client: a }, { id: 'desktop', client: host });+ const inject = (env: Record<string, unknown>) => direct.handles.right!.receive(JSON.stringify(env));+ // Link control and unwrapped legacy invokes (even with a forged src) never enter via direct.+ inject({ v: PROTOCOL_VERSION, kind: 'link-close', dst: 'desktop', payload: { reason: 'revoked' } });+ inject({ v: PROTOCOL_VERSION, kind: 'invoke', id: 'legacy-1', src: 'viewer-b', dst: 'desktop',+ payload: { channel: 'local-db:sessions:get', args: [] } });+ await pump();+ expect(hostFrames).toHaveLength(0);+ expect(host.isLinkReady('viewer-a')).toBe(true);++ // A local write failure sends the same request over relay immediately.+ direct.failSend.left = true;+ const viaRelay = a.invoke('desktop', { channel: 'local-db:sessions:get', args: ['s1'] });+ await pump();+ await expect(viaRelay).resolves.toEqual({ ok: true, result: 'ok' });+ expect(hostFrames.filter(env => env.kind === 'invoke' && env.src === 'viewer-a')).toHaveLength(1);+ expect(direct.closeReasons).toContain('send-failed');+ expect(a.getPeerPath('desktop')).toBe('relay');++ // The relay stays the presence authority: an offline report removes a fresh direct path.+ const again = connectDirect({ id: 'viewer-a', client: a }, { id: 'desktop', client: host });+ expect(host.getPeerPath('viewer-a')).toBe('direct');+ const hostSocket = sockets.mock.results.find(entry => entry.value.ownerId === 'desktop')!.value;+ hostSocket.push({ v: PROTOCOL_VERSION, kind: 'presence-changed', payload: {+ deviceId: 'viewer-a', online: false, deviceName: 'viewer-a', platform: 'darwin', appVersion: '1',+ lastSeenAt: 0, remoteControlEnabled: true, busy: false,+ } });+ expect(again.closeReasons).toContain('peer-offline');+ expect(host.getPeerPath('viewer-a')).toBe('relay');++ const last = connectDirect({ id: 'viewer-a', client: a }, { id: 'desktop', client: host });+ a.stop();+ expect(last.closeReasons).toContain('stopped');+ expect(a.getPeerPath('desktop')).toBe('relay');+ } finally {+ host.stop(); a.stop();+ vi.useRealTimers();+ }+ });+});diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex f43d2bf009..6b5521cc6e 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -71,6 +71,14 @@ import {} from './transport.js';import { PLUGIN_SYNC_CHANNEL } from './pluginSyncProtocol.js';import { MAKER_EVENT_BATCH_CHANNEL } from './topics.js';+import {+ DIRECT_PATH_HIGH_WATER_BYTES,+ type DeviceLinkDirectChannel,+ type DeviceLinkDirectCloseReason,+ type DeviceLinkDirectPathHandle,+ type DeviceLinkPeerPath,+ type DeviceLinkPeerPathChanged,+} from './directPath.js';/** Budget measurement: physical wire envelope size regardless of relay announcement. */const ALL_SCOPES: ScopeSupport = { sharedTask: true, providerShare: true };@@ -572,7 +580,10 @@ interface PendingReliableMessage {*/firstSentAt?: number;/** Last observed gate, diagnostics only; never controls transport scheduling. */- lastBlockedBy?: 'link' | 'receive-window' | 'recovery-ack' | 'relay-budget' | 'socket' | 'socket-budget' | 'pass-budget';+ lastBlockedBy?: 'link' | 'receive-window' | 'recovery-ack' | 'relay-budget' | 'socket' | 'socket-budget' | 'pass-budget'+ | 'direct-buffer';+ /** 最近一次物理写出走的路径;直连失效时据此把仍未确认的帧改走 relay。 */+ path?: DeviceLinkPeerPath;}type ReliableSendPhase = 'down' | 'awaiting-confirm' | 'ready';@@ -684,6 +695,11 @@ interface PeerTransportState {pushAdmissionDropLogAt: number;/** 同一 relay WebSocket 内每次接受 link-open/link-accept 都递增。 */linkGeneration: number;+ /**+ * 最近一条可靠帧从哪条路径到达。累计 ACK 原路返回:对端已因直连异常改走+ * relay 时,ACK 不能继续投进可能已失效的直连通道。+ */+ lastInboundPath: DeviceLinkPeerPath;}interface PendingInboundLinkOffer {@@ -844,6 +860,12 @@ export class DeviceLinkClient {string,Map<string, Array<{ linkGeneration: number; count: number }>>>();+ /**+ * 每台同账号设备至多一条直连通道(见 directPath.ts)。只承载已建立可靠链路上的+ * 数据面帧;没有通道或通道失效时,同一批帧照常走 relay。+ */+ private readonly directPaths = new Map<string, DeviceLinkDirectChannel>();+ private peerPathHandlers = new Set<(change: DeviceLinkPeerPathChanged) => void>();constructor(opts: DeviceLinkClientOptions) {this.opts = opts;@@ -1060,6 +1082,9 @@ export class DeviceLinkClient {this.clearTimers();this.handshakeTimeoutStreak = 0;this.failAllPending(new DeviceLinkError('NOT_CONNECTED', 'client stopped'));+ // 登出、切账号与设备被移除都经由 stop:直连通道绑定的是旧账号下的身份,不能留给下一次 start。+ for (const [deviceId, channel] of this.directPaths) this.closeDirectChannel(deviceId, channel, 'stopped');+ this.directPaths.clear();this.clearPeerTransport();this.congestionSendBudget.reset();this.localSendPressure = false;@@ -1205,6 +1230,50 @@ export class DeviceLinkClient {return () => this.presenceHandlers.delete(cb);}+ /**+ * 接入一条到同账号设备的直连通道(直连优先、中继兜底,见 directPath.ts)。+ *+ * 通道只承载该设备已建立可靠链路上的数据面帧与 ACK;link 控制帧、跨账号范围+ * 与未协商可靠传输的对端始终走 relay。通道断开、写入失败或经它发出的帧过期+ * 未确认时,客户端关闭通道,把仍未确认的帧经 relay 重发;接收端按 seq 去重,+ * 不会重复执行。同一设备再次接入会替换旧通道。+ */+ attachDirectPath(deviceId: string, channel: DeviceLinkDirectChannel): DeviceLinkDirectPathHandle {+ const isActive = (): boolean => this.directPaths.get(deviceId) === channel;+ const handle: DeviceLinkDirectPathHandle = {+ receive: (text) => {+ if (isActive()) this.handleDirectFrame(deviceId, text);+ },+ drained: () => {+ if (isActive()) this.retryPending(deviceId, { ignoreInterval: false, onlyUnsent: true });+ },+ closed: () => {+ if (isActive()) this.detachDirectPath(deviceId, 'channel-closed');+ },+ isActive,+ };+ if (this.stopped || !deviceId || deviceId === this.selfDeviceId || isScopedPeer(deviceId)) {+ this.closeDirectChannel(deviceId, channel, 'not-eligible');+ return handle;+ }+ this.detachDirectPath(deviceId, 'replaced');+ this.directPaths.set(deviceId, channel);+ this.log.info(`device-link direct path attached dst=${deviceId.slice(0, 8)}`);+ this.emitPeerPathChanged({ deviceId, path: 'direct' });+ return handle;+ }++ /** 该设备的数据面路径:接入了直连通道即为 'direct'(链路就绪后启用),否则走 relay。 */+ getPeerPath(deviceId: string): DeviceLinkPeerPath {+ return this.directPaths.has(deviceId) ? 'direct' : 'relay';+ }++ /** 订阅直连与 relay 之间的切换;平台据此在切回 relay 后安排重新建立直连。 */+ onPeerPathChanged(cb: (change: DeviceLinkPeerPathChanged) => void): () => void {+ this.peerPathHandlers.add(cb);+ return () => this.peerPathHandlers.delete(cb);+ }+private notifyPeerRouteOffline(deviceId: string, linkGeneration: number): void {const notified = this.peerOfflineNotifiedGeneration.get(deviceId);if (@@ -1427,6 +1496,8 @@ export class DeviceLinkClient {this.abandonReliablePending(dst, `control link closed locally (${reason})`);}}+ // 撤权或断开都不保留直连:之后的数据面只能在 relay 重新建链(并复验授权)后恢复。+ this.detachDirectPath(dst, 'link-closed');// 显式关闭的本地语义不能依赖 relay 当前可写;离线时只跳过通知,// 已经清掉的可靠 pending 也绝不能在下一次 openLink 后复活。if (this.status !== 'online') return;@@ -2461,6 +2532,8 @@ export class DeviceLinkClient {return true;case 'presence-changed': {const snap = env.payload as PresenceSnapshot;+ // 在线与账号归属以 relay 为准:对端离开 relay(含被移出账号)即撤下直连。+ if (snap.online === false) this.detachDirectPath(snap.deviceId, 'peer-offline');for (const cb of this.presenceHandlers) {try {cb(snap);@@ -2713,6 +2786,7 @@ export class DeviceLinkClient {peer.remoteBaseSeq = 1;peer.receive.clear();this.abandonReliablePending(env.src, 'control link closed by peer');+ this.detachDirectPath(env.src, 'link-closed');} else if (env.kind === 'invoke'&& env.src@@ -2737,6 +2811,7 @@ export class DeviceLinkClient {*/private ingestTransportEnvelope(env: Envelope,+ path: DeviceLinkPeerPath = 'relay',): { handled: false } | { handled: true; result?: Promise<void> } {const parsed = parseTransportPayload(env.payload);if (!parsed || !env.src || !isReliableKind(env.kind)) return { handled: false };@@ -2760,6 +2835,7 @@ export class DeviceLinkClient {return { handled: true };}if (!peer.remoteStreamId) peer.remoteStreamId = parsed.meta.streamId;+ peer.lastInboundPath = path;const { meta } = parsed;this.logRecoveryStage(env.src, 'first-reliable-receive', ` seq=${meta.seq} baseSeq=${meta.baseSeq ?? 1}`);const stream = this.getReceiveStream(@@ -3159,15 +3235,17 @@ export class DeviceLinkClient {// 真会发送时仍在驱逐/腾位之前预检(旧 P1:先驱逐再拒会清空镜像历史)。const additionalFrames = Math.max(1, frames.length);const previousBaseSeq = this.getTransportBaseSeq(peer);+ // 走直连的帧不占 relay 的拥塞预算与 socket 缓冲。+ const viaDirect = this.directChannelForSend(env.dst, peer) !== null;const willSendNow = this.isPeerSendReady(peer)// Admission may evict a discardable prefix and move this message into// the window. Preserve the socket preflight before that mutation.&& (!this.isOutsideReceiveWindow(peer, seq) || !hasPendingCapacity())&& !this.shouldHoldRecoverySend(peer, additionalFrames)- && (this.congestionCloseStreak === 0 || this.congestionSendBudget.canTake(+ && (viaDirect || this.congestionCloseStreak === 0 || this.congestionSendBudget.canTake(env.dst, additionalFrames, this.getReadyReliablePeers(env.dst), this.monotonicNow(),));- if (willSendNow) {+ if (willSendNow && !viaDirect) {this.assertWebSocketCapacity(this.measureReliableFrames(frames));}if (!hasPendingCapacity()) {@@ -3262,6 +3340,12 @@ export class DeviceLinkClient {this.getTransportBaseSeq(peer),);const wireBytes = this.measureReliableFrames(frames);+ const direct = this.directChannelForSend(pending.envelope.dst!, peer);+ if (direct) {+ const sentDirect = this.sendReliableFramesDirect(peer, pending, frames, wireBytes, direct);+ // null: 一帧都没写进直连且通道已撤下,本次立即改走 relay。+ if (sentDirect !== null) return sentDirect;+ }const peers = this.getReadyReliablePeers(pending.envelope.dst!);const budgetNow = this.monotonicNow();const congestionBudget = this.congestionCloseStreak > 0 ? this.congestionSendBudget : null;@@ -3308,31 +3392,212 @@ export class DeviceLinkClient {} finally {congestionBudget?.refund(pending.envelope.dst!, frames.length - sent);localBudget?.refund(pending.envelope.dst!, byteCredits - Math.ceil(writtenBytes / SOCKET_SEND_CREDIT_BYTES));- if (sent > 0) {- const ageMs = Math.round(this.monotonicNow() - pending.enqueuedAt);- if ((pending.envelope.kind === 'invoke' || pending.envelope.kind === 'invoke-result')- && (ageMs >= 250 || pending.attempts > 0)) {- this.log.debug(`device-link send timing kind=${pending.envelope.kind} request=${pending.envelope.id?.slice(0, 8) ?? 'none'}`- + ` dst=${pending.envelope.dst!.slice(0, 8)} seq=${pending.seq}`- + ` ${pending.attempts === 0 ? 'queueMs' : 'ageMs'}=${ageMs}`- + ` attempt=${pending.attempts + 1} frames=${sent} bytes=${pending.bytes}`- + ` pending=${peer.pending.size} congestion=${this.congestionCloseStreak}`- + ` lastBlockedBy=${pending.lastBlockedBy ?? 'none'} socketBufferedBytes=${this.ws?.bufferedAmount ?? 0}`);- }- pending.lastBlockedBy = undefined;- pending.sent = true;- if (pending.attempts === 0) pending.firstSentAt = this.monotonicNow();- 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}`);- }+ this.noteReliableWrite(peer, pending, sent, 'relay');+ }+ return sent;+ }++ /** 一次物理写出(relay 或直连)之后的统一记账。 */+ private noteReliableWrite(+ peer: PeerTransportState,+ pending: PendingReliableMessage,+ sent: number,+ path: DeviceLinkPeerPath,+ ): void {+ if (sent <= 0) return;+ const ageMs = Math.round(this.monotonicNow() - pending.enqueuedAt);+ if ((pending.envelope.kind === 'invoke' || pending.envelope.kind === 'invoke-result')+ && (ageMs >= 250 || pending.attempts > 0)) {+ this.log.debug(`device-link send timing kind=${pending.envelope.kind} request=${pending.envelope.id?.slice(0, 8) ?? 'none'}`+ + ` dst=${pending.envelope.dst!.slice(0, 8)} seq=${pending.seq} path=${path}`+ + ` ${pending.attempts === 0 ? 'queueMs' : 'ageMs'}=${ageMs}`+ + ` attempt=${pending.attempts + 1} frames=${sent} bytes=${pending.bytes}`+ + ` pending=${peer.pending.size} congestion=${this.congestionCloseStreak}`+ + ` lastBlockedBy=${pending.lastBlockedBy ?? 'none'} socketBufferedBytes=${this.ws?.bufferedAmount ?? 0}`);+ }+ pending.lastBlockedBy = undefined;+ pending.sent = true;+ pending.path = path;+ if (pending.attempts === 0) pending.firstSentAt = this.monotonicNow();+ 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}`);+ }+ }++ // ─── 内部:直连选路(直连优先、中继兜底) ─────────────────────────────────────++ /** 可靠帧此刻能否走直连:双方已提交可靠链路、本机发送方向就绪且接入了通道。 */+ private directChannelForSend(dst: string, peer: PeerTransportState): DeviceLinkDirectChannel | null {+ if (!peer.reliable || !this.isPeerSendReady(peer)) return null;+ return this.directPaths.get(dst) ?? null;+ }++ /**+ * 经直连写出一条可靠消息的全部分片。返回 null 表示一帧都没写出且通道已撤下,+ * 调用方立即改走 relay;返回 0 表示直连缓冲已满,帧留在队列等 drained()。+ */+ private sendReliableFramesDirect(+ peer: PeerTransportState,+ pending: PendingReliableMessage,+ frames: readonly Envelope[],+ wireBytes: number,+ channel: DeviceLinkDirectChannel,+ ): number | null {+ const dst = pending.envelope.dst!;+ const buffered = channel.bufferedAmount ?? 0;+ // 与 relay 一致:缓冲排空后单条大消息总能发出,不会被软上限永久卡住。+ if (buffered > 0 && buffered + wireBytes > DIRECT_PATH_HIGH_WATER_BYTES) {+ pending.lastBlockedBy = 'direct-buffer';+ return 0;+ }+ let sent = 0;+ for (const frame of frames) {+ try {+ channel.send(JSON.stringify(frame));+ } catch (err) {+ this.log.debug(`device-link direct send failed dst=${dst.slice(0, 8)} seq=${pending.seq} frames=${sent}`, err);+ break;}+ sent += 1;+ }+ if (sent === 0) {+ this.detachDirectPath(dst, 'send-failed');+ return null;}+ if (pending.envelope.id) this.pending.get(pending.envelope.id)?.noteFirstWrite?.();+ this.noteReliableWrite(peer, pending, sent, 'direct');+ // 只写出部分分片:整条消息改由 relay 从头重发,接收端丢弃重复分片。+ if (sent < frames.length) this.detachDirectPath(dst, 'send-failed');return sent;}+ /**+ * 撤下直连并切回 relay。经直连写出、仍未确认的消息恢复为未发送,按 relay 的+ * 恢复预算重发(先发一批探测,收到 ACK 再继续)。只作用于这一台设备:不重连+ * relay、不重建链路、不影响其它设备的链路与在途请求。+ */+ private detachDirectPath(deviceId: string, reason: DeviceLinkDirectCloseReason): void {+ const channel = this.directPaths.get(deviceId);+ if (!channel) return;+ this.directPaths.delete(deviceId);+ this.closeDirectChannel(deviceId, channel, reason);+ const peer = this.peerTransport.get(deviceId);+ let resent = 0;+ if (peer) {+ peer.lastInboundPath = 'relay';+ for (const pending of peer.pending.values()) {+ if (pending.path !== 'direct') continue;+ pending.path = undefined;+ pending.sent = false;+ resetReliableSendRound(pending);+ resent += 1;+ }+ if (resent > 0) {+ peer.recoveryNeedsAck = true;+ peer.recoveryFramesSent = 0;+ }+ }+ const message = `device-link direct path closed dst=${deviceId.slice(0, 8)} reason=${reason} resendViaRelay=${resent}`;+ if (reason === 'ack-timeout' || reason === 'send-failed') this.log.warn(message);+ else this.log.info(message);+ this.emitPeerPathChanged({ deviceId, path: 'relay', reason, ...(resent > 0 ? { resent } : {}) });+ if (resent === 0) return;+ // 调用方可能正处于 retryPending / sendPeerEnvelope 中:下一个微任务再重放,避免重入。+ // 只补发仍未发送的:调用方当轮已经改走 relay 发出的帧不再复制一份。+ void Promise.resolve().then(() => {+ this.retryPending(deviceId, { ignoreInterval: false, onlyUnsent: true });+ const current = this.peerTransport.get(deviceId);+ if (current?.reliable && this.isPeerSendReady(current) && current.pending.size > 0) {+ this.ensureRetryTimer(deviceId);+ }+ });+ }++ private closeDirectChannel(+ deviceId: string,+ channel: DeviceLinkDirectChannel,+ reason: DeviceLinkDirectCloseReason,+ ): void {+ try {+ channel.close(reason);+ } catch (err) {+ this.log.debug(`device-link direct path close failed dst=${deviceId.slice(0, 8)}`, err);+ }+ }++ private emitPeerPathChanged(change: DeviceLinkPeerPathChanged): void {+ for (const cb of this.peerPathHandlers) {+ try {+ cb(change);+ } catch (err) {+ this.log.error('device-link peer path handler failed', err);+ }+ }+ }++ /**+ * 直连入站:只接受同账号对端发给本机的可靠数据面帧与累计 ACK。来源取自通道+ * 绑定的设备,不信任帧内 src;跨账号范围、link 控制帧与非可靠帧一律丢弃(它们+ * 只走 relay)。不刷新 relay 心跳:直连有流量不能掩盖 relay 已经失联。+ */+ private handleDirectFrame(deviceId: string, text: string): void {+ if (this.stopped) return;+ const self = this.selfDeviceId;+ let parsed: unknown;+ try {+ if (byteLength(text) > MAX_FRAME_BYTES) throw new Error('direct frame too large');+ parsed = JSON.parse(text) as unknown;+ } catch {+ this.log.warn(`dropping invalid direct frame from ${deviceId.slice(0, 8)}`);+ return;+ }+ if (+ !isRecord(parsed)+ || parsed.v !== PROTOCOL_VERSION+ || typeof parsed.kind !== 'string'+ || !isReliableKind(parsed.kind as Envelope['kind'])+ || parsed.sharedTask !== undefined+ || parsed.providerShare !== undefined+ || !self+ || parsed.dst !== self+ || (parsed.id !== undefined && typeof parsed.id !== 'string')+ ) {+ this.log.warn(`dropping disallowed direct frame from ${deviceId.slice(0, 8)}`);+ return;+ }+ const env: Envelope = {+ v: PROTOCOL_VERSION,+ kind: parsed.kind as Envelope['kind'],+ ...(typeof parsed.id === 'string' ? { id: parsed.id } : {}),+ src: deviceId,+ dst: self,+ payload: parsed.payload,+ };+ if (!isValidInboundEnvelope(env)) {+ this.log.warn(`dropping invalid direct frame kind=${env.kind} from ${deviceId.slice(0, 8)}`);+ return;+ }+ const ack = parseTransportAck(env);+ if (ack) {+ // 链路确认 ACK 属于控制面,只认 relay;直连上的确认只按普通累计 ACK 处理。+ this.handleTransportAck(deviceId, ack.streamId, ack.ackSeq);+ return;+ }+ if (!parseTransportPayload(env.payload)) {+ this.log.warn(`dropping non-reliable direct frame kind=${env.kind} from ${deviceId.slice(0, 8)}`);+ return;+ }+ const transport = this.ingestTransportEnvelope(env, 'direct');+ if (transport.handled) {+ void transport.result?.catch((err) => {+ this.log.error('device-link reliable frame failed', err);+ });+ }+ }+private canWriteReliableBytes(bytes: number): boolean {const buffered = this.ws?.bufferedAmount ?? 0;const pressured = buffered > SOCKET_DATA_LOW_WATER_BYTES@@ -3665,6 +3930,7 @@ export class DeviceLinkClient {peer.receiveReady = false;peer.pendingLinkConfirmation = null;peer.outboundLinkConfirmationAck = null;+ peer.lastInboundPath = 'relay';}private getPeerTransport(dst: string): PeerTransportState {@@ -3703,6 +3969,7 @@ export class DeviceLinkClient {pushAdmissionDropCount: 0,pushAdmissionDropLogAt: 0,linkGeneration: 0,+ lastInboundPath: 'relay',};this.peerTransport.set(dst, peer);}@@ -3884,10 +4151,23 @@ export class DeviceLinkClient {? pendingConfirmation.requestId: undefined);+ const ack = makeTransportAck(dst, streamId, ackSeq, effectiveLinkRequestId);+ // 累计 ACK 原路返回;链路确认 ACK 属于控制面,始终走 relay。+ const direct = !effectiveLinkRequestId && this.peerTransport.get(dst)?.lastInboundPath === 'direct'+ ? this.directPaths.get(dst)+ : undefined;+ if (direct) {+ try {+ direct.send(JSON.stringify(ack));+ this.logRecoveryStage(dst, 'ack-sent', ` receiveStream=${streamId.slice(0, 8)} ack=${ackSeq}`, false);+ return true;+ } catch (err) {+ this.log.debug(`reliable transport direct ACK send failed dst=${dst.slice(0, 8)}`, err);+ this.detachDirectPath(dst, 'send-failed');+ }+ }try {- this.sendBestEffortRoutedEnvelope(- makeTransportAck(dst, streamId, ackSeq, effectiveLinkRequestId),- );+ this.sendBestEffortRoutedEnvelope(ack);this.logRecoveryStage(dst, 'ack-sent', ` receiveStream=${streamId.slice(0, 8)} ack=${ackSeq}`, false);return true;} catch (err) {@@ -4391,6 +4671,11 @@ export class DeviceLinkClient {// the later frame without exhausting its budget behind that head.continue;}+ if (pending.path === 'direct' && pending.sent && !opts.ignoreInterval) {+ // 经直连写出的帧到了重发期限仍未确认:直连已不可信,撤下并改走 relay。+ // 这些帧恢复为未发送、重试次数从零计,直连的失败不消耗 relay 的重试预算。+ this.detachDirectPath(dst, 'ack-timeout');+ }if (pending.attempts >= this.timing.transportMaxRetryAttempts) {this.handleReliableRetryExhausted(dst, pending.seq);return;@@ -4832,8 +5117,10 @@ export class DeviceLinkClient {*/private isRelayWideReliableStall(dst: string, peer: PeerTransportState): boolean {// 与首发同一时刻到达的入站帧不可能是对它的应答,所以取 <=。+ // 经直连发出的队头不能证明 relay 卡住:它的应答不经 relay,沉默只说明直连有问题。const silentSince = (head: PendingReliableMessage | undefined): boolean => (head?.sent === true+ && head.path !== 'direct'&& head.firstSentAt !== undefined&& this.lastPeerInboundAt <= head.firstSentAt);diff --git a/packages/device-link/src/directPath.ts b/packages/device-link/src/directPath.tsnew file mode 100644index 0000000000..f9bde44b6a--- /dev/null+++ b/packages/device-link/src/directPath.ts@@ -0,0 +1,71 @@+/**+ * Device Link 直连优先、中继兜底的选路契约(同账号设备之间)。+ *+ * relay 仍是控制面:登录、在线状态、link-open / link-accept / link-close 与+ * 授权都只走 relay。直连通道(例如局域网内的 WebRTC DataChannel)只承载已建立+ * 可靠链路上的数据面帧:reliable-transport-v1 包装的 invoke / invoke-result /+ * push,以及它们的累计 ACK。可靠层按 seq 去重、按序交付,所以同一条消息在+ * 两条路径上各到一次也只会执行一次;直连失效时未确认的帧原样改走 relay 重发。+ *+ * 平台(Desktop / Mobile)负责经已授权的信令建立通道,再交给+ * `DeviceLinkClient.attachDirectPath`。跨账号的共享任务与供应商分享不走直连:+ * 它们的逐帧授权仍由 relay 执行。+ */++/** 平台提供的一条直连通道。 */+export interface DeviceLinkDirectChannel {+ /**+ * 发送一条完整的 JSON 文本。实现必须保序;无法交付时应关闭通道而不是静默丢弃。+ * 单条最多 MAX_FRAME_BYTES,超过底层消息上限时由实现自行分片。不可写时抛错。+ */+ send(text: string): void;+ /** 本地已排队、尚未交给网络的字节数(如 RTCDataChannel.bufferedAmount);缺省视为 0。 */+ readonly bufferedAmount?: number;+ /** 释放通道。客户端切回 relay、对端下线、链路关闭或停止时调用;可重复调用。 */+ close(reason: DeviceLinkDirectCloseReason): void;+}++/** 客户端结束直连的原因(仅本地诊断,不上 wire)。 */+export type DeviceLinkDirectCloseReason =+ /** 同一设备接入了新的直连通道。 */+ | 'replaced'+ /** 平台报告通道已断开(对端关闭、ICE 失败等)。 */+ | 'channel-closed'+ /** 写入通道失败。 */+ | 'send-failed'+ /** 经直连发出的帧过了重发期限仍未确认。 */+ | 'ack-timeout'+ /** relay 报告对端已离线;在线状态以 relay 为准。 */+ | 'peer-offline'+ /** 控制链路被显式关闭或撤权。 */+ | 'link-closed'+ /** 客户端停止(登出、切换账号、设备被移除)。 */+ | 'stopped'+ /** 不允许直连的对象(跨账号范围、本机或客户端未运行)。 */+ | 'not-eligible';++/** 平台持有的句柄:把通道上的事件交回客户端。 */+export interface DeviceLinkDirectPathHandle {+ /** 交付通道上收到的一条完整消息。 */+ receive(text: string): void;+ /** 通道发送缓冲回落,可继续发送排队中的帧。 */+ drained(): void;+ /** 通道已结束;未确认的帧改走 relay。 */+ closed(): void;+ /** 该通道是否仍是此设备当前的直连路线。 */+ isActive(): boolean;+}++export type DeviceLinkPeerPath = 'direct' | 'relay';++export interface DeviceLinkPeerPathChanged {+ deviceId: string;+ path: DeviceLinkPeerPath;+ /** 切回 relay 的原因;切到直连时缺省。 */+ reason?: DeviceLinkDirectCloseReason;+ /** 切回 relay 时需要经 relay 重发的未确认消息数。 */+ resent?: number;+}++/** 直连发送缓冲软上限:超过后帧留在可靠队列,等 `drained()` 再发。 */+export const DIRECT_PATH_HIGH_WATER_BYTES = 1024 * 1024;diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.tsindex b96c95e092..165f65ece0 100644--- a/packages/device-link/src/index.ts+++ b/packages/device-link/src/index.ts@@ -10,6 +10,7 @@export * from "./protocol.js";export * from "./allowlist.js";export * from "./client.js";+export * from "./directPath.js";export * from "./transport.js";export * from "./invokeTransfer.js";export * from "./topics.js";