Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(device-link): 弱网下压缩远程回包、按往返时间调整重发并修复重连重复发送
Dash50eab9a6c354
diff --git a/apps/desktop/src/main/device-link/__tests__/transferCodec.test.ts b/apps/desktop/src/main/device-link/__tests__/transferCodec.test.tsnew file mode 100644index 0000000000..b3a7523f99--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/transferCodec.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';+import { encodeInvokeResultTransfer, InvokeResultCache } from '@cindy/device-link';+import { desktopTransferCodec } from '../transferCodec';++describe('desktop device-link transfer codec', () => {+ it('round-trips a large result between a desktop host and a desktop controller', () => {+ const result = Array.from({ length: 300 }, (_, i) => ({ id: `s-${i}`, title: '远程任务 ✓' }));+ const controller = new InvokeResultCache(desktopTransferCodec);+ const request = controller.prepare('desktop-b', { channel: 'local-db:sessions:list', args: [] });+ const wire = encodeInvokeResultTransfer(request.payload.transfer!, { ok: true, result }, desktopTransferCodec);+ expect(wire.ok && wire.transfer?.gzipBase64).toEqual(expect.any(String));+ expect(JSON.stringify(wire).length).toBeLessThan(JSON.stringify(result).length / 4);+ expect(request.decode(wire)).toEqual({ ok: true, result });+ });++ it('produces a stable content tag', () => {+ expect(desktopTransferCodec.contentTag!('abc')).toBe(desktopTransferCodec.contentTag!('abc'));+ expect(desktopTransferCodec.contentTag!('abc')).not.toBe(desktopTransferCodec.contentTag!('abd'));+ });+});diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex b0d4281d7c..bc8a9c79a7 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -14,6 +14,7 @@ import os from 'node:os';import { tryPeerInvoke } from './filePeer';import { assertBackgroundLinkAccepted, linkOpenCapabilities } from './backgroundLink';import { deviceName, initializeDeviceName } from './deviceName';+import { desktopTransferCodec } from './transferCodec';import { watchNetworkChanges } from './networkChanges';import path from 'node:path';import { app, BrowserWindow } from 'electron';@@ -677,6 +678,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v};client = new DeviceLinkClient({getWsUrl: wsUrl,+ transferCodec: desktopTransferCodec,getToken: async () => {// Prepare the name before the first hello without blocking Electron's main thread.await deviceNameReady;diff --git a/apps/desktop/src/main/device-link/transferCodec.ts b/apps/desktop/src/main/device-link/transferCodec.tsnew file mode 100644index 0000000000..d904451bc1--- /dev/null+++ b/apps/desktop/src/main/device-link/transferCodec.ts@@ -0,0 +1,13 @@+import { createHash } from 'node:crypto';+import { constants, gunzipSync, gzipSync } from 'node:zlib';+import type { DeviceLinkTransferCodec } from '@cindy/device-link';++/**+ * Desktop 既是被控端也是控制端(桌面远控桌面),两个方向共用一份编码器。+ * 压缩级别取速度优先:大结果在主进程同步压缩,几百 KB 的会话列表约几毫秒。+ */+export const desktopTransferCodec: DeviceLinkTransferCodec = {+ gzipBase64: (text) => gzipSync(Buffer.from(text, 'utf8'), { level: constants.Z_BEST_SPEED + 3 }).toString('base64'),+ gunzipBase64: (base64) => gunzipSync(Buffer.from(base64, 'base64')).toString('utf8'),+ contentTag: (text) => createHash('sha256').update(text).digest('base64url'),+};diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 3a843297b0..403d1e5b8d 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -166,6 +166,7 @@ import { hasMoreOlderMessages } from '@/session/messagePaging';import type { InputProjection, PendingInteraction, RemoteMessage } from '@/session/types';import { prepareVisualMockDeviceLinkContext } from '@/debug/visualMock';import { meterDeviceLinkInvokes, recordDeviceLinkPush } from '@/debug/deviceLinkTraffic';+import { decodeGzipBase64Text } from '@/utils/gzipBase64';export interface DeviceLinkContextValue {status: DeviceLinkStatus;@@ -946,6 +947,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {}),createWebSocket: createRnWebSocket,logger: mobileDeviceLinkLogger,+ // 弱网减流量:声明可解 gzip,大结果压缩、内容未变的结果只回标记(被控端支持时)。+ transferCodec: { gunzipBase64: decodeGzipBase64Text },// Mobile 具备按 deviceId 独立 openLink/订阅/快照恢复能力。可靠 ACK// 耗尽时只复位该 peer,共享 WSS 和其它远端继续工作;恢复仍只使用所有// Desktop 版本都支持的 link-open,不增加 wire/capability 要求。diff --git a/apps/mobile/src/session/fileBrowserActions.ts b/apps/mobile/src/session/fileBrowserActions.tsindex 94b6996e54..8fa2a4aa22 100644--- a/apps/mobile/src/session/fileBrowserActions.ts+++ b/apps/mobile/src/session/fileBrowserActions.ts@@ -1,8 +1,6 @@/*** 文件浏览的跨屏公共动作:发送到会话(composer 草稿注入)、gzip 文本解码。*/-import { ungzip } from 'pako';-import {readComposerDocumentDraftSync,readComposerDraftSync,@@ -79,37 +77,4 @@ export function mergePathIntoComposerDraft(return merged;}-/** readFile 返回 contentEncoding:'gzip' 时的解码(base64 → gunzip → utf8)。 */-export function decodeGzipBase64Text(contentBase64: string): string {- return ungzip(base64ToUint8Array(contentBase64), { to: 'string' });-}--export function base64ToUint8Array(base64: string): Uint8Array {- const binary = typeof atob === 'function' ? atob(base64) : decodeBase64Fallback(base64);- const bytes = new Uint8Array(binary.length);- for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);- return bytes;-}--const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';--/** Hermes 老版本无全局 atob 的兜底(实现对齐 mobileRealtimeAudio 的做法)。 */-function decodeBase64Fallback(base64: string): string {- const clean = base64.replace(/[^A-Za-z0-9+/=]/g, '');- let output = '';- let i = 0;- while (i < clean.length) {- const enc1 = BASE64_ALPHABET.indexOf(clean.charAt(i++));- const enc2 = BASE64_ALPHABET.indexOf(clean.charAt(i++));- const enc3 = BASE64_ALPHABET.indexOf(clean.charAt(i++));- const enc4 = BASE64_ALPHABET.indexOf(clean.charAt(i++));- const chr1 = (enc1 << 2) | (enc2 >> 4);- const chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);- const chr3 = ((enc3 & 3) << 6) | enc4;- output += String.fromCharCode(chr1);- // `=` 填充位 indexOf 返回 -1;字母表只有 64 个字符,索引恒在 0-63。- if (enc3 !== -1) output += String.fromCharCode(chr2);- if (enc4 !== -1) output += String.fromCharCode(chr3);- }- return output;-}+export { base64ToUint8Array, decodeGzipBase64Text } from '@/utils/gzipBase64';diff --git a/apps/mobile/src/utils/gzipBase64.ts b/apps/mobile/src/utils/gzipBase64.tsnew file mode 100644index 0000000000..b536246425--- /dev/null+++ b/apps/mobile/src/utils/gzipBase64.ts@@ -0,0 +1,40 @@+/**+ * gzip + base64 文本解码,无业务依赖:文件浏览 readFile 与 device-link invoke+ * 结果传输编码共用。+ */+import { ungzip } from 'pako';++/** readFile 返回 contentEncoding:'gzip' 时的解码(base64 → gunzip → utf8)。 */+export function decodeGzipBase64Text(contentBase64: string): string {+ return ungzip(base64ToUint8Array(contentBase64), { to: 'string' });+}++export function base64ToUint8Array(base64: string): Uint8Array {+ const binary = typeof atob === 'function' ? atob(base64) : decodeBase64Fallback(base64);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);+ return bytes;+}++const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';++/** Hermes 老版本无全局 atob 的兜底(实现对齐 mobileRealtimeAudio 的做法)。 */+function decodeBase64Fallback(base64: string): string {+ const clean = base64.replace(/[^A-Za-z0-9+/=]/g, '');+ let output = '';+ let i = 0;+ while (i < clean.length) {+ const enc1 = BASE64_ALPHABET.indexOf(clean.charAt(i++));+ const enc2 = BASE64_ALPHABET.indexOf(clean.charAt(i++));+ const enc3 = BASE64_ALPHABET.indexOf(clean.charAt(i++));+ const enc4 = BASE64_ALPHABET.indexOf(clean.charAt(i++));+ const chr1 = (enc1 << 2) | (enc2 >> 4);+ const chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);+ const chr3 = ((enc3 & 3) << 6) | enc4;+ output += String.fromCharCode(chr1);+ // `=` 填充位 indexOf 返回 -1;字母表只有 64 个字符,索引恒在 0-63。+ if (enc3 !== -1) output += String.fromCharCode(chr2);+ if (enc4 !== -1) output += String.fromCharCode(chr3);+ }+ return output;+}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 5ceda201dd..001a09c4d8 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -48,6 +48,25 @@ known 是消息 ID 与主机提供的 SHA-256 正文指纹对。支持的主机传输去重仅保留有界内存,两端持久展示缓存继续使用原有账号隔离与删除屏障。不修改 relay、不新增权限、数据库 migration 或 Mobile 原生指纹。+## invoke 结果传输编码(弱网减流量)++控制端 `invoke` payload 可选携带 `transfer: { gzip?: 1, ifNoneMatch?: string }`:注入了解压+能力就声明 `gzip: 1`;本机持有同一被控端、同一 channel 与 args 的上一份大结果时,带上它的+内容标签。被控端照常执行 handler,只改写发出的 ok 结果:序列化后不小于 4 KiB 的结果附带+`transfer.tag`(SHA-256);标签与 `ifNoneMatch` 相同时回 `{ result: null, transfer: { tag,+notModified: true } }`;否则在控制端声明可解且压缩确有收益时回 `{ result: null, transfer:+{ tag, gzipBase64 } }`。共享 DeviceLinkClient 在交给调用方之前还原成普通结果,并只用发请求+时固定的缓存快照还原,回包前被淘汰也不影响;标签对不上时返回错误,不返回旧数据。++handler 每次都执行,`notModified` 只省略字节完全相同的结果,因此对所有 channel 语义不变,+不需要逐 channel 登记。控制端缓存按设备、channel、args 键控,最多 32 条、约 8 MB,只在内存,+随客户端 `stop()` 清空;共享任务与供应商分享等跨账号 peer 不使用该编码。旧被控端忽略+`transfer` 回普通结果;旧控制端从不携带 `transfer`,被控端也就不会编码。Desktop(同时作为+被控端与控制端)注入 zlib 与 SHA-256,Mobile 只注入 pako 解压(已有依赖,不改原生指纹)。+relay 不解析隧道 payload,无服务端改动、数据库 migration 或部署顺序要求。实现见+`packages/device-link/src/invokeTransfer.ts`,回归见同目录 `__tests__/invokeTransfer.test.ts`+与 `client.test.ts`「invoke 结果传输编码」。+## 群执行终态与错误展示发送前拒绝、SDK 错误、正常完成和宿主超时进入同一个执行收尾入口;首个终态及提交正文固定,diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 74930d8c33..f9ba13febb 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -2,6 +2,8 @@* DeviceLinkClient 状态机单测:fake WebSocket 注入,覆盖* 握手 / 请求配对 / 超时 / relay-error / 重连退避 / 心跳僵死 / token 缺失。*/+import { createHash } from 'node:crypto';+import { gunzipSync, gzipSync } from 'node:zlib';import { describe, it, expect, vi } from 'vitest';import { DeviceLinkClient, computeReconnectDelayMs, type WsLike } from '../client.js';import {@@ -10,6 +12,7 @@ import {sharedTaskHostPeer,SHARED_TASK_RELAY_CAPABILITY,type Envelope,+ type InvokePayload,type LinkAcceptPayload,} from '../protocol.js';import {@@ -680,8 +683,10 @@ function makeRelayClient(relay: MemoryRelay,deviceId: string,timing?: ConstructorParameters<typeof DeviceLinkClient>[0]['timing'],+ extra?: Pick<ConstructorParameters<typeof DeviceLinkClient>[0], 'transferCodec'>,): DeviceLinkClient {return new DeviceLinkClient({+ ...extra,getWsUrl: () => 'ws://test/api/device-link/ws',getToken: async () => 'jwt-token',getHello: () => ({@@ -7688,6 +7693,107 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {const retriedSeqs = (counts: Map<number, number>): number[] =>[...counts.entries()].filter(([, n]) => n > 1).map(([seq]) => seq).sort((a, b) => a - b);+ it('invoke 结果传输编码:大结果 gzip,内容未变只回 notModified,调用方拿到的结果不变', async () => {+ const codec = {+ gzipBase64: (text: string) => gzipSync(Buffer.from(text, 'utf8')).toString('base64'),+ gunzipBase64: (base64: string) => gunzipSync(Buffer.from(base64, 'base64')).toString('utf8'),+ contentTag: (text: string) => createHash('sha256').update(text).digest('base64url'),+ };+ const relay = new MemoryRelay();+ const host = makeRelayClient(relay, 'desktop', undefined, { transferCodec: codec });+ const controller = makeRelayClient(relay, 'ios', undefined, { transferCodec: codec });+ let rows = Array.from({ length: 400 }, (_, i) => ({ id: `session-${i}`, title: '弱网任务', status: 'idle' }));+ const handled: Envelope[] = [];+ const offHost = host.onFrame((env) => {+ if (env.kind === 'link-open' && env.src && env.id) {+ host.sendLinkAccept(env.src, env.id, { appVersion: '1', allowlistHash: 'hash' });+ }+ if (env.kind === 'invoke' && env.src && env.id) {+ handled.push(env);+ host.sendInvokeResult(env.src, env.id, { ok: true, result: rows });+ }+ });+ host.start();+ controller.start();+ await relay.settleUntil(() => host.getStatus() === 'online' && controller.getStatus() === 'online');+ await Promise.all([+ controller.openLink('desktop', { controllerName: 'iPhone', protocolVersion: 1, appVersion: '1' }, 500),+ relay.settle(),+ ]);+ const resultBytes = () => (relay.deliveredTo.get('ios') ?? [])+ .filter((env) => env.kind === 'invoke-result')+ .reduce((sum, env) => sum + JSON.stringify(env.payload).length, 0);+ const call = async () => {+ const pending = controller.invoke('desktop', { channel: 'local-db:sessions:list', args: [{ filter: 'active' }] }, 1_000);+ await relay.settle();+ return pending;+ };++ const first = await call();+ expect(first).toEqual({ ok: true, result: rows });+ expect(handled[0]!.payload).toMatchObject({ transfer: { gzip: 1 } });+ const plainBytes = JSON.stringify(rows).length;+ const firstBytes = resultBytes();+ expect(firstBytes).toBeLessThan(plainBytes / 4);++ const second = await call();+ expect(second).toEqual({ ok: true, result: rows });+ expect((handled[1]!.payload as InvokePayload).transfer?.ifNoneMatch).toEqual(expect.any(String));+ expect(resultBytes() - firstBytes).toBeLessThan(1_000);+ // Each call returns its own object: a consumer mutating one result cannot corrupt the cache.+ expect(second.ok && second.result).not.toBe(first.ok && first.result);++ rows = rows.map((row, i) => (i === 0 ? { ...row, status: 'running' } : row));+ await expect(call()).resolves.toEqual({ ok: true, result: rows });+ expect(handled).toHaveLength(3);++ offHost();+ host.stop();+ controller.stop();+ }, 10_000);++ it('invoke 结果传输编码:未注入编码器的旧控制端收到的结果与 wire 格式都不变', async () => {+ const relay = new MemoryRelay();+ const host = makeRelayClient(relay, 'desktop', undefined, {+ transferCodec: {+ gzipBase64: (text: string) => gzipSync(Buffer.from(text, 'utf8')).toString('base64'),+ contentTag: (text: string) => createHash('sha256').update(text).digest('base64url'),+ },+ });+ const controller = makeRelayClient(relay, 'ios');+ const rows = Array.from({ length: 400 }, (_, i) => ({ id: `session-${i}` }));+ const handled: Envelope[] = [];+ const offHost = host.onFrame((env) => {+ if (env.kind === 'link-open' && env.src && env.id) {+ host.sendLinkAccept(env.src, env.id, { appVersion: '1', allowlistHash: 'hash' });+ }+ if (env.kind === 'invoke' && env.src && env.id) {+ handled.push(env);+ host.sendInvokeResult(env.src, env.id, { ok: true, result: rows });+ }+ });+ host.start();+ controller.start();+ await relay.settleUntil(() => host.getStatus() === 'online' && controller.getStatus() === 'online');+ await Promise.all([+ controller.openLink('desktop', { controllerName: 'iPhone', protocolVersion: 1, appVersion: '1' }, 500),+ relay.settle(),+ ]);+ for (let i = 0; i < 2; i += 1) {+ const pending = controller.invoke('desktop', { channel: 'maker:provider:list', args: [] }, 1_000);+ await relay.settle();+ await expect(pending).resolves.toEqual({ ok: true, result: rows });+ }+ expect(handled.map((env) => env.payload)).toEqual([+ { channel: 'maker:provider:list', args: [] },+ { channel: 'maker:provider:list', args: [] },+ ]);++ offHost();+ host.stop();+ controller.stop();+ }, 10_000);+it('新确认阶段:首个 link-accept 丢失时不提前发可靠帧,同 stream 重开确认后恢复小帧', async () => {const relay = new MemoryRelay();const host = makeRelayClient(relay, 'desktop');@@ -8556,7 +8662,9 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {payload: { streamId, ackSeq: seqs[2] },},});- await advance(200);+ // seqs[2] was written once, so this ACK is also a ~200ms RTT sample: the+ // retry delay widens to SRTT + 4·RTTVAR (~600ms after first send).+ await advance(400);expect(retriedSeqs(sendsBySeq(ws))).toEqual([...seqs.slice(0, 2), seqs[3], seqs[4]]);}, {pingIntervalMs: 600_000,@@ -9389,6 +9497,118 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {});}, 10_000);+ it('恢复探测收到 ACK 后只放开预算,不立刻重发刚写出、仍在途的探针', async () => {+ await withFakeTimers(async (h, advance) => {+ for (let i = 0; i < 6; i += 1) {+ h.client.sendInvokeResult('dev-b', `req-${i}`, { ok: true, result: i });+ }+ const ws = h.current();+ const seqs = [...sendsBySeq(ws).keys()].sort((a, b) => a - b);+ const streamId = parseTransportPayload(ws.sent.find((env) => env.kind === 'invoke-result')!.payload)!.meta.streamId;+ const internals = h.client as unknown as {+ peerTransport: Map<string, { sendPhase: string; receiveReady: boolean }>;+ };+ internals.peerTransport.get('dev-b')!.sendPhase = 'down';+ internals.peerTransport.get('dev-b')!.receiveReady = false;++ const id = `inbound-link-${++inboundLinkId}`;+ const off = h.client.onFrame((env) => {+ if (env.kind !== 'link-open' || env.id !== id || !env.src) return;+ h.client.sendLinkAccept(env.src, env.id, { appVersion: '1', allowlistHash: 'hash' });+ });+ ws.push({+ v: PROTOCOL_VERSION,+ kind: 'link-open',+ id,+ src: 'dev-b',+ payload: {+ controllerName: 'Remote',+ protocolVersion: 1,+ appVersion: '1',+ capabilities: [+ DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,+ DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,+ ],+ transportStreamId: 'remote-stream-2',+ transportBaseSeq: 1,+ },+ });+ await advance(1);+ off();+ // Recovery pass: the first three frames are re-sent as probes.+ expect(seqs.slice(0, 3).map((seq) => sendsBySeq(ws).get(seq))).toEqual([2, 2, 2]);+ expect(seqs.slice(3).map((seq) => sendsBySeq(ws).get(seq))).toEqual([1, 1, 1]);++ ws.push({+ v: PROTOCOL_VERSION,+ kind: 'push',+ src: 'dev-b',+ payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId, ackSeq: seqs[0] },+ },+ });+ await advance(1);+ // In-flight probes wait for their retry delay; the held tail drains now.+ expect(seqs.slice(1, 3).map((seq) => sendsBySeq(ws).get(seq))).toEqual([2, 2]);+ expect(seqs.slice(3).map((seq) => sendsBySeq(ws).get(seq))).toEqual([2, 2, 2]);+ }, {+ pingIntervalMs: 600_000,+ transportRetryIntervalMs: 10_000,+ transportRetryPassBudget: 3,+ transportMaxRetryAttempts: 50,+ });+ }, 10_000);++ it('多 peer 拓扑:慢链路 peer 的往返估计只放宽它自己的重发,另一个 peer 节奏不变', async () => {+ await withFakeTimers(async (h, advance) => {+ const linked = establishInboundReliableLink(h, 'stream-c', 1, 'dev-c');+ await advance(1);+ await linked;+ const ws = h.current();+ const sendsTo = (dst: string, id: string) => ws.sent.filter((env) => (+ env.kind === 'invoke-result' && env.dst === dst && parseTransportPayload(env.payload) !== null+ && env.id === id+ )).length;+ const ack = (src: string, id: string) => {+ const frame = ws.sent.find((env) => (+ env.kind === 'invoke-result' && env.dst === src && parseTransportPayload(env.payload) !== null+ && env.id === id+ ))!;+ const meta = parseTransportPayload(frame.payload)!.meta;+ ws.push({+ v: PROTOCOL_VERSION,+ kind: 'push',+ src,+ payload: { channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: { streamId: meta.streamId, ackSeq: meta.seq } },+ });+ };++ // dev-b answers after ~3s even though its frame was retried meanwhile.+ h.client.sendInvokeResult('dev-b', 'b-slow', { ok: true, result: 'b' });+ await advance(3_000);+ expect(sendsTo('dev-b', 'b-slow')).toBeGreaterThan(1);+ ack('dev-b', 'b-slow');+ await advance(1);++ h.client.sendInvokeResult('dev-b', 'b-next', { ok: true, result: 'b' });+ h.client.sendInvokeResult('dev-c', 'c-next', { ok: true, result: 'c' });+ await advance(1_000);+ // dev-c keeps the configured 200ms / 400ms / 800ms schedule.+ expect(sendsTo('dev-c', 'c-next')).toBe(3);+ // dev-b waits ~SRTT + 4·RTTVAR before resending into its slow path.+ expect(sendsTo('dev-b', 'b-next')).toBe(1);+ await advance(9_000);+ expect(sendsTo('dev-b', 'b-next')).toBe(2);+ expect(ws.closed).toBeNull();+ }, {+ pingIntervalMs: 600_000,+ transportRetryIntervalMs: 200,+ transportRetryPassBudget: 8,+ transportMaxRetryAttempts: 50,+ });+ }, 10_000);+it('多 peer 拓扑:一个 peer 停止 ACK 被限流,另一个 peer 的投递零感知', async () => {// 故障半径第 3 问(docs/dev-rules/remote-and-mobile-adaptation.md):预算是 per-peer 的,// 一台休眠手机的积压不得拖慢另一台在线设备。diff --git a/packages/device-link/src/__tests__/invokeTransfer.test.ts b/packages/device-link/src/__tests__/invokeTransfer.test.tsnew file mode 100644index 0000000000..8969feb99a--- /dev/null+++ b/packages/device-link/src/__tests__/invokeTransfer.test.ts@@ -0,0 +1,105 @@+import { createHash } from 'node:crypto';+import { gunzipSync, gzipSync } from 'node:zlib';+import { describe, expect, it } from 'vitest';+import {+ INVOKE_TRANSFER_MIN_CHARS,+ InboundInvokeTransferOptions,+ InvokeResultCache,+ encodeInvokeResultTransfer,+ parseInvokeTransferOptions,+ type DeviceLinkTransferCodec,+} from '../invokeTransfer.js';++const codec: Required<DeviceLinkTransferCodec> = {+ gzipBase64: (text) => gzipSync(Buffer.from(text, 'utf8')).toString('base64'),+ gunzipBase64: (base64) => gunzipSync(Buffer.from(base64, 'base64')).toString('utf8'),+ contentTag: (text) => createHash('sha256').update(text).digest('base64url'),+};+const large = { rows: 'a'.repeat(INVOKE_TRANSFER_MIN_CHARS * 4) };++describe('invoke result transfer encoding', () => {+ it('accepts only the documented request options', () => {+ expect(parseInvokeTransferOptions(undefined)).toBeNull();+ expect(parseInvokeTransferOptions({ gzip: true })).toBeNull();+ expect(parseInvokeTransferOptions({ ifNoneMatch: '' })).toBeNull();+ expect(parseInvokeTransferOptions({ ifNoneMatch: 'x'.repeat(129) })).toBeNull();+ expect(parseInvokeTransferOptions({ gzip: 1, ifNoneMatch: 'tag', extra: 1 })).toEqual({ gzip: 1, ifNoneMatch: 'tag' });+ });++ it('leaves small results, errors and already-encoded results unchanged', () => {+ const small = { ok: true as const, result: { id: 1 } };+ expect(encodeInvokeResultTransfer({ gzip: 1 }, small, codec)).toBe(small);+ const failure = { ok: false as const, error: { code: 'IPC_ERROR' as const, message: 'x' } };+ expect(encodeInvokeResultTransfer({ gzip: 1 }, failure, codec)).toBe(failure);+ const encoded = { ok: true as const, result: null, transfer: { tag: 't', notModified: true as const } };+ expect(encodeInvokeResultTransfer({ gzip: 1 }, encoded, codec)).toBe(encoded);+ });++ it('keeps an incompressible result plain but still tags it', () => {+ let seed = 1;+ const noise = Array.from({ length: INVOKE_TRANSFER_MIN_CHARS * 2 }, () => {+ seed = (seed * 1103515245 + 12345) % 2 ** 31;+ return String.fromCharCode(33 + (seed % 90));+ }).join('');+ const payload = { ok: true as const, result: noise };+ const out = encodeInvokeResultTransfer({ gzip: 1 }, payload, codec);+ expect(out).toEqual({ ok: true, result: noise, transfer: { tag: expect.any(String) } });+ });++ it('host without gzip support only tags, and answers a matching tag with notModified', () => {+ const tagOnly = { contentTag: codec.contentTag };+ const first = encodeInvokeResultTransfer({ gzip: 1 }, { ok: true, result: large }, tagOnly);+ expect(first.ok && first.result).toEqual(large);+ const tag = first.ok ? first.transfer?.tag : undefined;+ expect(tag).toEqual(expect.any(String));+ expect(encodeInvokeResultTransfer({ ifNoneMatch: tag }, { ok: true, result: large }, tagOnly))+ .toEqual({ ok: true, result: null, transfer: { tag, notModified: true } });+ });++ it('controller decodes against the snapshot fixed at request time', () => {+ const cache = new InvokeResultCache(codec);+ const request = { channel: 'maker:provider:list', args: [] };+ const first = cache.prepare('desktop', request);+ expect(first.payload).toEqual({ ...request, transfer: { gzip: 1 } });+ const encoded = encodeInvokeResultTransfer({ gzip: 1 }, { ok: true, result: large }, codec);+ expect(first.decode(encoded)).toEqual({ ok: true, result: large });++ const second = cache.prepare('desktop', request);+ const tag = second.payload.transfer?.ifNoneMatch;+ expect(tag).toEqual(expect.any(String));+ // Evicting everything after the request was sent must not lose the snapshot.+ cache.clear();+ expect(second.decode({ ok: true, result: null, transfer: { tag, notModified: true } }))+ .toEqual({ ok: true, result: large });+ // Another peer or other args never reuse this entry.+ expect(cache.prepare('laptop', request).payload.transfer?.ifNoneMatch).toBeUndefined();+ });++ it('turns an unexpected notModified into an error instead of returning stale data', () => {+ const cache = new InvokeResultCache(codec);+ const prepared = cache.prepare('desktop', { channel: 'c', args: [] });+ expect(prepared.decode({ ok: true, result: null, transfer: { tag: 'other', notModified: true } }))+ .toMatchObject({ ok: false, error: { code: 'IPC_ERROR' } });+ });++ it('bounds the controller cache by entry count', () => {+ const cache = new InvokeResultCache(codec);+ for (let i = 0; i < 40; i += 1) {+ const prepared = cache.prepare('desktop', { channel: 'c', args: [i] });+ prepared.decode(encodeInvokeResultTransfer({ gzip: 1 }, { ok: true, result: large }, codec));+ }+ expect(cache.prepare('desktop', { channel: 'c', args: [0] }).payload.transfer?.ifNoneMatch).toBeUndefined();+ expect(cache.prepare('desktop', { channel: 'c', args: [39] }).payload.transfer?.ifNoneMatch).toEqual(expect.any(String));+ });++ it('host keeps a bounded record of request options', () => {+ const inbound = new InboundInvokeTransferOptions();+ inbound.record('ios', 'old', { channel: 'c', args: [], transfer: { gzip: 1 } });+ inbound.record('ios', 'plain', { channel: 'c', args: [] });+ for (let i = 0; i < 512; i += 1) inbound.record('ios', `r-${i}`, { channel: 'c', args: [], transfer: { gzip: 1 } });+ expect(inbound.get('ios', 'old')).toBeUndefined();+ expect(inbound.get('ios', 'plain')).toBeUndefined();+ expect(inbound.get('ios', 'r-511')).toEqual({ gzip: 1 });+ expect(inbound.get('android', 'r-511')).toBeUndefined();+ });+});diff --git a/packages/device-link/src/__tests__/transport.test.ts b/packages/device-link/src/__tests__/transport.test.tsindex 75dfc9c837..94dca97a79 100644--- a/packages/device-link/src/__tests__/transport.test.ts+++ b/packages/device-link/src/__tests__/transport.test.ts@@ -9,6 +9,11 @@ import {makeTransportAck,parseTransportAck,parseTransportPayload,+ reliableRetryDelayMs,+ retransmitBaseMs,+ TRANSPORT_ADAPTIVE_RETRY_MAX_MS,+ updateRetransmitEstimate,+ type RetransmitEstimate,} from '../transport.js';describe('device-link reliable transport codec', () => {@@ -96,3 +101,54 @@ describe('device-link reliable transport codec', () => {});});});++describe('adaptive retransmit interval', () => {+ it('keeps the configured interval until the first round-trip sample', () => {+ const estimate: RetransmitEstimate = { srttMs: null, rttVarMs: 0 };+ expect(retransmitBaseMs(estimate, 2_000)).toBe(2_000);+ });++ it('never retries faster than configured on a fast link', () => {+ const estimate: RetransmitEstimate = { srttMs: null, rttVarMs: 0 };+ for (let i = 0; i < 10; i += 1) updateRetransmitEstimate(estimate, 40);+ expect(retransmitBaseMs(estimate, 2_000)).toBe(2_000);+ });++ it('widens to SRTT + 4·RTTVAR on a slow link and is capped', () => {+ const estimate: RetransmitEstimate = { srttMs: null, rttVarMs: 0 };+ updateRetransmitEstimate(estimate, 1_500);+ expect(retransmitBaseMs(estimate, 2_000)).toBe(1_500 + 4 * 750);+ updateRetransmitEstimate(estimate, 60_000);+ expect(retransmitBaseMs(estimate, 2_000)).toBe(TRANSPORT_ADAPTIVE_RETRY_MAX_MS);+ });++ it('recovers toward the configured interval once the link speeds up', () => {+ const estimate: RetransmitEstimate = { srttMs: null, rttVarMs: 0 };+ updateRetransmitEstimate(estimate, 6_000);+ for (let i = 0; i < 40; i += 1) updateRetransmitEstimate(estimate, 100);+ expect(retransmitBaseMs(estimate, 2_000)).toBe(2_000);+ });++ it('matches the fixed schedule until a round trip is measured', () => {+ const unknown: RetransmitEstimate = { srttMs: null, rttVarMs: 0 };+ expect([1, 2, 3, 4].map((attempts) => reliableRetryDelayMs(unknown, 2_000, 1, attempts)))+ .toEqual([2_000, 4_000, 8_000, 8_000]);+ expect(reliableRetryDelayMs(unknown, 2_000, 13, 1)).toBe(26_000);+ });++ it('does not multiply byte pacing by the slow round trip', () => {+ const slow: RetransmitEstimate = { srttMs: 4_000, rttVarMs: 1_000 };+ expect(reliableRetryDelayMs(slow, 2_000, 1, 1)).toBe(8_000);+ expect(reliableRetryDelayMs(slow, 2_000, 13, 1)).toBe(26_000);+ expect(reliableRetryDelayMs(slow, 2_000, 13, 3)).toBe(32_000);+ });++ it('clamps an outlier sample so one stalled ACK cannot pin the interval at the cap', () => {+ const estimate: RetransmitEstimate = { srttMs: null, rttVarMs: 0 };+ for (let i = 0; i < 10; i += 1) updateRetransmitEstimate(estimate, 300);+ updateRetransmitEstimate(estimate, 120_000);+ expect(estimate.srttMs).toBeLessThan(1_600);+ for (let i = 0; i < 20; i += 1) updateRetransmitEstimate(estimate, 300);+ expect(retransmitBaseMs(estimate, 2_000)).toBe(2_000);+ });+});diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex c83d5e4b81..42cbc969ac 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -1,6 +1,12 @@import { isPeerResetRetryableInvoke, isBackgroundInvoke, bypassInvokeScheduling } from './invokePolicy.js';import { InvokeScheduler } from './invokeScheduler.js';import { SessionMessageReuse } from './sessionMessageReuse.js';+import {+ InboundInvokeTransferOptions,+ InvokeResultCache,+ encodeInvokeResultTransfer,+ type DeviceLinkTransferCodec,+} from './invokeTransfer.js';import { decodeScopedEnvelope, encodeScopedEnvelope, type ScopeSupport } from './providerShareEnvelope.js';import { isProviderSharePeer } from './providerSharePeer.js';import { isSharedTaskPeer } from './sharedTaskPeer.js';@@ -16,6 +22,7 @@ import {MAX_FRAME_BYTES,SERVER_CAPABILITY_NOTIFY,DeviceLinkError,+ isScopedPeer,type Envelope,type HelloPayload,type HelloAckPayload,@@ -53,7 +60,10 @@ import {makeTransportSkipPayload,parseTransportAck,parseTransportPayload,+ reliableRetryDelayMs,+ updateRetransmitEstimate,byteLength,+ type RetransmitEstimate,} from './transport.js';import { MAKER_EVENT_BATCH_CHANNEL } from './topics.js';@@ -252,6 +262,12 @@ export interface DeviceLinkClientOptions {* 由 host 重开 link 后最多重试一次。写请求和长执行请求不走这条路径。*/peerResetReadRetry?: boolean;+ /**+ * invoke 结果传输编码(gzip 与内容标签,见 invokeTransfer.ts)。控制端提供+ * gunzipBase64 才声明可解 gzip;被控端提供 gzipBase64 / contentTag 才编码。+ * 不传时 wire 行为与旧版完全相同。+ */+ transferCodec?: DeviceLinkTransferCodec;/** 测试注入:覆盖重连/心跳的时间参数 */timing?: Partial<DeviceLinkTiming>;}@@ -642,6 +658,8 @@ interface PeerTransportState {recoveryNeedsAck: boolean;/** 本轮恢复探测已写出的帧数(含 replay 与恢复期内首发)。 */recoveryFramesSent: number;+ /** ACK round-trip estimate for this peer; survives link resets on the same network path. */+ rtt: RetransmitEstimate;recoveryTrace: RecoveryTrace | null;/** latest-wins 腾位驱逐的聚合计数(自上次告警起),仅服务日志聚合。 */pushAdmissionDropCount: number;@@ -802,6 +820,7 @@ export class DeviceLinkClient {constructor(opts: DeviceLinkClientOptions) {this.opts = opts;+ this.invokeResultCache = new InvokeResultCache(opts.transferCodec);this.timing = { ...DEFAULT_TIMING, ...opts.timing };this.log = opts.logger ?? {debug: () => {},@@ -989,6 +1008,8 @@ export class DeviceLinkClient {stop(): void {this.messageReuse.clear();+ this.invokeResultCache.clear();+ this.inboundInvokeTransfer.clear();if (this.stopped) return;this.stopped = true;this.clearTimers();@@ -1380,12 +1401,15 @@ export class DeviceLinkClient {): Promise<InvokeResultPayload> {if (this.status !== 'online') throw new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');const reuse = this.messageReuse.prepare(dst, payload);+ const tagged = requestSessionTagCatalog(reuse.payload);+ // Scoped cross-account peers keep the plain wire format.+ const transfer = isScopedPeer(dst) ? null : this.invokeResultCache.prepare(dst, tagged);const send = () => {// Admission may wait: validate caller ownership/cancellation after dequeue,// synchronously before creating the request or retaining a transport frame.options?.preSend?.();return this.request(- { v: PROTOCOL_VERSION, kind: 'invoke', dst, payload: requestSessionTagCatalog(reuse.payload) },+ { v: PROTOCOL_VERSION, kind: 'invoke', dst, payload: transfer?.payload ?? tagged },'invoke-result',timeoutMs,);@@ -1393,7 +1417,9 @@ export class DeviceLinkClient {const env = await (bypassInvokeScheduling(payload) ? send() : this.invokeScheduler.run(dst, isBackgroundInvoke(payload.channel), Math.min(timeoutMs ?? this.timing.requestTimeoutMs, 30_000), send,));- const result = env.payload as InvokeResultPayload;+ const result = transfer+ ? transfer.decode(env.payload as InvokeResultPayload)+ : env.payload as InvokeResultPayload;return result.ok? {...result,@@ -1404,6 +1430,8 @@ export class DeviceLinkClient {/** 被控端:回 invoke-result(对应入站 invoke 的 id) */sendInvokeResult(dst: string, requestId: string, payload: InvokeResultPayload): void {+ const transfer = this.opts.transferCodec ? this.inboundInvokeTransfer.get(dst, requestId) : undefined;+ if (transfer) payload = encodeInvokeResultTransfer(transfer, payload, this.opts.transferCodec!);const peer = this.peerTransport.get(dst);const env: Envelope = { v: PROTOCOL_VERSION, kind: 'invoke-result', id: requestId, dst, payload };// 死锁绕行:relay 在线但控制链路未就绪时,result 不能只进可靠队列等一个可能永远@@ -2860,8 +2888,13 @@ export class DeviceLinkClient {}private readonly messageReuse = new SessionMessageReuse();+ private readonly invokeResultCache: InvokeResultCache;+ private readonly inboundInvokeTransfer = new InboundInvokeTransferOptions();private emitFrame(env: Envelope): boolean | Promise<boolean> {+ if (env.kind === 'invoke' && env.src && env.id && !isScopedPeer(env.src)) {+ this.inboundInvokeTransfer.record(env.src, env.id, env.payload);+ }if (env.kind === 'push' && env.src) {const push = env.payload as { channel: string; payload: unknown };this.messageReuse.receive(env.src, push.channel, push.payload);@@ -3568,6 +3601,7 @@ export class DeviceLinkClient {lastDuplicateOpenRepairAt: Number.NEGATIVE_INFINITY,recoveryNeedsAck: false,recoveryFramesSent: 0,+ rtt: { srttMs: null, rttVarMs: 0 },recoveryTrace: null,pushAdmissionDropCount: 0,pushAdmissionDropLogAt: 0,@@ -3859,20 +3893,33 @@ export class DeviceLinkClient {if (ackSeq > peer.nextSeq - 1 || ackSeq <= peer.highestAckSeq) return;peer.highestAckSeq = ackSeq;this.logRecoveryStage(src, 'ack-received', ` ack=${ackSeq}`, false);+ let rttSample: number | null = null;for (const [seq, pending] of peer.pending) {if (seq > ackSeq) break;if (pending.envelope.id) {this.discardOutboundRouteAttemptsForId(src, pending.envelope.id);}+ // Measured from the first write of this round (replay restarts it), so a+ // slow link still yields samples after its frames were retried; the latest+ // message in the ACK gives the tightest one. Large messages measure+ // transfer time, which byte pacing already covers.+ if (pending.firstSentAt !== undefined && pending.bytes <= RELIABLE_RETRY_BYTES_PER_INTERVAL) {+ rttSample = this.monotonicNow() - pending.firstSentAt;+ }peer.pending.delete(seq);peer.pendingBytes -= pending.bytes;}+ if (rttSample !== null) updateRetransmitEstimate(peer.rtt, rttSample);if (peer.recoveryNeedsAck) {peer.confirmedGapRepair = null;peer.recoveryNeedsAck = false;peer.recoveryFramesSent = 0;this.logRecoveryStage(src, 'recovery-probe-acked', ` ack=${ackSeq}`);- this.retryPending(src, { ignoreInterval: true });+ // Lift the probe budget only. The recovery pass just wrote the head+ // frames; resending them before their retry delay doubles the replay on+ // the slow links that caused the reset (a link-confirm ACK lands within+ // milliseconds of that pass).+ this.retryPending(src, { ignoreInterval: false });} else {const repair = peer.confirmedGapRepair;if (repair && ackSeq >= repair.awaitingSeq) {@@ -4217,9 +4264,11 @@ export class DeviceLinkClient {RELIABLE_RETRY_MAX_SIZE_INTERVALS,Math.ceil(pending.bytes / RELIABLE_RETRY_BYTES_PER_INTERVAL),);- const retryDelayMs = this.timing.transportRetryIntervalMs * Math.max(+ const retryDelayMs = reliableRetryDelayMs(+ peer.rtt,+ this.timing.transportRetryIntervalMs,sizeIntervals,- Math.min(4, 2 ** Math.max(0, pending.attempts - 1)),+ pending.attempts,);if (pending.sent && !opts.ignoreInterval && now - pending.lastSentAt < retryDelayMs) {// A large head frame may still be inside its byte-based cooldown whilediff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.tsindex 1358761bb8..3dbdf7e64a 100644--- a/packages/device-link/src/index.ts+++ b/packages/device-link/src/index.ts@@ -11,6 +11,7 @@ export * from "./protocol.js";export * from "./allowlist.js";export * from "./client.js";export * from "./transport.js";+export * from "./invokeTransfer.js";export * from "./topics.js";export * from "./attachmentOssRef.js";export * from "./contactsSyncProtocol.js";diff --git a/packages/device-link/src/invokeTransfer.ts b/packages/device-link/src/invokeTransfer.tsnew file mode 100644index 0000000000..5ea282fafb--- /dev/null+++ b/packages/device-link/src/invokeTransfer.ts@@ -0,0 +1,216 @@+import type { InvokePayload, InvokeResultPayload } from './protocol.js';++/**+ * invoke 结果的传输编码(弱网减流量),与业务 channel 无关:+ *+ * - 控制端在 invoke payload 上可选携带 `transfer`:能解 gzip 时带 `gzip: 1`;+ * 本机已持有同一 channel + args 的上一份结果时带它的内容标签 `ifNoneMatch`。+ * - 被控端照常执行 handler,只在发出结果时改写:大结果附带内容标签;与+ * `ifNoneMatch` 相同则只回 `notModified`;否则在控制端声明可解时 gzip。+ *+ * handler 每次都真实执行,`notModified` 只省略字节相同的结果,因此对任何+ * channel(包括有副作用的)语义不变。旧被控端忽略 `transfer` 回普通结果;+ * 旧控制端从不携带 `transfer`,被控端也就不会对它编码。+ */++/** 控制端 → 被控端,逐请求可选。 */+export interface InvokeTransferOptions {+ /** 控制端能解开 `gzipBase64` 结果。 */+ gzip?: 1;+ /** 控制端已持有的同 channel + args 结果的内容标签。 */+ ifNoneMatch?: string;+}++/** 被控端 → 控制端,只出现在 ok 结果上;有 `notModified` / `gzipBase64` 时 result 为 null。 */+export interface InvokeResultTransfer {+ /** 完整结果 JSON 的内容标签;控制端据此缓存。 */+ tag?: string;+ notModified?: true;+ /** gzip(UTF-8 JSON.stringify(result)) 的 base64。 */+ gzipBase64?: string;+}++/** host 注入:device-link 包保持零依赖,压缩与摘要由各端平台实现提供。 */+export interface DeviceLinkTransferCodec {+ /** 控制端:解开被控端的 gzip 结果。 */+ gunzipBase64?(base64: string): string;+ /** 被控端:压缩结果。 */+ gzipBase64?(text: string): string;+ /** 被控端:结果内容标签,须抗碰撞(如 SHA-256)。 */+ contentTag?(text: string): string;+}++/** 小结果编码收益抵不过开销,原样发送。 */+export const INVOKE_TRANSFER_MIN_CHARS = 4 * 1024;+const MAX_TAG_CHARS = 128;+/** 缓存键(channel + args)过长说明 args 本身就是大载荷,不值得缓存。 */+const MAX_CACHE_KEY_CHARS = 4 * 1024;+const MAX_CACHE_ENTRIES = 32;+/** JS 字符串按 UTF-16 计,约 8MB 内存。 */+const MAX_CACHE_CHARS = 4 * 1024 * 1024;+const MAX_INBOUND_OPTIONS = 512;++export function parseInvokeTransferOptions(value: unknown): InvokeTransferOptions | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const raw = value as Record<string, unknown>;+ const options: InvokeTransferOptions = {};+ if (raw.gzip === 1) options.gzip = 1;+ if (typeof raw.ifNoneMatch === 'string' && raw.ifNoneMatch.length > 0+ && raw.ifNoneMatch.length <= MAX_TAG_CHARS) {+ options.ifNoneMatch = raw.ifNoneMatch;+ }+ return options.gzip || options.ifNoneMatch ? options : null;+}++/** 被控端:按控制端在该请求上的声明改写 ok 结果;不满足条件时原样返回。 */+export function encodeInvokeResultTransfer(+ options: InvokeTransferOptions,+ payload: InvokeResultPayload,+ codec: DeviceLinkTransferCodec,+): InvokeResultPayload {+ if (!payload.ok || payload.transfer) return payload;+ let text: string | undefined;+ try {+ text = JSON.stringify(payload.result);+ } catch {+ return payload;+ }+ if (text === undefined || text.length < INVOKE_TRANSFER_MIN_CHARS) return payload;+ const tag = codec.contentTag?.(text);+ if (tag !== undefined && options.ifNoneMatch === tag) {+ return { ok: true, result: null, transfer: { tag, notModified: true } };+ }+ if (options.gzip && codec.gzipBase64) {+ const gzipBase64 = codec.gzipBase64(text);+ if (gzipBase64.length < text.length * 0.9) {+ return { ok: true, result: null, transfer: { ...(tag ? { tag } : {}), gzipBase64 } };+ }+ }+ return tag ? { ...payload, transfer: { tag } } : payload;+}++/** 被控端:记住每个入站 invoke 的声明,供回结果(含补发 / 降级重发)时编码。 */+export class InboundInvokeTransferOptions {+ private readonly options = new Map<string, InvokeTransferOptions>();++ record(src: string, requestId: string, payload: unknown): void {+ const transfer = parseInvokeTransferOptions((payload as InvokePayload | undefined)?.transfer);+ if (!transfer) return;+ const key = `${src}\u0000${requestId}`;+ this.options.delete(key);+ this.options.set(key, transfer);+ while (this.options.size > MAX_INBOUND_OPTIONS) {+ this.options.delete(this.options.keys().next().value!);+ }+ }++ get(src: string, requestId: string): InvokeTransferOptions | undefined {+ return this.options.get(`${src}\u0000${requestId}`);+ }++ clear(): void {+ this.options.clear();+ }+}++interface CachedResult {+ tag: string;+ text: string;+}++/** 控制端发出一次 invoke 前固定的编码上下文;结果回来时只用这份快照解码。 */+export interface PreparedInvokeTransfer {+ payload: InvokePayload;+ decode(result: InvokeResultPayload): InvokeResultPayload;+}++/** 控制端:按 peer + channel + args 保留最近的大结果,有界 LRU,只在内存。 */+export class InvokeResultCache {+ private readonly entries = new Map<string, CachedResult>();+ private chars = 0;++ constructor(private readonly codec: DeviceLinkTransferCodec | undefined) {}++ prepare(dst: string, payload: InvokePayload): PreparedInvokeTransfer {+ const key = cacheKey(dst, payload);+ // 请求时固定快照:结果回来前即使被淘汰,notModified 仍能还原。+ const cached = key ? this.entries.get(key) : undefined;+ const transfer: InvokeTransferOptions = {};+ if (this.codec?.gunzipBase64) transfer.gzip = 1;+ if (cached) transfer.ifNoneMatch = cached.tag;+ const prepared = transfer.gzip || transfer.ifNoneMatch ? { ...payload, transfer } : payload;+ return {+ payload: prepared,+ decode: (result) => this.decode(key, cached, result),+ };+ }++ clear(): void {+ this.entries.clear();+ this.chars = 0;+ }++ private decode(+ key: string | null,+ cached: CachedResult | undefined,+ result: InvokeResultPayload,+ ): InvokeResultPayload {+ if (!result.ok || !result.transfer) return result;+ const transfer = result.transfer;+ let text: string;+ let value: unknown;+ try {+ if (transfer.notModified) {+ if (!cached || cached.tag !== transfer.tag) throw new Error('unexpected notModified');+ text = cached.text;+ value = JSON.parse(text);+ } else if (typeof transfer.gzipBase64 === 'string') {+ if (!this.codec?.gunzipBase64) throw new Error('unexpected gzip result');+ text = this.codec.gunzipBase64(transfer.gzipBase64);+ value = JSON.parse(text);+ } else {+ value = result.result;+ text = JSON.stringify(value);+ }+ } catch (err) {+ return {+ ok: false,+ error: {+ code: 'IPC_ERROR',+ message: `[INTERNAL] invalid invoke result transfer: ${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ if (key && typeof transfer.tag === 'string' && transfer.tag.length <= MAX_TAG_CHARS) {+ this.remember(key, { tag: transfer.tag, text });+ }+ return { ok: true, result: value };+ }++ private remember(key: string, entry: CachedResult): void {+ const previous = this.entries.get(key);+ if (previous) {+ this.chars -= previous.text.length;+ this.entries.delete(key);+ }+ if (entry.text.length > MAX_CACHE_CHARS) return;+ this.entries.set(key, entry);+ this.chars += entry.text.length;+ while (this.entries.size > MAX_CACHE_ENTRIES || this.chars > MAX_CACHE_CHARS) {+ const [oldestKey, oldest] = this.entries.entries().next().value!;+ this.chars -= oldest.text.length;+ this.entries.delete(oldestKey);+ }+ }+}++function cacheKey(dst: string, payload: InvokePayload): string | null {+ let args: string;+ try {+ args = JSON.stringify(payload.args ?? []);+ } catch {+ return null;+ }+ const key = `${dst}\u0000${payload.channel}\u0000${args}`;+ return key.length <= MAX_CACHE_KEY_CHARS ? key : null;+}diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.tsindex b911b43bc7..e52ba838cd 100644--- a/packages/device-link/src/protocol.ts+++ b/packages/device-link/src/protocol.ts@@ -26,6 +26,7 @@ import {type RelayErrorCode,type RelayErrorPayload,} from '@cindy/device-link-protocol';+import type { InvokeResultTransfer, InvokeTransferOptions } from './invokeTransfer.js';import { isProviderSharePeer as isProviderSharePeerLocal } from './providerSharePeer.js';import { isSharedTaskPeer as isSharedTaskPeerLocal } from './sharedTaskPeer.js';@@ -205,6 +206,8 @@ export interface LinkClosePayload {export interface InvokePayload {channel: string;args: unknown[];+ /** 可选结果传输编码声明(见 invokeTransfer.ts);旧被控端忽略。 */+ transfer?: InvokeTransferOptions;}/**@@ -213,7 +216,12 @@ export interface InvokePayload {* 控制端 renderer 继续用现有 extractIpcError 解码,错误协议全链路免改。*/export type InvokeResultPayload =- | { ok: true; result: unknown }+ | {+ ok: true;+ result: unknown;+ /** 仅在请求声明了 transfer 时出现;控制端 DeviceLinkClient 在交给调用方前还原。 */+ transfer?: InvokeResultTransfer;+ }| {ok: false;error: { code: DeviceLinkErrorCode | 'IPC_ERROR'; message: string };diff --git a/packages/device-link/src/transport.ts b/packages/device-link/src/transport.tsindex ad94716ecd..b93fe75c4a 100644--- a/packages/device-link/src/transport.ts+++ b/packages/device-link/src/transport.ts@@ -98,6 +98,59 @@ export const TRANSPORT_RETRY_PASS_BUDGET = 8;* 前缀(含新鲜 push 与 transport-skip 占位),保证 invoke-result 是最早的 live seq。*/export const TRANSPORT_PENDING_PUSH_MAX_AGE_MS = 5 * 60_000;+/**+ * 自适应重发间隔的上限。弱网(机上 Wi-Fi、卫星链路)往返常达数秒,固定 2s 重发会+ * 在 ACK 回来前反复写出同一帧,2026-10-12 机上实测 40% 出站字节是重发;但间隔也+ * 不能无限拉长,否则真正断掉的链路要很久才走到重试耗尽的止损。+ */+export const TRANSPORT_ADAPTIVE_RETRY_MAX_MS = 10_000;++/**+ * RFC 6298 平滑往返估计,样本取小消息从本轮首次写出到被累计 ACK 的时长。+ * 不套用 Karn 规则(只采未重发的消息):链路往返超过重发间隔时每帧都会先被+ * 重发,按 Karn 永远采不到样本,自适应恰在最需要时失效。代价是真丢包时样本+ * 偏大,单样本按 TRANSPORT_ADAPTIVE_RETRY_MAX_MS 截断。+ */+export interface RetransmitEstimate {+ srttMs: number | null;+ rttVarMs: number;+}++export function updateRetransmitEstimate(estimate: RetransmitEstimate, sampleMs: number): void {+ const sample = Math.min(TRANSPORT_ADAPTIVE_RETRY_MAX_MS, Math.max(0, sampleMs));+ if (estimate.srttMs === null) {+ estimate.srttMs = sample;+ estimate.rttVarMs = sample / 2;+ return;+ }+ estimate.rttVarMs = 0.75 * estimate.rttVarMs + 0.25 * Math.abs(estimate.srttMs - sample);+ estimate.srttMs = 0.875 * estimate.srttMs + 0.125 * sample;+}++/** 重发基准间隔:不低于配置值,慢链路按 SRTT + 4·RTTVAR 放宽,封顶。 */+export function retransmitBaseMs(estimate: RetransmitEstimate, configuredMs: number): number {+ if (estimate.srttMs === null) return configuredMs;+ const adaptive = Math.min(+ TRANSPORT_ADAPTIVE_RETRY_MAX_MS,+ estimate.srttMs + 4 * estimate.rttVarMs,+ );+ return Math.max(configuredMs, adaptive);+}++/**+ * 单条可靠消息距上次写出后多久可以重发。字节节奏(sizeIntervals)估的是传输耗时,+ * 按配置间隔计;实测往返只放宽按次数的退避。两者取大而不相乘,否则慢链路上的+ * 大回包要等上百秒才重发。往返未知时与原先 configured × max(size, backoff) 相同。+ */+export function reliableRetryDelayMs(+ estimate: RetransmitEstimate,+ configuredMs: number,+ sizeIntervals: number,+ attempts: number,+): number {+ const backoff = Math.min(4, 2 ** Math.max(0, attempts - 1));+ return Math.max(configuredMs * sizeIntervals, retransmitBaseMs(estimate, configuredMs) * backoff);+}const TRANSPORT_MARKER = '__cindyDeviceLinkTransport';const TRANSPORT_SKIP_MARKER = '__cindyDeviceLinkTransportSkip';