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): 分离发送等待并放宽弱网建链确认
Dashbb6e2abbd075
diff --git a/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts b/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.tsindex 979dacf67f..525f7460d6 100644--- a/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts@@ -69,6 +69,21 @@ async function openBreaker(}describe('responsivenessTracker', () => {+ it('local socket queue expiry neither opens the peer circuit nor starts link recovery', async () => {+ const recoverLink = vi.fn(async () => undefined);+ const h = harness({ recoverLink });+ for (let i = 0; i < BREAKER_FAILURE_THRESHOLD + 2; i++) {+ await expect(h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () =>+ Promise.reject(new DeviceLinkError('BACKPRESSURE', 'request expired before socket write')),+ )).rejects.toMatchObject({ code: 'BACKPRESSURE' });+ h.advance(1_100);+ }+ expect(h.tracker.isUnresponsive(DEV)).toBe(false);+ expect(recoverLink).not.toHaveBeenCalled();+ await expect(h.tracker.guardInvoke(OTHER_DEV, 'local-db:sessions:list', async () => ['healthy']))+ .resolves.toEqual(['healthy']);+ });+it('late probe timeout cannot recover a newly opened lifecycle', async () => {const recoverLink = vi.fn(async () => {});const h = harness({ recoverLink });diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 4ce9e8e291..acec93151e 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -155,6 +155,15 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即每设备最多等待 128 条,后台最多占前 96 个等待位置;排队预算不超过 30 秒,排队过期返回 BACKPRESSURE,发送后仍保留原通道执行预算。断连/停止时取消未发送项,在途项仍由既有 transport 结算,不能把取消或超时当成远端操作未执行。+进入 transport 后,invoke 首次写入 socket 前另有最多 `min(通道超时, 10s)` 的发送等待,+到期返回本地 `BACKPRESSURE`,不累计设备无响应次数、不触发 peer 重开。首次成功写入后才+开始原通道响应预算;分片续发和重传不续期,transport 总等待最多为发送等待加响应预算,+业务准入队列的最多 30 秒等待另计。单调时间或墙钟任一到期,恢复重放前均先淘汰请求,+避免睡眠期间计时器停跑后补发过期写操作。断线时,完全未写入的可靠请求立即结束并以 skip+替换,已经写入(含部分分片)的可靠请求保留原回执等待;`inFlight` 不把排队误报为已发送。+建链确认使用 `max(2 × handshakeTimeoutMs, peer 自适应重传基准 × 重试次数)` 的有界等待,+默认冷启动 30 秒、有 RTT 样本时最多 50 秒;重复确认不延长当前确认对象的期限,成功/撤销+取消原计时器。只调整等待预算,不扩大既有故障恢复半径,不改变 wire 协议。调用方的 `preSend` 同步检查在出队后、创建请求前再次执行;排队期间失效的写入必须拒绝发送并释放配额,本地检查失败不作为远端无响应的证据。Desktop 将 BACKPRESSURE 映射为 DEVICE_LINK_BUSY;桌面和手机标签入口显示繁忙与手动重试。diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 64551e5cba..78027034a0 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -8191,6 +8191,7 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {it('新确认阶段:确认重试全部丢失后超时重置 peer,通知控制端重开而非永久等待', async () => {const relay = new MemoryRelay();const host = makeRelayClient(relay, 'desktop', {+ handshakeTimeoutMs: 20,transportRetryIntervalMs: 20,transportMaxRetryAttempts: 3,});@@ -8398,6 +8399,192 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {}}+ it('expires an unsent request as local backpressure and never replays its command', async () => {+ await withFakeTimers(async (h, advance) => {+ const socket = h.current();+ const reset = vi.fn();+ h.client.onPeerTransportReset(reset);+ socket.bufferedAmount = 700 * 1024;+ const result = h.client.invoke('dev-b', { channel: 'maker:send', args: ['never-send'] }, 59_000)+ .catch((error: unknown) => error);+ await advance(10_000);+ expect(await result).toMatchObject({ code: 'BACKPRESSURE', inFlight: false });+ socket.bufferedAmount = 0;+ await advance(250);+ const frames = socket.sent.filter(env => env.kind === 'invoke' && env.dst === 'dev-b');+ expect(frames.length).toBeGreaterThan(0);+ expect(frames.every(env => isTransportSkipPayload(JSON.parse(parseTransportPayload(env.payload)!.data)))).toBe(true);+ const healthy = h.client.invoke('dev-c', { channel: 'local-db:sessions:list', args: [] });+ const request = socket.sent.at(-1)!;+ socket.push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-c', id: request.id,+ payload: { ok: true, result: ['healthy'] } });+ await expect(healthy).resolves.toMatchObject({ result: ['healthy'] });+ expect(reset).not.toHaveBeenCalled();+ expect(socket.closed).toBeNull();+ }, { pingIntervalMs: 600_000 });+ });++ it.each(['stop', 'closeLink'] as const)('reports partial writes separately from unsent commands on %s', async (action) => {+ await withFakeTimers(async (h, advance) => {+ const socket = h.current();+ const send = socket.send.bind(socket);+ let chunks = 0;+ const writer = vi.spyOn(socket, 'send').mockImplementation(data => {+ if (JSON.parse(data).kind === 'invoke' && ++chunks === 2) throw new Error('socket write interrupted');+ send(data);+ });+ const written = h.client.invoke('dev-b', { channel: 'maker:send', args: ['x'.repeat(200 * 1024)] }, 12_000)+ .catch((error: unknown) => error);+ expect(chunks).toBe(2);+ expect(socket.sent.filter(env => env.kind === 'invoke')).toHaveLength(1);+ writer.mockRestore();+ socket.bufferedAmount = 700 * 1024;+ const queued = h.client.invoke('dev-b', { channel: 'maker:send', args: ['never-send'] }, 12_000)+ .catch((error: unknown) => error);+ if (action === 'stop') h.client.stop();+ else h.client.closeLink('dev-b', 'user');+ expect(await written).toMatchObject({ code: 'NOT_CONNECTED', inFlight: true });+ expect(await queued).toMatchObject({ code: 'NOT_CONNECTED', inFlight: false });+ expect(await written).not.toBe(await queued);+ await advance(13_000);+ }, { pingIntervalMs: 600_000 });+ });++ it.each([true, false])('gives a queued request its response budget without renewing it on retries (reply=%s)', async (reply) => {+ await withFakeTimers(async (h, advance) => {+ const socket = h.current();+ socket.bufferedAmount = 700 * 1024;+ let settled = false;+ const result = h.client.invoke('dev-b', { channel: 'local-db:sessions:list', args: [] }, 12_000)+ .then(value => { settled = true; return value; }, error => { settled = true; return error; });+ await advance(9_000);+ socket.bufferedAmount = 0;+ await advance(250);+ const request = socket.sent.find(env => env.kind === 'invoke' && env.dst === 'dev-b')!;+ expect(request).toBeDefined();+ await advance(11_000);+ expect(settled).toBe(false); // Original 12s deadline must not consume 9s of local queuing.+ expect(socket.sent.filter(env => env.id === request.id).length).toBeGreaterThan(1);+ if (reply) {+ encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-b', id: request.id,+ payload: { ok: true, result: ['arrived'] },+ }, 'remote-stream', 1).forEach(frame => socket.push(frame));+ await advance(1);+ expect(await result).toMatchObject({ result: ['arrived'] });+ } else {+ await advance(1_001);+ expect(await result).toMatchObject({ code: 'INVOKE_TIMEOUT', inFlight: true });+ }+ expect(h.sockets).toHaveLength(1);+ }, { pingIntervalMs: 600_000 });+ });++ it.each(['disconnect', 'restart'])('retires only unsent reliable commands on %s and preserves the written request', async (mode) => {+ await withFakeTimers(async (h, advance) => {+ const socket = h.current();+ const written = h.client.invoke('dev-b', { channel: 'maker:send', args: ['already-written'] }, 12_000);+ const request = socket.sent.at(-1)!;+ socket.bufferedAmount = 700 * 1024;+ const queued = h.client.invoke('dev-b', { channel: 'maker:send', args: ['never-send'] }, 12_000)+ .catch((error: unknown) => error);+ if (mode === 'disconnect') socket.emit('close', 1006, 'offline');+ else h.client.restartConnection('test-resume');+ await advance(1_001);+ expect(await queued).toMatchObject({ code: 'NOT_CONNECTED', inFlight: false });+ h.current().ack();+ const linked = establishInboundReliableLink(h, 'remote-stream');+ await advance(1);+ await linked;+ encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-b', id: request.id,+ payload: { ok: true, result: 'receipt' },+ }, 'remote-stream', 1).forEach(frame => h.current().push(frame));+ await advance(1);+ await expect(written).resolves.toMatchObject({ result: 'receipt' });+ expect(h.current().sent.some(env => JSON.stringify(env.payload).includes('never-send'))).toBe(false);+ }, { pingIntervalMs: 600_000 });+ });++ it.each([false, true])('waits for a slow link confirmation without disturbing another peer (learned RTT=%s)', async (learnedRtt) => {+ await withFakeTimers(async (h, advance) => {+ const clock = vi.spyOn(h.client as unknown as { monotonicNow(): number }, 'monotonicNow')+ .mockImplementation(() => Date.now());+ try {+ const socket = h.current();+ const reset = vi.fn();+ h.client.onPeerTransportReset(reset);+ if (learnedRtt) {+ h.client.sendInvokeResult('dev-b', 'rtt-sample', { ok: true, result: true });+ const meta = parseTransportPayload(socket.sent.at(-1)!.payload)!.meta;+ await advance(5_000);+ socket.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: { streamId: meta.streamId, ackSeq: meta.seq },+ } });+ }+ const linked = establishInboundReliableLink(h, 'changed-stream', 1, 'dev-b', [+ DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT, DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,+ DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM,+ ]);+ await advance(1);+ await linked;+ const accept = socket.sent.filter(env => env.kind === 'link-accept').at(-1)!;+ const payload = accept.payload as LinkAcceptPayload;+ await advance(learnedRtt ? 40_000 : 25_000);+ expect(reset).not.toHaveBeenCalled();+ expect(h.client.isLinkReady('dev-b')).toBe(false);+ const healthy = h.client.invoke('dev-c', { channel: 'local-db:sessions:list', args: [] });+ const request = socket.sent.at(-1)!;+ socket.push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-c', id: request.id,+ payload: { ok: true, result: ['healthy'] } });+ await expect(healthy).resolves.toMatchObject({ result: ['healthy'] });+ socket.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId: payload.transportStreamId, ackSeq: (payload.transportBaseSeq ?? 1) - 1, linkRequestId: accept.id },+ } });+ expect(h.client.isLinkReady('dev-b')).toBe(true);+ await advance(30_000); // The confirmation deadline must have been cancelled.+ expect(reset).not.toHaveBeenCalled();+ expect(h.sockets).toHaveLength(1);+ } finally { clock.mockRestore(); }+ }, { pingIntervalMs: 600_000 });+ });++ it('bounds a missing confirmation at 30s while another reliable peer completes its request', async () => {+ await withFakeTimers(async (h, advance) => {+ const socket = h.current();+ const healthyLink = establishInboundReliableLink(h, 'healthy-stream', 1, 'dev-c');+ await advance(1);+ await healthyLink;+ const reset = vi.fn();+ h.client.onPeerTransportReset(reset);+ const linked = establishInboundReliableLink(h, 'changed-stream', 1, 'dev-b', [+ DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT, DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,+ DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM,+ ]);+ await advance(1);+ await linked;+ const healthy = h.client.invoke('dev-c', { channel: 'local-db:sessions:list', args: [] }, 60_000);+ const request = socket.sent.at(-1)!;+ const meta = parseTransportPayload(request.payload)!.meta;+ socket.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-c', payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId: meta.streamId, ackSeq: meta.seq },+ } });+ await advance(29_000);+ expect(reset).not.toHaveBeenCalled();+ await advance(1_000);+ expect(reset).toHaveBeenCalledTimes(1);+ expect(socket.sent.some(env => env.kind === 'link-close' && env.dst === 'dev-b')).toBe(true);+ encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-c', id: request.id,+ payload: { ok: true, result: ['healthy'] },+ }, 'healthy-stream', 1).forEach(frame => socket.push(frame));+ await advance(1);+ await expect(healthy).resolves.toMatchObject({ result: ['healthy'] });+ expect(h.client.isLinkReady('dev-c')).toBe(true);+ expect(socket.closed).toBeNull();+ expect(h.sockets).toHaveLength(1);+ }, { pingIntervalMs: 600_000 });+ });+it('holds a large future response locally until ACK frees receive slots, then sends without the 30s retry wait', async () => {await withFakeTimers(async (h, advance) => {const ws = h.current();@@ -8448,7 +8635,7 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {const outcome = h.client.invoke('dev-b', { channel: 'maker:list-active', args: [] }, 100).catch((error: unknown) => error);await advance(101);- expect(await outcome).toMatchObject({ code: 'INVOKE_TIMEOUT' });+ expect(await outcome).toMatchObject({ code: 'BACKPRESSURE', inFlight: false });expect(ws.sent.some(e => e.kind === 'invoke')).toBe(false);const meta = parseTransportPayload(ws.sent.find(e => e.id === 'held-15')!.payload)!.meta;ws.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', payload: {diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 42cbc969ac..781132ab5c 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -61,6 +61,7 @@ import {parseTransportAck,parseTransportPayload,reliableRetryDelayMs,+ retransmitBaseMs,updateRetransmitEstimate,byteLength,type RetransmitEstimate,@@ -134,6 +135,8 @@ const HANDSHAKE_TIMEOUT_WIDEN_AFTER = 2;/** 「link 未就绪收到可靠帧」通知的 per-peer 节流(见 onReliableFrameBeforeLink)。 */const STALE_LINK_NOTIFY_THROTTLE_MS = 30_000;const SLOW_REQUEST_WARN_MS = 1_000;+/** Local transport admission must not consume a remote handler's response budget. */+const REQUEST_SEND_WAIT_MAX_MS = 10_000;// Stop bulk writes well before the native socket's hard limit. Control envelopes// retain the hard-limit headroom; healthy sockets that drain immediately stay unpaced.const SOCKET_DATA_HIGH_WATER_BYTES = 512 * 1024;@@ -514,8 +517,9 @@ export type InboundFrameHandler = (env: Envelope) => unknown | Promise<unknown>;interface PendingRequest {/** Timers may be suspended; retire an overdue request before replaying its payload. */expireIfOverdue(): boolean;- /** Diagnostics only: first successful socket write, not a delivery receipt. */+ /** First successful socket write starts the response budget; never a delivery receipt. */noteFirstWrite?: () => void;+ hasWritten(): boolean;resolve(env: Envelope): void;reject(err: DeviceLinkError): void;timer: ReturnType<typeof setTimeout>;@@ -1601,6 +1605,9 @@ export class DeviceLinkClient {const startedAt = Date.now();const startedMonotonicAt = this.monotonicNow();let firstWriteAt: number | undefined;+ const sendWaitMs = env.kind === 'invoke' ? Math.min(timeout, REQUEST_SEND_WAIT_MAX_MS) : timeout;+ let deadlineMonotonicAt = startedMonotonicAt + sendWaitMs;+ let deadlineWallAt = startedAt + sendWaitMs;const requestDescription = `${this.describeRequest(env, expectKind)} request=${id.slice(0, 8)}`;const logFinished = (outcome: 'ok' | 'timeout' | 'error', err?: DeviceLinkError): void => {@@ -1633,9 +1640,14 @@ export class DeviceLinkClient {if (env.dst) this.settleOutboundRouteAttemptsForId(env.dst, id);if (env.dst && env.kind === 'invoke') this.dropReliablePendingForRequest(env.dst, id);logFinished('timeout');- reject(new DeviceLinkError('INVOKE_TIMEOUT', `no ${expectKind} within ${timeout}ms`));+ // No physical write is local backpressure, not evidence against the peer.+ const err = firstWriteAt === undefined+ ? new DeviceLinkError('BACKPRESSURE', `request expired before socket write within ${sendWaitMs}ms`)+ : new DeviceLinkError('INVOKE_TIMEOUT', `no ${expectKind} within ${timeout}ms after first socket write`);+ err.inFlight = firstWriteAt !== undefined;+ reject(err);};- const timer = setTimeout(expire, timeout);+ let timer = setTimeout(expire, sendWaitMs);const pendingRequest: PendingRequest = {expireIfOverdue: () => {@@ -1643,12 +1655,25 @@ export class DeviceLinkClient {// clock reaching the budget retires this request: wall time covers// suspension, monotonic time covers wall-clock rollback. A forward// wall correction may expire early, but must not replay stale writes.- if (this.monotonicNow() - startedMonotonicAt < timeout- && Date.now() - startedAt < timeout) return false;+ if (this.monotonicNow() < deadlineMonotonicAt+ && Date.now() < deadlineWallAt) return false;expire();return true;},- noteFirstWrite: () => { firstWriteAt ??= this.monotonicNow(); },+ noteFirstWrite: () => {+ if (firstWriteAt !== undefined) return;+ firstWriteAt = this.monotonicNow();+ // Only the first write can move the deadline. Replays and partial writes+ // cannot extend it; total transport lifetime is at most sendWaitMs + timeout.+ deadlineMonotonicAt = Math.min(firstWriteAt + timeout, startedMonotonicAt + sendWaitMs + timeout);+ deadlineWallAt = Math.min(Date.now() + timeout, startedAt + sendWaitMs + timeout);+ clearTimeout(timer);+ timer = setTimeout(expire, Math.max(0, Math.min(+ deadlineMonotonicAt - this.monotonicNow(), deadlineWallAt - Date.now(),+ )));+ pendingRequest.timer = timer;+ },+ hasWritten: () => firstWriteAt !== undefined,resolve: (frame) => {clearTimeout(timer);logFinished('ok');@@ -1656,8 +1681,12 @@ export class DeviceLinkClient {},reject: (err) => {clearTimeout(timer);- logFinished('error', err);- reject(err);+ // Batch failures can share an error, but each request has its own+ // delivery status (including partial writes). Never mutate the shared error.+ const failure = new DeviceLinkError(err.code, err.message);+ failure.inFlight = firstWriteAt !== undefined;+ logFinished('error', failure);+ reject(failure);},timer,expectKind,@@ -1685,7 +1714,6 @@ export class DeviceLinkClient {'PEER_RESET',`peer link reset before ${expectKind}; host may retry this read once`,);- err.inFlight = true;pendingRequest.reject(err);};}@@ -1710,8 +1738,7 @@ export class DeviceLinkClient {err instanceof DeviceLinkError? err: new DeviceLinkError('INTERNAL', err instanceof Error ? err.message : String(err));- logFinished('error', deviceLinkErr);- reject(deviceLinkErr);+ pendingRequest.reject(deviceLinkErr);}});}@@ -1724,20 +1751,18 @@ export class DeviceLinkClient {private failAllPending(err: DeviceLinkError): void {this.invokeScheduler.clear(err);- // pending 里的请求全部已经 sendEnvelope 成功(in-flight):打上标记,- // 让控制端的重试逻辑知道「请求可能已送达对端,只是响应丢了」,- // 与发送前本地拒绝的 NOT_CONNECTED 区分开。- err.inFlight = true;- for (const [, p] of this.pending) p.reject(err);+ for (const pending of this.pending.values()) {+ pending.reject(err);+ }this.pending.clear();}private failNonReliablePending(err: DeviceLinkError): void {this.invokeScheduler.clear(err);- err.inFlight = true;for (const [id, pending] of this.pending) {- if (pending.reliableDst) continue;+ if (pending.reliableDst && pending.hasWritten()) continue;this.pending.delete(id);+ if (pending.reliableDst) this.dropReliablePendingForRequest(pending.reliableDst, id);pending.reject(err);}}@@ -4434,6 +4459,13 @@ export class DeviceLinkClient {+ ` conn=${this.connEpoch}`,);const attempts = normalizeTransportRetryAttempts(this.timing.transportMaxRetryAttempts);+ // Accept + confirmation crosses the same slow path as a handshake. Keep a+ // cold-path allowance and reuse the peer RTT estimate once available; this+ // single timer stays bounded and retains the existing recovery policy.+ const confirmationTimeoutMs = Math.max(+ this.timing.handshakeTimeoutMs * 2,+ retransmitBaseMs(peer.rtt, normalizeTransportRetryInterval(this.timing.transportRetryIntervalMs)) * attempts,+ );confirmation.timer = setTimeout(() => {confirmation.timer = null;if (@@ -4449,7 +4481,7 @@ export class DeviceLinkClient {+ ` request=${requestId.slice(0, 8)}; resetting peer link`,);this.handleReliableRetryExhausted(dst, confirmation.minimumAckSeq);- }, normalizeTransportRetryInterval(this.timing.transportRetryIntervalMs) * attempts);+ }, confirmationTimeoutMs);}/**@@ -4792,7 +4824,6 @@ export class DeviceLinkClient {peer.pendingBytes = 0;}const err = new DeviceLinkError('NOT_CONNECTED', message);- err.inFlight = true;for (const [id, pending] of this.pending) {if (pending.reliableDst !== dst) continue;this.pending.delete(id);