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): relay 拥塞断连(1013)引入独立重连冷却,掐断重连-重放-再被踢循环 (#2185)
Dash89867866090b
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 2a81e23f12..68bd8e6e2c 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -914,7 +914,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {}// 回前台立刻重连:绕开断线后遗留的指数退避计时器(可能 park 到 30s),// 让"打开 App → 打开会话"路径快速恢复在线,而不是干等退避。- client.connectNow('appstate-active');+ // overrideCongestionCooldown:用户显式回前台是拥塞冷却的合法豁免——+ // 冷却默认只拦请求路径的 un-park(waitUntilOnline),不拦真人操作。+ client.connectNow('appstate-active', { overrideCongestionCooldown: true });// 快速切换(连接被宽限保住、始终 online)不会有 online 状态转换,这条显式// 补齐就是断档回填的唯一触发点;其余路径下它因 status 未 online 而空转。void rehydrateWithClient(client);diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 488e62b8d7..f235514b3b 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -43,11 +43,17 @@ Cindy 的产品形态不止本地桌面单机。同一个功能可能运行在## 恢复动作先回答故障半径(device-link 共享链路)设备互联是 1:N 拓扑:被控端与 relay 之间只有一条连接,同账号的全部控制端共用它。-故障域从小到大分三层——单个请求、单个 peer 的 link、整条 relay 连接。修改+故障域从小到大分四层——单个请求、单个 peer 的 link、整条 relay 连接、**relay 聚合+背压**(第四层:故障原因不是任何单个请求或 peer,而是本机对 relay 的**聚合出站速率**;+relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即重连 + 全量重放」+的恢复动作都会立刻复现故障,形成「重连 → 洪峰 → 再被踢」的自放大循环,2026-08-08+线上:两次 1013 间隔 15s,第二条连接只活了 7s,期间控制端全部超时熔断)。修改`packages/device-link` 或 Desktop dispatch 层的重试/超时/teardown/重连逻辑前,先回答三个问题:-1. **触发条件是哪一层的故障?** 单个请求失败、单个 peer 停止 ACK,还是整条连接断开?+1. **触发条件是哪一层的故障?** 单个请求失败、单个 peer 停止 ACK、整条连接断开,+ 还是 relay 对聚合速率的背压?对第四层,恢复动作除了同半径(连接级冷却/降速)+ 外还要问一句:**重连成功后的重放会不会立刻重造触发条件?**2. **恢复动作作用在哪一层?** 默认选择与故障同半径的最小动作。动作半径大于故障半径(如「单 peer 可靠重试耗尽 → 强拆整条 relay 连接」)就是把一台设备的故障放大成所有设备同时掉线;确需扩大半径的,必须在 PR 描述里写明理由,且理由要经得起diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex eb6ec658c3..8caae20f9e 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -3,7 +3,7 @@* 握手 / 请求配对 / 超时 / relay-error / 重连退避 / 心跳僵死 / token 缺失。*/import { describe, it, expect, vi } from 'vitest';-import { DeviceLinkClient, type WsLike } from '../client.js';+import { DeviceLinkClient, computeReconnectDelayMs, type WsLike } from '../client.js';import { PROTOCOL_VERSION, DeviceLinkError, type Envelope } from '../protocol.js';import {DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,@@ -4201,3 +4201,212 @@ describe('DeviceLinkClient', () => {});});});++describe('computeReconnectDelayMs(relay 拥塞冷却下限)', () => {+ const timing = {+ reconnectBaseMs: 1_000,+ reconnectMaxMs: 30_000,+ congestionBackoffBaseMs: 5_000,+ congestionBackoffMaxMs: 30_000,+ };++ it('无拥塞信号:维持原指数退避曲线与 0.7x–1.0x 向下抖动', () => {+ expect(computeReconnectDelayMs({ ...timing, attempt: 0, congestionCloseStreak: 0, random: 0 }))+ .toBe(700);+ expect(computeReconnectDelayMs({ ...timing, attempt: 0, congestionCloseStreak: 0, random: 0.9999 }))+ .toBe(1000);+ // 指数封顶 reconnectMaxMs+ expect(computeReconnectDelayMs({ ...timing, attempt: 10, congestionCloseStreak: 0, random: 0 }))+ .toBe(21_000);+ });++ it('拥塞冷却:与普通退避取 max,按连击加深,封顶 congestionBackoffMaxMs', () => {+ // 稳定在线后 attempt 归零,但拥塞连击在:冷却下限接管(5s × 0.7 = 3.5s)+ expect(computeReconnectDelayMs({ ...timing, attempt: 0, congestionCloseStreak: 1, random: 0 }))+ .toBe(3_500);+ expect(computeReconnectDelayMs({ ...timing, attempt: 0, congestionCloseStreak: 2, random: 0 }))+ .toBe(7_000);+ // 连击封顶:5s × 2^3 = 40s > 30s 上限+ expect(computeReconnectDelayMs({ ...timing, attempt: 0, congestionCloseStreak: 4, random: 0 }))+ .toBe(21_000);+ // 普通退避已深于冷却下限时,取普通退避(max 语义,不是叠加)+ expect(computeReconnectDelayMs({ ...timing, attempt: 6, congestionCloseStreak: 1, random: 0 }))+ .toBe(21_000);+ });++ it('入参钳制:非法 attempt/streak/random 不产生 NaN 或负延迟', () => {+ expect(computeReconnectDelayMs({ ...timing, attempt: -3, congestionCloseStreak: -1, random: 0 }))+ .toBe(700);+ expect(computeReconnectDelayMs({ ...timing, attempt: Number.NaN, congestionCloseStreak: 0, random: 2 }))+ .toBe(1_000);+ expect(computeReconnectDelayMs({ ...timing, attempt: 0.9, congestionCloseStreak: 1.9, random: Number.NaN }))+ .toBe(3_500);+ });+});++describe('DeviceLinkClient relay 拥塞断连(close 1013)', () => {+ it('1013 计入拥塞连击,握手成功不清零,稳定在线满窗口才清零;普通断线不计入', async () => {+ const h = makeHarness({+ timing: {+ reconnectBaseMs: 1,+ reconnectMaxMs: 5,+ reconnectStableResetMs: 20,+ congestionBackoffBaseMs: 2,+ congestionBackoffMaxMs: 8,+ pingIntervalMs: 60_000,+ },+ });+ const internals = h.client as unknown as { congestionCloseStreak: number };+ h.client.start();+ await tick();+ h.current().ack();+ expect(internals.congestionCloseStreak).toBe(0);++ // relay 拥塞踢连接:计入连击+ h.current().emit('close', 1013, 'inbound backpressure');+ expect(internals.congestionCloseStreak).toBe(1);++ // 退避后重连成功:握手成功**不**清拥塞连击(与 reconnectAttempt 生命周期不同)+ await tick(40);+ h.current().ack();+ expect(h.client.getStatus()).toBe('online');+ expect(internals.congestionCloseStreak).toBe(1);++ // 稳定在线满 reconnectStableResetMs 后清零+ await tick(100);+ expect(internals.congestionCloseStreak).toBe(0);++ // 普通断线(1006)不计入拥塞连击+ h.current().emit('close', 1006, 'heartbeat lost');+ expect(internals.congestionCloseStreak).toBe(0);+ h.client.stop();+ });++ it('拥塞冷却不被请求路径打穿:waitUntilOnline 不 un-park,显式用户意图 override 才立即重连', async () => {+ // review P1:事故形态下在途请求经 waitUntilOnline → connectNow 清掉冷却+ // 计时器,每次 1013 后仍立即重连,循环掐不断。+ const h = makeHarness({+ timing: {+ reconnectBaseMs: 1,+ reconnectMaxMs: 5,+ // 冷却下限拉大,确保测试窗口内计时器不会自然到点+ congestionBackoffBaseMs: 60_000,+ congestionBackoffMaxMs: 60_000,+ pingIntervalMs: 60_000,+ },+ });+ h.client.start();+ await tick();+ h.current().ack();+ const socketsBefore = h.sockets.length;++ h.current().emit('close', 1013, 'inbound backpressure');+ // 请求路径 un-park:冷却期间必须被 park,不新建连接,有界等待快速失败+ await expect(h.client.waitUntilOnline(30)).rejects.toMatchObject({ code: 'NOT_CONNECTED' });+ expect(h.sockets.length).toBe(socketsBefore);++ // 显式用户意图(移动端回前台):override 立即重连+ h.client.connectNow('appstate-active', { overrideCongestionCooldown: true });+ await tick();+ expect(h.sockets.length).toBe(socketsBefore + 1);+ h.client.stop();+ });++ it('非拥塞断线的 waitUntilOnline un-park 行为不变:立即打断退避重连', async () => {+ const h = makeHarness({+ timing: {+ // 普通退避拉大:不 un-park 的话测试窗口内不会自然重连+ reconnectBaseMs: 60_000,+ reconnectMaxMs: 60_000,+ pingIntervalMs: 60_000,+ },+ });+ h.client.start();+ await tick();+ h.current().ack();+ const socketsBefore = h.sockets.length;++ h.current().emit('close', 1006, 'heartbeat lost');+ const wait = h.client.waitUntilOnline(2_000);+ await tick();+ expect(h.sockets.length).toBe(socketsBefore + 1);+ h.current().ack();+ await expect(wait).resolves.toBeUndefined();+ h.client.stop();+ });++ it('多 peer 拓扑:冷却是连接级的,两个控制端对称受影响、pending 均保留并在重连后各自重放', async () => {+ // 故障半径三问 §3(remote-and-mobile-adaptation):被控端与 relay 只有一条+ // 连接、服务多个控制端。1013 是连接级故障,冷却也只推迟连接级重连——必须+ // 断言它不偏袒/不惩罚任何单个 peer:两边的 link 与 pending 处理完全对称,+ // 且冷却期间不丢在途帧,重连后各自按原 seq 重放(#1187→#1405 的放大判例+ // 正是「单 peer 故障升级成整条连接」,这里反向确认没有引入新的不对称)。+ const h = makeHarness({+ timing: {+ reconnectBaseMs: 1,+ reconnectMaxMs: 5,+ congestionBackoffBaseMs: 20,+ congestionBackoffMaxMs: 20,+ pingIntervalMs: 60_000,+ transportRetryIntervalMs: 60_000, // 重试计时器不参与本用例+ },+ });+ h.client.start();+ await tick();+ h.current().ack();+ await establishInboundReliableLink(h, 'stream-a', 1, 'ctrl-a');+ await establishInboundReliableLink(h, 'stream-b', 1, 'ctrl-b');++ // 在途帧用 invoke-result(live 帧,永不可丢弃):push 是 best-effort 镜像,+ // 建链时会被可丢弃前缀清扫丢掉(#1375),验证不了「pending 跨冷却保留」。+ // 它也正是「另一个 peer 的在途请求回包」这一关注点本身。+ const reliableResultsTo = (dst: string): Envelope[] => h.current().sent.filter(+ (e) => e.kind === 'invoke-result' && e.dst === dst && parseTransportPayload(e.payload) !== null,+ );+ h.client.sendInvokeResult('ctrl-a', 'req-a', { ok: true, result: 'a' });+ h.client.sendInvokeResult('ctrl-b', 'req-b', { ok: true, result: 'b' });+ expect(reliableResultsTo('ctrl-a')).toHaveLength(1);+ expect(reliableResultsTo('ctrl-b')).toHaveLength(1);++ // relay 拥塞踢掉整条共享连接+ const socketsBefore = h.sockets.length;+ h.current().emit('close', 1013, 'inbound backpressure');++ // 冷却期内不重连(对两个 peer 一视同仁:谁都拿不到新连接,也没人被单独放行)+ await tick(8);+ expect(h.sockets.length).toBe(socketsBefore);++ // 冷却到点:重连并重建两条 link → 两个 peer 的 pending 各自按原 seq 重放,+ // 一条都没丢、也没有串到对方的 stream+ await tick(30);+ expect(h.sockets.length).toBe(socketsBefore + 1);+ h.current().ack();+ await establishInboundReliableLink(h, 'stream-a', 1, 'ctrl-a');+ await establishInboundReliableLink(h, 'stream-b', 1, 'ctrl-b');+ await tick();+ const replayedA = reliableResultsTo('ctrl-a');+ const replayedB = reliableResultsTo('ctrl-b');+ expect(replayedA).toHaveLength(1);+ expect(replayedB).toHaveLength(1);+ expect(parseTransportPayload(replayedA[0]!.payload)!.meta.seq).toBe(1);+ expect(parseTransportPayload(replayedB[0]!.payload)!.meta.seq).toBe(1);+ h.client.stop();+ });++ it('stopped 后经 connectNow 拉起 = 新生命周期:拥塞连击清零(与 start 对齐)', async () => {+ const h = makeHarness({+ timing: { reconnectBaseMs: 1, reconnectMaxMs: 5, pingIntervalMs: 60_000 },+ });+ const internals = h.client as unknown as { congestionCloseStreak: number };+ h.client.start();+ await tick();+ h.current().ack();+ h.current().emit('close', 1013, 'inbound backpressure');+ expect(internals.congestionCloseStreak).toBe(1);++ h.client.stop();+ h.client.connectNow('relaunch');+ expect(internals.congestionCloseStreak).toBe(0);+ h.client.stop();+ });+});diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex e4a631bb76..e745e2cb6b 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -41,6 +41,8 @@ import {byteLength,} from './transport.js';const DUPLICATE_CONNECTION_CLOSE_CODE = 4409;+/** RFC 6455 1013 Try Again Later:relay 因拥塞主动断连(如 inbound backpressure)。 */+const RELAY_TRY_AGAIN_LATER_CLOSE_CODE = 1013;/*** latest-wins 腾位适用的**可驱逐通道白名单**(review 三轮收敛:contacts-sync* 黑名单 → 白名单 → 收缩到单通道)。push 单 FIFO 上混着三类语义,只有第一类@@ -211,6 +213,18 @@ export interface DeviceLinkTiming {* 由重连 resync 补偿,invoke-result 的原请求方早已超时,整队放弃无损。*/stalledLinkPendingMaxAgeMs: number;+ /**+ * relay 主动拥塞断连(close 1013 Try Again Later,如 inbound backpressure)+ * 后的重连冷却下限:连续第 N 次拥塞断连后,下一次重连至少等+ * min(congestionBackoffBaseMs × 2^(N-1), congestionBackoffMaxMs),与普通+ * 退避取 max。普通退避在稳定在线(reconnectStableResetMs)后归零,而拥塞+ * 断连恰恰常发生在「在线很久 → 出站洪峰 → 被踢」之后——若冷却随稳定期+ * 归零,客户端会以 1s 级节奏反复「重连 → 全量重放洪峰 → 再被踢」+ * (2026-08-08 线上:两次 1013 间隔仅 15s,第二条连接只活了 7s)。+ * 连续拥塞计数同样只在稳定在线一个 reconnectStableResetMs 后清零。+ */+ congestionBackoffBaseMs: number;+ congestionBackoffMaxMs: number;}const DEFAULT_TIMING: DeviceLinkTiming = {@@ -226,8 +240,44 @@ const DEFAULT_TIMING: DeviceLinkTiming = {transportMaxRetryAttempts: TRANSPORT_MAX_RETRY_ATTEMPTS,presenceRetryIntervalMs: 500,stalledLinkPendingMaxAgeMs: 60_000,+ congestionBackoffBaseMs: 5_000,+ congestionBackoffMaxMs: 30_000,};+/**+ * 重连延迟计算(包内部工具,为确定性单测保持具名导出;**不属于稳定公共+ * API 面**,外部不应依赖):普通指数退避与拥塞冷却下限取 max,再做向下抖动+ * (0.7x–1.0x,与 scheduleReconnect 既有抖动语义一致)。+ * 入参钳制(review P2,防误用产生 NaN/负延迟):attempt / congestionCloseStreak+ * 取整并夹到 ≥0(非有限值按 0),random 夹到 [0,1];streak=0 表示无拥塞信号。+ */+export function computeReconnectDelayMs(input: {+ attempt: number;+ congestionCloseStreak: number;+ reconnectBaseMs: number;+ reconnectMaxMs: number;+ congestionBackoffBaseMs: number;+ congestionBackoffMaxMs: number;+ random: number;+}): number {+ const attempt = Number.isFinite(input.attempt) ? Math.max(0, Math.floor(input.attempt)) : 0;+ const streak = Number.isFinite(input.congestionCloseStreak)+ ? Math.max(0, Math.floor(input.congestionCloseStreak))+ : 0;+ const random = Number.isFinite(input.random) ? Math.min(Math.max(input.random, 0), 1) : 0;+ const base = Math.min(+ input.reconnectBaseMs * 2 ** attempt,+ input.reconnectMaxMs,+ );+ const congestionFloor = streak > 0+ ? Math.min(+ input.congestionBackoffBaseMs * 2 ** (streak - 1),+ input.congestionBackoffMaxMs,+ )+ : 0;+ return Math.round(Math.max(base, congestionFloor) * (0.7 + random * 0.3));+}+export type DeviceLinkStatus = 'stopped' | 'connecting' | 'online';/**@@ -398,6 +448,15 @@ export class DeviceLinkClient {private status: DeviceLinkStatus = 'stopped';private stopped = true;private reconnectAttempt = 0;+ /**+ * 连续 relay 拥塞断连(1013)计数,驱动重连冷却下限(computeReconnectDelayMs)。+ * 与 reconnectAttempt 生命周期刻意不同:attempt 在稳定在线后归零以恢复快速+ * 重连,本计数只在稳定在线满 reconnectStableResetMs 后清零——拥塞信号不因+ * 「重连握手成功」而失效,否则回到「重连 → 重放洪峰 → 再被踢」的紧循环。+ * connectNow / restartConnection(用户显式等待的前台恢复/唤醒)清 attempt+ * 但不清本计数:立即重连可以,但若再被踢,冷却按更深一档生效。+ */+ private congestionCloseStreak = 0;private reconnectTimer: ReturnType<typeof setTimeout> | null = null;private reconnectStableTimer: ReturnType<typeof setTimeout> | null = null;private handshakeTimer: ReturnType<typeof setTimeout> | null = null;@@ -467,6 +526,8 @@ export class DeviceLinkClient {if (!this.stopped) return;this.stopped = false;this.reconnectAttempt = 0;+ // 全新生命周期(登录/切号后 start):不背上一世代的拥塞冷却。+ this.congestionCloseStreak = 0;void this.connect('start');}@@ -476,12 +537,32 @@ export class DeviceLinkClient {* 供"用户正在等"的场景(如移动端回到前台)opt-in,绕开指数退避——* 不改默认退避曲线(桌面端断线重连仍走 scheduleReconnect 的 1s→30s)。* 已 online 时为空操作,不打断健康连接;stopped 时等价于 start()。+ *+ * 拥塞冷却例外(review P1):relay 刚以 1013 拥塞断连、冷却计时器在跑时,+ * 默认**不** un-park——事故形态下恰是在途请求经 waitUntilOnline → connectNow+ * 把每次 1013 后的冷却清掉,「重连 → 重放洪峰 → 再被踢」的循环因此掐不断。+ * 只有显式用户意图(移动端回前台)传 overrideCongestionCooldown 保留立即重连;+ * 被 park 的调用方等冷却计时器到点自然重连(封顶 congestionBackoffMaxMs)。*/- connectNow(reason = 'connect-now'): void {+ connectNow(reason = 'connect-now', opts?: { overrideCongestionCooldown?: boolean }): void {// online 时强制重建请用 restartConnection —— 它才是「半开假活」场景的入口,// 且已包含 resetLinkStateForReconnect(此处曾有一个等价的 { force } 分支,// 生产代码从未使用,只有测试在调,故收敛为单一入口)。if (this.status === 'online') return;+ if (this.stopped) {+ // stopped → 等价 start():全新生命周期不背上一世代的拥塞冷却(review P1,+ // 与 start() 的清零语义对齐)。+ this.congestionCloseStreak = 0;+ } else if (+ this.congestionCloseStreak > 0+ && this.reconnectTimer+ && !opts?.overrideCongestionCooldown+ ) {+ this.log.debug(+ `connectNow(${reason}) parked: congestion cool-down active (streak=${this.congestionCloseStreak})`,+ );+ return;+ }this.stopped = false;this.reconnectAttempt = 0;if (this.reconnectTimer) {@@ -1234,6 +1315,12 @@ export class DeviceLinkClient {`relay replaced this device connection; keeping reconnect backoff warm${reason ? ` (${reason})` : ''}`,);}+ if (code === RELAY_TRY_AGAIN_LATER_CLOSE_CODE) {+ this.congestionCloseStreak++;+ this.log.warn(+ `relay signalled congestion (close=1013${reason ? `, ${reason}` : ''}); reconnect cool-down engaged (streak=${this.congestionCloseStreak})`,+ );+ }// 可分类的失败(鉴权/顶号/超限/版本)记为 issue 供 UI 展示原因;普通断线// 不产生也不清除 issue —— 401 重连风暴里穿插的网络失败不该把原因洗掉。const kind = classifyConnectionIssue(code, reason, this.lastSocketErrorMessage);@@ -1284,16 +1371,23 @@ export class DeviceLinkClient {private scheduleReconnect(): void {if (this.stopped || this.reconnectTimer) return;- const base = Math.min(- this.timing.reconnectBaseMs * 2 ** this.reconnectAttempt,- this.timing.reconnectMaxMs,- );- // 向下抖动(0.7x–1.0x):打散同 deviceId 双连风暴 / 服务重启后的全端齐步重连,- // 上界不变,文档承诺的最大退避(reconnectMaxMs)仍然成立。- const delay = Math.round(base * (0.7 + Math.random() * 0.3));+ // 普通指数退避与拥塞冷却下限取 max;向下抖动(0.7x–1.0x)打散同 deviceId+ // 双连风暴 / 服务重启后的全端齐步重连,上界不变,文档承诺的最大退避+ // (reconnectMaxMs / congestionBackoffMaxMs)仍然成立。+ const delay = computeReconnectDelayMs({+ attempt: this.reconnectAttempt,+ congestionCloseStreak: this.congestionCloseStreak,+ reconnectBaseMs: this.timing.reconnectBaseMs,+ reconnectMaxMs: this.timing.reconnectMaxMs,+ congestionBackoffBaseMs: this.timing.congestionBackoffBaseMs,+ congestionBackoffMaxMs: this.timing.congestionBackoffMaxMs,+ random: Math.random(),+ });this.reconnectAttempt++;this.setStatus('connecting');- this.log.debug(`scheduling device-link reconnect in ${delay}ms (attempt=${this.reconnectAttempt})`);+ this.log.debug(+ `scheduling device-link reconnect in ${delay}ms (attempt=${this.reconnectAttempt}, congestionStreak=${this.congestionCloseStreak})`,+ );this.reconnectTimer = setTimeout(() => {this.reconnectTimer = null;void this.connect('backoff-reconnect');@@ -2909,6 +3003,9 @@ export class DeviceLinkClient {if (this.stopped || this.status !== 'online') return;this.reconnectAttempt = 0;this.shortLivedStreak = 0;+ // 拥塞冷却与普通退避在同一稳定判据下清零:稳定在线一个窗口说明出站+ // 速率已被 relay 接受,下一次普通断线不再背负拥塞冷却。+ this.congestionCloseStreak = 0;if (this.connectionIssue?.kind === 'unstable') this.setConnectionIssue(null);}, this.timing.reconnectStableResetMs);}