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): 保留立即重连与读取取消隔离
Dashcd9835189ebd
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 37768f1b00..364bce865d 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -134,19 +134,17 @@ RPC 时才替换。候选失败或仍走中继继续用旧连接;受现有四取消、退后台、切账号依然是取消,不触发 OSS;不并行竞速或预先上传用户文件。回归包含两台控制端一台停滞、另一台持续写入并完成,以及旧端缺能力字段的兼容。-### 共享连接静默与重复读取+### 共享连接静默与请求隔离2026-10-30:Desktop 在业务超时时先检查共享 relay 最近是否仍有入站活动;整条连接静默时复用现有有界网络探测,不直接累加某台电脑的熔断失败。任一 peer 的有效回包都能结束探测;只有共享探测本身超时才恢复整条连接。探测期间后台刷新以未发送的-背压结果退出,前台操作继续按原预算执行。普通 `waitUntilOnline` 不打断重连退避,-显式重试与网络变化仍走原恢复入口。--Desktop/Mobile 共用客户端对已有保守列表白名单的相同在途读取合并;设备、参数、-超时预算或优先级不同则不合并,不缓存完成结果。写操作、强制刷新、推送和断链使-后续读取不再加入旧请求;每个调用方仍执行自己的取消/账号检查。本次恢复不新增-写请求的合并或应用层重试。回归覆盖两台 peer,一台静默时另一台仍能完成前台请求-且共享连接不被拆除。+背压结果退出,前台操作继续按原预算执行。Desktop/Mobile 的 `waitUntilOnline` 保留+原有立即重连入口;已有握手不重复打断,relay 1013 拥塞冷却仍按原规则执行。++相同的列表读取沿用独立请求和发送前取消/账号检查,一个调用方取消不能拖累另一个。+本次恢复不新增请求合并或应用层重试。回归覆盖两台 peer,一台静默时另一台仍能完成+前台请求且共享连接不被拆除。设备互联是 1:N 拓扑:被控端与 relay 之间只有一条连接,同账号的全部控制端共用它。故障域从小到大分四层——单个请求、单个 peer 的 link、整条 relay 连接、**relay 聚合diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex bc0dbf337e..d0df79efe5 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -6820,7 +6820,7 @@ describe('DeviceLinkClient', () => {h.client.stop();});- it('waitUntilOnline preserves backoff; explicit foreground retry can still reconnect', async () => {+ it('waitUntilOnline:离线请求有界等待 —— un-park 退避立即重连,上线后 resolve', async () => {// 退避基数 10s:断线后会 park 一个长计时器,模拟"掉线/重连窗口"。const h = makeHarness({ timing: { reconnectBaseMs: 10_000, reconnectMaxMs: 30_000 } });h.client.start();@@ -6832,10 +6832,7 @@ describe('DeviceLinkClient', () => {expect(h.sockets.length).toBe(1); // 退避还没到,park 住,没新建连接const p = h.client.waitUntilOnline(1_000);- await tick();- expect(h.sockets.length).toBe(1); // A query must not reset DNS/network backoff.- h.client.connectNow('user-retry');- await tick();+ await tick(); // waitUntilOnline 内 connectNow un-park,立刻发起重连expect(h.sockets.length).toBe(2);h.current().ack();await expect(p).resolves.toBeUndefined(); // 上线后放行,而不是干等 10s 退避@@ -7762,65 +7759,40 @@ describe('DeviceLinkClient', () => {});});-// Oct 30: concurrent UI reads piled up during a shared relay outage. Unit tests-// exercise the real client send boundary; existing admission tests only capped-// concurrency, not duplicate reads, invalidation, or shared-vs-peer attribution.+// Unit regression for PR #7975: invoke must isolate cancellation between identical+// queued listings. Prior coverage cancelled only a joining consumer, not the first.+// Minimal input: fill admission, enqueue two identical reads, cancel either one.describe('remote recovery regression', () => {- it('joins concurrent safe listings while preserving consumer cancellation and write freshness', async () => {- const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 5000 } });- try {- h.client.start(); await tick(); h.current().ack();- const payload = { channel: 'local-db:sessions:list', args: [] };- let cancelled = false;- const a = h.client.invoke('a', payload);- const b = h.client.invoke('a', payload);- const c = h.client.invoke('a', payload, undefined, { preSend: () => {- if (cancelled) throw new Error('cancelled consumer');- } }).catch(error => error);- expect(h.current().sent.filter(e => e.kind === 'invoke')).toHaveLength(1);- cancelled = true;- const original = h.current().sent.at(-1)!;- // A write fences subsequent listings even while the original is in flight.- const write = h.client.invoke('a', { channel: 'maker:send', args: [] });- const fresh = h.client.invoke('a', payload);- const other = h.client.invoke('b', payload);- expect(h.current().sent.filter(e => e.kind === 'invoke')).toHaveLength(4);- for (const e of h.current().sent.filter(e => e.kind === 'invoke'))- h.current().push({ v: PROTOCOL_VERSION, kind: 'invoke-result', id: e.id, src: e.dst,- payload: { ok: true, result: [e.id === original.id ? 'old' : 'new'] } });- const [ar, br] = await Promise.all([a, b]);- expect(ar).toEqual(br); expect(ar).not.toBe(br);- expect(ar.ok && ar.result).not.toBe(br.ok && br.result);- expect(await c).toMatchObject({ message: 'cancelled consumer' });- expect(await fresh).toEqual({ ok: true, result: ['new'] });- await Promise.all([write, other]);- } finally { h.client.stop(); }- });-- it('does not join reads across write completion, push invalidation or explicit refresh', async () => {+ it.each([0, 1])('keeps identical queued listings independent when consumer %i cancels', async (cancelIndex) => {+ vi.useFakeTimers();const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });const pending: Promise<unknown>[] = [];try {- h.client.start(); await tick(); h.current().ack();- const listing = { channel: 'local-db:sessions:list', args: [] };+ h.client.start(); await vi.advanceTimersByTimeAsync(0); h.current().ack();const sent = () => h.current().sent.filter(e => e.kind === 'invoke');const reply = (e: Envelope) => h.current().push({ v: PROTOCOL_VERSION, kind: 'invoke-result',- id: e.id, src: e.dst, payload: { ok: true, result: e.id } });- const write = h.client.invoke('a', { channel: 'maker:send', args: [] });- pending.push(write, h.client.invoke('a', listing));- reply(sent()[0]); await write;- pending.push(h.client.invoke('a', listing));- expect(sent()).toHaveLength(3); // A read begun during the write is not fresh after it.- h.current().push({ v: PROTOCOL_VERSION, kind: 'push', src: 'a',- payload: { channel: 'local-db:sessions:changed', payload: {} } });- pending.push(h.client.invoke('a', listing));- expect(sent()).toHaveLength(4);- pending.push(h.client.invoke('a', { channel: listing.channel, args: [null, null, { fresh: true }] }));- pending.push(h.client.invoke('a', listing));- expect(sent()).toHaveLength(6);- for (const e of sent().slice(1)) reply(e);+ id: e.id, src: e.dst, payload: { ok: true, result: 'ok' } });+ for (let i = 0; i < 12; i++) pending.push(h.client.invoke('a', {+ channel: 'local-db:sessions:list', args: [{ request: i }],+ }).catch(error => error));+ expect(sent()).toHaveLength(12);+ const cancelled = [false, false];+ const reads = cancelled.map((_, i) => h.client.invoke('a', {+ channel: 'local-db:sessions:list', args: [],+ }, undefined, { preSend: () => {+ if (cancelled[i]) throw new Error('cancelled consumer');+ } }).catch(error => error));+ pending.push(...reads);+ expect(sent()).toHaveLength(12);+ cancelled[cancelIndex] = true;+ sent().forEach(reply);+ await vi.advanceTimersByTimeAsync(0);+ expect(sent()).toHaveLength(13); // Only the valid caller reaches the wire.+ reply(sent().at(-1)!);+ expect(await reads[cancelIndex]).toMatchObject({ message: 'cancelled consumer' });+ expect(await reads[1 - cancelIndex]).toEqual({ ok: true, result: 'ok' });await Promise.all(pending);- } finally { h.client.stop(); await Promise.allSettled(pending); }+ } finally { h.client.stop(); await Promise.allSettled(pending); vi.useRealTimers(); }});it('probes the shared relay once, pauses background work, and keeps healthy peers connected', async () => {@@ -8237,10 +8209,10 @@ describe('DeviceLinkClient relay 拥塞断连(close 1013)', () => {h.client.stop();});- it('非拥塞断线的普通等待保留退避,显式用户重试可立即重连', async () => {+ it('非拥塞断线的 waitUntilOnline un-park 行为不变:立即打断退避重连', async () => {const h = makeHarness({timing: {- // 普通等待不得将 DNS/网络错误的退避清零。+ // 普通退避拉大:不 un-park 的话测试窗口内不会自然重连reconnectBaseMs: 60_000,reconnectMaxMs: 60_000,pingIntervalMs: 60_000,@@ -8254,9 +8226,6 @@ describe('DeviceLinkClient relay 拥塞断连(close 1013)', () => {h.current().emit('close', 1006, 'heartbeat lost');const wait = h.client.waitUntilOnline(2_000);await tick();- expect(h.sockets.length).toBe(socketsBefore);- h.client.connectNow('user-retry');- await tick();expect(h.sockets.length).toBe(socketsBefore + 1);h.current().ack();await expect(wait).resolves.toBeUndefined();@@ -8429,11 +8398,11 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {await expect(call()).resolves.toEqual({ ok: true, result: rows });expect(handled).toHaveLength(3);- // Distinct caller budgets cannot coalesce: the thirteenth waits for admission. A completed+ // Cold-cache burst: the thirteenth call waits for admission. A completed// earlier result must supply its validator before that queued call is sent.- const burst = Array.from({ length: 13 }, (_, i) => controller.invoke('desktop', {+ const burst = Array.from({ length: 13 }, () => controller.invoke('desktop', {channel: 'local-db:sessions:list', args: [{ filter: 'archived' }],- }, 1_000 + i));+ }, 1_000));await relay.settle();expect(await Promise.all(burst)).toEqual(Array.from({ length: 13 }, () => ({ ok: true, result: rows })));expect((handled.at(-1)!.payload as InvokePayload).transfer?.ifNoneMatch).toEqual(expect.any(String));@@ -10771,7 +10740,7 @@ describe('confirmed duplicate-open gap repair', () => {await open(phone); await open(healthy);// Twelve requests are sent; two remain locally queued and must be cancelled on reconnect.for (let i = 0; i < 12; i++) relay.dropNext((sender, env) => sender === 'desktop' && env.dst === 'phone' && env.kind === 'invoke-result');- const old = Promise.all(Array.from({ length: 14 }, (_, i) => phone.invoke('desktop', { channel: 'maker:provider:list', args: [{ request: i }] }, 60000).catch(e => e)));+ const old = Promise.all(Array.from({ length: 14 }, () => phone.invoke('desktop', { channel: 'maker:provider:list', args: [] }, 60000).catch(e => e)));await pump(); await vi.advanceTimersByTimeAsync(1000);phone.restartConnection('phone-only-reconnect');await vi.advanceTimersByTimeAsync(1); await pump(); await open(phone);diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex e5e7acb561..fdbddc92fc 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -1,4 +1,4 @@-import { isPeerResetRetryableInvoke, bypassInvokeScheduling, resolveInvokePriority, canCoalesceRemoteListing } from './invokePolicy.js';+import { isPeerResetRetryableInvoke, bypassInvokeScheduling, resolveInvokePriority } from './invokePolicy.js';import { InvokeScheduler } from './invokeScheduler.js';import { SessionMessageReuse } from './sessionMessageReuse.js';import {@@ -786,8 +786,6 @@ interface ReceiveStreamState {// ─── 客户端实现 ───────────────────────────────────────────────────────────────export class DeviceLinkClient {- /** Only concurrent listing reads, never a result cache or a write retry. */- private readonly listingReads = new Map<string, Promise<InvokeResultPayload>>();private readonly invokeScheduler = new InvokeScheduler((id) => {const peer = this.peerTransport.get(id);return (this.ws?.bufferedAmount ?? 0) > SOCKET_DATA_LOW_WATER_BYTES@@ -1145,8 +1143,8 @@ export class DeviceLinkClient {* 有界等待连接就绪。online 立即 resolve;否则订阅状态变化,在 timeoutMs 内* 等到 online 就 resolve,超时 / stopped 则 reject(NOT_CONNECTED)。*- * 普通请求只等待既有重连,不清零 DNS/网络错误的指数退避。显式用户重试或- * 前台恢复仍可调用 connectNow;网络变化由 notifyNetworkChanged 处理。+ * Desktop/Mobile 请求等待时可打断普通退避,促成一次立即重连;+ * 已在途的握手和 relay 1013 拥塞冷却仍保留。* 已 stopped 时不自动拉起连接* (start/stop 仍由宿主生命周期掌管),直接快速失败让上层感知。*/@@ -1155,6 +1153,9 @@ export class DeviceLinkClient {if (this.stopped) {return Promise.reject(new DeviceLinkError('NOT_CONNECTED', 'client stopped'));}+ // Only un-park a pending retry; concurrent waiters keep the in-flight handshake.+ if (this.reconnectTimer) this.connectNow('wait-until-online');+const timeout = timeoutMs ?? this.timing.requestTimeoutMs;return new Promise<void>((resolve, reject) => {let off: (() => void) | null = null;@@ -1604,7 +1605,6 @@ export class DeviceLinkClient {reason: LinkCloseReason,direction: 'outbound' | 'inbound' = 'outbound',): void {- this.listingReads.clear();// 本地永久关闭必须同步撤销已排期的 transport-timeout 重试通知:否则迟到// 的回调会在链路已关闭后补发瞬时重置帧,诱使对端重开用户已关掉的控制方向。this.cancelTimeoutCloseNotify(dst);@@ -1678,42 +1678,6 @@ export class DeviceLinkClient {payload: InvokePayload,timeoutMs?: number,options?: { preSend?: () => void; background?: boolean },- ): Promise<InvokeResultPayload> {- const priority = resolveInvokePriority(payload.channel, options?.background);- const coalescible = canCoalesceRemoteListing(payload);- // Fresh reads and writes invalidate joining old reads. A push does the same- // below. Use the existing conservative freshness policy, not retry safety.- if (!coalescible) this.listingReads.clear();- let key: string | undefined;- if (coalescible) {- const serialized = JSON.stringify([dst, payload, timeoutMs, priority]);- if (serialized.length <= 16_384) key = serialized;- }- const existing = key && this.listingReads.get(key);- if (existing) {- options?.preSend?.();- const result = await existing;- options?.preSend?.(); // Each consumer retains its own cancellation/owner check.- return JSON.parse(JSON.stringify(result)) as InvokeResultPayload;- }- const work = this.invokeUnshared(dst, payload, timeoutMs, options);- if (key && this.listingReads.size < 128) this.listingReads.set(key, work);- try {- const result = await work;- if (key) options?.preSend?.();- return key ? JSON.parse(JSON.stringify(result)) as InvokeResultPayload : result;- } finally {- // A read started while a write was in flight can predate its commit too.- if (!coalescible) this.listingReads.clear();- if (key && this.listingReads.get(key) === work) this.listingReads.delete(key);- }- }-- private async invokeUnshared(- dst: string,- payload: InvokePayload,- timeoutMs?: number,- options?: { preSend?: () => void; background?: boolean },): Promise<InvokeResultPayload> {if (this.status !== 'online' && !this.hasOfflineDirectPath(dst)) {throw new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');@@ -2101,7 +2065,6 @@ export class DeviceLinkClient {}private failAllPending(err: DeviceLinkError): void {- this.listingReads.clear();this.invokeScheduler.clear(err);for (const pending of this.pending.values()) {pending.reject(err);@@ -2110,7 +2073,6 @@ export class DeviceLinkClient {}private failNonReliablePending(err: DeviceLinkError): void {- this.listingReads.clear();this.invokeScheduler.clear(err);for (const [id, pending] of this.pending) {if (pending.reliableDst && pending.hasWritten()) continue;@@ -2604,7 +2566,6 @@ export class DeviceLinkClient {return;}if (validForHeartbeat) {- if (env.kind === 'push') this.listingReads.clear();this.lastInboundAt = this.monotonicNow();if (env.src && ROUTED_KINDS.has(env.kind)) this.lastPeerInboundAt = this.lastInboundAt;if (this.networkProbeTimer) {