Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(device-link): soften transient relay heartbeat recovery (#3284)

Chris Zhanga5242af7e641
diff --git a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
index 612188ae01..c567ec8331 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
@@ -48,6 +48,7 @@ describe('mobile voice credential sync desktop bootstrap path', () => {
// 永久放弃后的唯一恢复事件(#1520 review P1)。
expect(deviceLinkHost).toContain('if (available && wasAvailable !== true)');
expect(deviceLinkHost).toContain('replayActiveSubscriptions(`presence-online:${snap.deviceId.slice(0, 8)}`, snap.deviceId);');
+ expect(deviceLinkHost).toContain('createSubscriptionReplayScheduler({');
});
it('每个 relay 连接代上线时从设备目录补齐展示名与已在线桌面', () => {
diff --git a/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts b/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts
new file mode 100644
index 0000000000..8d58c8bdd8
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createSubscriptionReplayScheduler } from '../subscriptionReplayScheduler';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+describe('subscription replay scheduler', () => {
+ it('coalesces ws/presence triggers and replays the latest snapshot after settle', async () => {
+ const deviceId = 'device-a';
+ let refs = [{ deviceId, topics: ['session:one'] }];
+ const first = deferred<unknown>();
+ const calls: string[][] = [];
+ const remoteSubscribe = vi
+ .fn<(id: string, topics: string[]) => Promise<unknown>>()
+ .mockImplementation((_id, topics) => {
+ calls.push([...topics]);
+ return calls.length === 1 ? first.promise : Promise.resolve();
+ });
+ const scheduler = createSubscriptionReplayScheduler({
+ snapshotSubscriptions: () => refs,
+ remoteSubscribe,
+ isLinkTornDown: () => false,
+ isRelayOnline: () => true,
+ isDeviceUnresponsive: () => false,
+ isPresenceAvailable: () => true,
+ isPermanentError: () => false,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+
+ scheduler.replay('ws-online');
+ scheduler.replay('presence-online', deviceId);
+ refs = [{ deviceId, topics: ['session:one', 'session:two'] }];
+
+ expect(remoteSubscribe).toHaveBeenCalledTimes(1);
+ first.resolve(undefined);
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(calls).toEqual([['session:one'], ['session:one', 'session:two']]);
+ });
+
+ it('does not let an old request clear a new generation after teardown and reacquire', async () => {
+ const deviceId = 'device-a';
+ const first = deferred<unknown>();
+ const second = deferred<unknown>();
+ let call = 0;
+ const remoteSubscribe = vi.fn<(id: string, topics: string[]) => Promise<unknown>>().mockImplementation(() => {
+ call += 1;
+ return call === 1 ? first.promise : second.promise;
+ });
+ const scheduler = createSubscriptionReplayScheduler({
+ snapshotSubscriptions: () => [{ deviceId, topics: ['session:one'] }],
+ remoteSubscribe,
+ isLinkTornDown: () => false,
+ isRelayOnline: () => true,
+ isDeviceUnresponsive: () => false,
+ isPresenceAvailable: () => true,
+ isPermanentError: () => false,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+
+ scheduler.replay('ws-online');
+ scheduler.teardown();
+ scheduler.replay('ws-online-reacquire');
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+
+ first.resolve(undefined);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+
+ second.resolve(undefined);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+ });
+
+ it('invalidates retry timers from an old generation', async () => {
+ vi.useFakeTimers();
+ try {
+ const deviceId = 'device-a';
+ const remoteSubscribe = vi
+ .fn<(id: string, topics: string[]) => Promise<unknown>>()
+ .mockRejectedValue(new Error('temporary'));
+ const scheduler = createSubscriptionReplayScheduler({
+ snapshotSubscriptions: () => [{ deviceId, topics: ['session:one'] }],
+ remoteSubscribe,
+ isLinkTornDown: () => false,
+ isRelayOnline: () => true,
+ isDeviceUnresponsive: () => false,
+ isPresenceAvailable: () => true,
+ isPermanentError: () => false,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ retryBaseMs: 10,
+ });
+
+ scheduler.replay('old-generation');
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(remoteSubscribe).toHaveBeenCalledTimes(1);
+
+ scheduler.teardown();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index eedfa7713b..8939488f8a 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -126,6 +126,7 @@ import {
buildSessionNotifyPayload,
type MobileSessionEventKind,
} from './mobileNotify';
+import { createSubscriptionReplayScheduler } from './subscriptionReplayScheduler';
import { getSessionNotificationBody } from '../sessionNotificationCopy';
import { getClientEndpoint } from '../clientEndpointsService';
import {
@@ -1209,8 +1210,7 @@ function teardownActiveLink(): void {
dropAllControllers(client, 'shutdown');
// 熔断状态是账号 / 链路作用域的:登出或失去持有权后全部翻篇,不串到下一段链路。
responsivenessTracker?.resetAll();
- for (const timer of subscriptionReplayRetryTimers.values()) clearTimeout(timer);
- subscriptionReplayRetryTimers.clear();
+ subscriptionReplayScheduler.teardown();
presenceAvailableByDevice.clear();
revokedByRemote.clear();
// 词典同步驱动是进程级的,**不随单次链路起停**:多实例仲裁的 demote → acquire
@@ -1229,39 +1229,9 @@ function teardownActiveLink(): void {
}
function replayActiveSubscriptions(reason: string, deviceId?: string): void {
- const refs = snapshotSubscriptions(deviceId);
- if (refs.length === 0) return;
- const topicCount = refs.reduce((sum, item) => sum + item.topics.length, 0);
- log.debug(
- `device-link replay subscriptions (${reason}): devices=${refs.length} topics=${topicCount}`,
- );
- for (const { deviceId, topics } of refs) {
- // 这里**不套** presence 离线门禁(2026-08-08 review 的收敛结论,别再加回来):
- // - 唯一的广播型调用者是 ws-online,而它跑在「非 online 时清空视图」之后、
- // 本代首帧 presence 之前,当代 presence 必然为空 → 门禁在此恒不成立,是死码;
- // - 其余三个调用者都是定向的(link-reopen / responsiveness-recovered /
- // presence-online),各自的触发证据(收到 link-accept、探测 invoke 刚成功、
- // presence 刚翻成 online)都比 presence 视图更新更强,拿更旧的 presence 去
- // 拦它们只会把恢复事件拦死——与 dispatch 侧「定向 flush 不受门禁约束」同构。
- // 已知离线目标的无效 subscribe 由 replayDeviceSubscription 的重试前置门
- // (presenceAvailableByDevice !== true)在当代内收敛,首发放行一帧即可。
- replayDeviceSubscription(deviceId, topics, reason, 0);
- }
+ subscriptionReplayScheduler.replay(reason, deviceId);
}
-/**
- * 重放失败的退避收敛循环(mobile rehydrate 同精神):重连后的 subscribe 若赶上
- * 链路抖动失败,不再「补 2 次后放弃」——push 流静默缺失会一直持续到下次重连或
- * 用户手动操作。改为 3s×2^n 指数退避、封顶 30s,重试到成功或命中终止条件
- * (登出 / relay 离线 / presence 不可用 / 订阅快照已空)。与熔断器的分工:超时类
- * 失败由 subscribe 回包喂熔断,open 后本循环让位(终止条件之一),恢复时 tracker
- * 触发定向重放接棒;本循环负责熔断覆盖不到的非超时瞬时失败(BACKPRESSURE /
- * NOT_CONNECTED / 链路重建竞态)的持续收敛。
- */
-const SUBSCRIPTION_REPLAY_RETRY_BASE_MS = 3_000;
-const SUBSCRIPTION_REPLAY_RETRY_MAX_MS = 30_000;
-const subscriptionReplayRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();
-
/**
* 订阅重放的永久失败判据:这些码代表「重试同一动作不可能改变结果」的终态
* (协议不符 / 对端明确拒绝 / 授权被收回 / 本机 fail-closed 门),各自有独立的
@@ -1289,87 +1259,22 @@ function isPermanentSubscriptionReplayError(err: unknown): boolean {
return code !== undefined && PERMANENT_SUBSCRIPTION_REPLAY_CODES.has(code);
}
-/**
- * 每设备的重放代次:只有当前代允许排下一次重试。timer map 只能取消**未触发**的
- * 排期,取消不了已在途的 remoteSubscribe——并发触发(ws-online / presence 恢复 /
- * 熔断恢复重叠)会让新旧两轮各自失败后各排各的 timer,旧轮回调还会误删新轮的
- * 登记,退化成多条并行永久循环(review P2)。代次是在途请求失败回调的身份证:
- * 外部触发翻代,旧代失败回调见代次不符即终止,任意并发形态下每设备至多一条
- * 收敛循环存活。
- */
-const subscriptionReplayGenerations = new Map<string, number>();
+const subscriptionReplayScheduler = createSubscriptionReplayScheduler({
+ snapshotSubscriptions,
+ remoteSubscribe,
+ isLinkTornDown: () => linkTornDown,
+ isRelayOnline: () => client?.getStatus() === 'online',
+ isDeviceUnresponsive: (deviceId) => responsivenessTracker?.isUnresponsive(deviceId) ?? false,
+ isPresenceAvailable: (deviceId) => presenceAvailableByDevice.get(deviceId) === true,
+ isPermanentError: isPermanentSubscriptionReplayError,
+ log: {
+ debug: (message) => log.debug(message),
+ warn: (message) => log.warn(message),
+ },
+});
-/**
- * 取消某设备的订阅重放收敛循环:翻代作废在途请求的失败回调 + 清已排期定时器。
- * closeRemoteLink 的取消义务之一——循环无上限收敛后,不取消的话 close 后定时器
- * 仍会以**新代次**重新 remoteSubscribe,经按需建链把用户刚关的链路建回来。
- */
function cancelSubscriptionReplay(deviceId: string): void {
- subscriptionReplayGenerations.set(
- deviceId,
- (subscriptionReplayGenerations.get(deviceId) ?? 0) + 1,
- );
- const timer = subscriptionReplayRetryTimers.get(deviceId);
- if (timer) {
- clearTimeout(timer);
- subscriptionReplayRetryTimers.delete(deviceId);
- }
-}
-
-function replayDeviceSubscription(
- deviceId: string,
- topics: string[],
- reason: string,
- attempt: number,
- generation?: number,
-): void {
- // 外部触发(无 generation)翻代:顶掉挂起的 timer,同时使旧代在途请求失效。
- let gen: number;
- if (generation === undefined) {
- gen = (subscriptionReplayGenerations.get(deviceId) ?? 0) + 1;
- subscriptionReplayGenerations.set(deviceId, gen);
- } else {
- gen = generation;
- }
- const prev = subscriptionReplayRetryTimers.get(deviceId);
- if (prev) {
- clearTimeout(prev);
- subscriptionReplayRetryTimers.delete(deviceId);
- }
- void remoteSubscribe(deviceId, topics).catch((err) => {
- // 旧代在途请求的迟到失败:已被新一轮取代,不再排重试也不动新代的登记。
- if (subscriptionReplayGenerations.get(deviceId) !== gen) return;
- // 永久失败不进收敛循环(review P2):VERSION_MISMATCH 等终态下 presence 可能
- // 一直 online、熔断也把终态应答记为恢复证据,定时器的终止条件全不命中,
- // 移除次数上限后会永久每 30s 重发刷 warn。放弃后由对应终态自己的恢复事件
- // 兜底(presence 翻转 / 版本升级后重连 / 用户显式重开)。
- if (isPermanentSubscriptionReplayError(err)) {
- log.warn(
- `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, permanent, giving up: ${String(err)}`,
- );
- return;
- }
- const delay = Math.min(
- SUBSCRIPTION_REPLAY_RETRY_BASE_MS * 2 ** attempt,
- SUBSCRIPTION_REPLAY_RETRY_MAX_MS,
- );
- log.warn(
- `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, retrying in ${delay}ms: ${String(err)}`,
- );
- const timer = setTimeout(() => {
- subscriptionReplayRetryTimers.delete(deviceId);
- if (subscriptionReplayGenerations.get(deviceId) !== gen) return;
- if (linkTornDown || client?.getStatus() !== 'online') return;
- if (responsivenessTracker?.isUnresponsive(deviceId)) return;
- if (presenceAvailableByDevice.get(deviceId) !== true) return;
- // 快照可能已变(窗口退订 / 新增 topic):按该设备当前的订阅快照重放。
- const current = snapshotSubscriptions(deviceId).find((ref) => ref.deviceId === deviceId);
- if (!current || current.topics.length === 0) return;
- replayDeviceSubscription(deviceId, current.topics, `${reason}-retry`, attempt + 1, gen);
- }, delay);
- timer.unref?.();
- subscriptionReplayRetryTimers.set(deviceId, timer);
- });
+ subscriptionReplayScheduler.cancel(deviceId);
}
export function getDeviceLinkStatus(): DeviceLinkStatus {
diff --git a/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts b/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts
new file mode 100644
index 0000000000..d62b788cb1
--- /dev/null
+++ b/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts
@@ -0,0 +1,146 @@
+export type SubscriptionReplayRef = {
+ deviceId: string;
+ topics: string[];
+};
+
+export type SubscriptionReplayScheduler = {
+ replay(reason: string, deviceId?: string): void;
+ cancel(deviceId: string): void;
+ teardown(): void;
+};
+
+type Timer = ReturnType<typeof setTimeout>;
+
+type SubscriptionReplaySchedulerOptions = {
+ snapshotSubscriptions: (deviceId?: string) => SubscriptionReplayRef[];
+ remoteSubscribe: (deviceId: string, topics: string[]) => Promise<unknown>;
+ isLinkTornDown: () => boolean;
+ isRelayOnline: () => boolean;
+ isDeviceUnresponsive: (deviceId: string) => boolean;
+ isPresenceAvailable: (deviceId: string) => boolean;
+ isPermanentError: (error: unknown) => boolean;
+ log: {
+ debug(message: string): void;
+ warn(message: string): void;
+ };
+ retryBaseMs?: number;
+ retryMaxMs?: number;
+};
+
+/**
+ * Coordinates subscription replay triggers for one relay connection.
+ *
+ * The scheduler deliberately owns only replay state. The caller supplies the
+ * current subscription snapshot and connection gates, so this logic can be
+ * exercised without booting Electron or a real relay.
+ */
+export function createSubscriptionReplayScheduler(
+ options: SubscriptionReplaySchedulerOptions,
+): SubscriptionReplayScheduler {
+ const retryBaseMs = options.retryBaseMs ?? 3_000;
+ const retryMaxMs = options.retryMaxMs ?? 30_000;
+ const retryTimers = new Map<string, Timer>();
+ const inFlight = new Map<string, symbol>();
+ const pendingReruns = new Map<string, string>();
+ const generations = new Map<string, number>();
+
+ const currentGeneration = (deviceId: string): number => generations.get(deviceId) ?? 0;
+
+ const clearTimer = (deviceId: string): void => {
+ const timer = retryTimers.get(deviceId);
+ if (!timer) return;
+ clearTimeout(timer);
+ retryTimers.delete(deviceId);
+ };
+
+ const replayDevice = (
+ deviceId: string,
+ topics: string[],
+ reason: string,
+ attempt: number,
+ generation?: number,
+ ): void => {
+ if (inFlight.has(deviceId)) {
+ pendingReruns.set(deviceId, reason);
+ return;
+ }
+
+ const gen = generation ?? currentGeneration(deviceId) + 1;
+ if (generation === undefined) generations.set(deviceId, gen);
+ clearTimer(deviceId);
+
+ const requestToken = Symbol(deviceId);
+ inFlight.set(deviceId, requestToken);
+ void options.remoteSubscribe(deviceId, topics).catch((error: unknown) => {
+ if (currentGeneration(deviceId) !== gen) return;
+ if (options.isPermanentError(error)) {
+ options.log.warn(
+ `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, permanent, giving up: ${String(error)}`,
+ );
+ return;
+ }
+
+ const delay = Math.min(retryBaseMs * 2 ** attempt, retryMaxMs);
+ options.log.warn(
+ `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, retrying in ${delay}ms: ${String(error)}`,
+ );
+ const timer = setTimeout(() => {
+ retryTimers.delete(deviceId);
+ if (currentGeneration(deviceId) !== gen) return;
+ if (options.isLinkTornDown() || !options.isRelayOnline()) return;
+ if (options.isDeviceUnresponsive(deviceId)) return;
+ if (!options.isPresenceAvailable(deviceId)) return;
+ const current = options
+ .snapshotSubscriptions(deviceId)
+ .find((ref) => ref.deviceId === deviceId);
+ if (!current || current.topics.length === 0) return;
+ replayDevice(deviceId, current.topics, `${reason}-retry`, attempt + 1, gen);
+ }, delay);
+ timer.unref?.();
+ retryTimers.set(deviceId, timer);
+ }).finally(() => {
+ // A teardown/re-acquire can start a new request before an old one settles.
+ // Only the request that registered the token may clear in-flight state.
+ if (inFlight.get(deviceId) !== requestToken) return;
+ inFlight.delete(deviceId);
+ const pendingReason = pendingReruns.get(deviceId);
+ if (!pendingReason) return;
+ pendingReruns.delete(deviceId);
+ if (options.isLinkTornDown() || !options.isRelayOnline()) return;
+ replay(pendingReason + '-pending', deviceId);
+ });
+ };
+
+ const replay = (reason: string, deviceId?: string): void => {
+ const refs = options.snapshotSubscriptions(deviceId);
+ if (refs.length === 0) return;
+ const topicCount = refs.reduce((sum, item) => sum + item.topics.length, 0);
+ options.log.debug(
+ `device-link replay subscriptions (${reason}): devices=${refs.length} topics=${topicCount}`,
+ );
+ for (const ref of refs) replayDevice(ref.deviceId, ref.topics, reason, 0);
+ };
+
+ const cancel = (deviceId: string): void => {
+ generations.set(deviceId, currentGeneration(deviceId) + 1);
+ clearTimer(deviceId);
+ pendingReruns.delete(deviceId);
+ };
+
+ const teardown = (): void => {
+ const devices = new Set([
+ ...retryTimers.keys(),
+ ...inFlight.keys(),
+ ...pendingReruns.keys(),
+ ...generations.keys(),
+ ]);
+ for (const deviceId of devices) {
+ generations.set(deviceId, currentGeneration(deviceId) + 1);
+ clearTimer(deviceId);
+ pendingReruns.delete(deviceId);
+ }
+ inFlight.clear();
+ };
+
+ return { replay, cancel, teardown };
+}
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 62b731cf62..6b0cb2da26 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -3327,6 +3327,278 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('非 pong 的有效入站流量也能阻止心跳误判共享连接', async () => {
+ // 这条验证的是 heartbeat tick 与入站活动的逻辑顺序,不是宿主定时器精度。
+ // Windows 高负载 runner 会把 4ms/8ms 真实 timer 一起推迟,再先执行较早注册的
+ // heartbeat,制造测试自身的假空闲窗口;用 fake timers 固定每个周期的先后关系。
+ vi.useFakeTimers();
+ try {
+ const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(1);
+ const ws = h.current();
+ ws.ack();
+
+ // 模拟 relay 仍在持续推送 presence,但 pong 偶发丢失;有效业务帧证明
+ // 共享 socket 仍有入站流量,不应因单独的 pong 计数拆掉所有 peer。
+ const activity = setInterval(() => {
+ ws.push({
+ v: PROTOCOL_VERSION,
+ kind: 'presence-changed',
+ payload: { deviceId: 'dev-b', online: true, deviceName: 'Test' },
+ });
+ }, 4);
+ await vi.advanceTimersByTimeAsync(50);
+ clearInterval(activity);
+ expect(ws.terminated).toBe(false);
+ expect(h.client.getStatus()).toBe('online');
+ h.client.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('多 peer 心跳:一个 peer 静默时健康 peer 的 link 与在途请求零感知', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({
+ timing: {
+ pingIntervalMs: 8,
+ pongMissLimit: 1,
+ requestTimeoutMs: 200,
+ transportRetryIntervalMs: 60_000,
+ },
+ });
+ let healthyPending: Promise<unknown> | null = null;
+ let activity: ReturnType<typeof setInterval> | null = null;
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(1);
+ const ws = h.current();
+ ws.ack();
+ const silentLink = establishInboundReliableLink(
+ h,
+ 'heartbeat-silent-stream',
+ 1,
+ 'peer-silent',
+ );
+ await vi.advanceTimersByTimeAsync(1);
+ await silentLink;
+ const healthyLink = establishInboundReliableLink(
+ h,
+ 'heartbeat-healthy-stream',
+ 1,
+ 'peer-healthy',
+ );
+ await vi.advanceTimersByTimeAsync(1);
+ await healthyLink;
+ expect(h.client.isLinkReady('peer-silent')).toBe(true);
+ expect(h.client.isLinkReady('peer-healthy')).toBe(true);
+
+ // peer-silent 此后不再发送任何帧;peer-healthy 上保留一个真实在途请求。
+ healthyPending = h.client.invoke('peer-healthy', {
+ channel: 'local-db:sessions:list',
+ args: [10],
+ }, 200);
+ const healthyInvoke = ws.sent
+ .filter((env) => env.kind === 'invoke' && env.dst === 'peer-healthy')
+ .at(-1)!;
+ const socketsBefore = h.sockets.length;
+
+ // relay 仍持续报告健康 peer 的有效入站活动,但 pong 丢失。heartbeat 必须按
+ // 共享 socket 的真实活性判断,不能因另一 peer 静默拆掉所有 link。
+ activity = setInterval(() => {
+ ws.push({
+ v: PROTOCOL_VERSION,
+ kind: 'presence-changed',
+ payload: { deviceId: 'peer-healthy', online: true, deviceName: 'Healthy' },
+ });
+ }, 4);
+ await vi.advanceTimersByTimeAsync(50);
+ clearInterval(activity);
+ activity = null;
+
+ expect(ws.terminated).toBe(false);
+ expect(h.sockets).toHaveLength(socketsBefore);
+ expect(h.client.isLinkReady('peer-silent')).toBe(true);
+ expect(h.client.isLinkReady('peer-healthy')).toBe(true);
+
+ ws.push({
+ v: PROTOCOL_VERSION,
+ kind: 'invoke-result',
+ id: healthyInvoke.id,
+ src: 'peer-healthy',
+ payload: { ok: true, result: ['healthy-ok'] },
+ });
+ await expect(healthyPending).resolves.toMatchObject({
+ ok: true,
+ result: ['healthy-ok'],
+ });
+ } finally {
+ if (activity) clearInterval(activity);
+ h.client.stop();
+ await healthyPending?.catch(() => undefined);
+ vi.useRealTimers();
+ }
+ });
+
+ it('可解析但协议无效的入站帧不会刷新 heartbeat 活性', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });
+ h.client.start();
+ await tick();
+ const ws = h.current();
+ ws.ack();
+
+ const invalidFrames = [
+ { v: PROTOCOL_VERSION + 1, kind: 'pong' },
+ { v: PROTOCOL_VERSION, kind: 'future-kind' },
+ {
+ v: PROTOCOL_VERSION,
+ kind: 'presence-changed',
+ payload: { online: true },
+ },
+ ] as unknown as Envelope[];
+ let index = 0;
+ const activity = setInterval(() => {
+ ws.push(invalidFrames[index % invalidFrames.length]);
+ index += 1;
+ }, 4);
+ for (let i = 0; i < 40 && !ws.terminated; i++) await tick(10);
+ clearInterval(activity);
+
+ expect(ws.terminated).toBe(true);
+ expect(h.client.getStatus()).toBe('connecting');
+ h.client.stop();
+ });
+
+ it('畸形 invoke 继续分发但不会喂活 heartbeat', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });
+ const frames: Envelope[] = [];
+ h.client.onFrame((env) => frames.push(env));
+ h.client.start();
+ await tick();
+ const ws = h.current();
+ ws.ack();
+
+ const malformed = {
+ v: PROTOCOL_VERSION,
+ kind: 'invoke',
+ id: 'malformed-heartbeat-invoke',
+ src: 'dev-b',
+ payload: { args: [] },
+ } as unknown as Envelope;
+ const activity = setInterval(() => ws.push(malformed), 4);
+ for (let i = 0; i < 40 && !ws.terminated; i++) await tick(10);
+ clearInterval(activity);
+
+ expect(frames.length).toBeGreaterThan(0);
+ expect(ws.terminated).toBe(true);
+ expect(h.client.getStatus()).toBe('connecting');
+ h.client.stop();
+ });
+
+ it('缺少 src 或 id 的 legacy invoke 不会喂活 heartbeat', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(1);
+ const ws = h.current();
+ ws.ack();
+
+ const malformed = {
+ v: PROTOCOL_VERSION,
+ kind: 'invoke',
+ payload: { channel: 'maker:valid-looking', args: [] },
+ } as unknown as Envelope;
+ const activity = setInterval(() => ws.push(malformed), 4);
+ await vi.advanceTimersByTimeAsync(50);
+ clearInterval(activity);
+
+ expect(ws.terminated).toBe(true);
+ expect(h.client.getStatus()).toBe('connecting');
+ h.client.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('可靠 invoke 分片在重组前也算入站活性', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 50, pongMissLimit: 2 } });
+ h.client.start();
+ await tick();
+ h.current().ack();
+ await establishInboundReliableLink(h, 'heartbeat-fragment-stream');
+
+ const frames = encodeReliableFrames({
+ v: PROTOCOL_VERSION,
+ kind: 'invoke',
+ id: 'fragmented-heartbeat-invoke',
+ src: 'dev-b',
+ dst: 'dev-self',
+ payload: { channel: 'maker:large', args: ['x'.repeat(150_000)] },
+ }, 'heartbeat-fragment-stream', 1);
+ expect(frames.length).toBeGreaterThan(1);
+
+ const activity = setInterval(() => {
+ for (const frame of frames) h.current().push(frame);
+ }, 10);
+ await tick(180);
+ clearInterval(activity);
+
+ expect(h.current().terminated).toBe(false);
+ expect(h.client.getStatus()).toBe('online');
+ h.client.stop();
+ });
+
+ it('缺少 src 或 id 的可靠 invoke 不会喂活 heartbeat', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });
+ h.client.start();
+ await tick();
+ h.current().ack();
+ await establishInboundReliableLink(h, 'heartbeat-missing-id-stream');
+ const ws = h.current();
+
+ const malformed = encodeReliableFrames({
+ v: PROTOCOL_VERSION,
+ kind: 'invoke',
+ payload: { channel: 'maker:valid-looking', args: [] },
+ }, 'heartbeat-missing-id-stream', 1)[0]!;
+ const activity = setInterval(() => ws.push(malformed), 4);
+ for (let i = 0; i < 40 && !ws.terminated; i++) await tick(10);
+ clearInterval(activity);
+
+ expect(ws.terminated).toBe(true);
+ expect(h.client.getStatus()).toBe('connecting');
+ h.client.stop();
+ });
+
+ it('heartbeat idle 使用单调时钟,不受系统时间回拨影响', async () => {
+ const proto = DeviceLinkClient.prototype as unknown as { monotonicNow(): number };
+ let monotonicMs = 100;
+ const monotonic = vi.spyOn(proto, 'monotonicNow').mockImplementation(() => monotonicMs);
+ const wallClock = vi.spyOn(Date, 'now').mockReturnValue(1_000_000);
+ try {
+ const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });
+ h.client.start();
+ await tick();
+ const ws = h.current();
+ ws.ack();
+ wallClock.mockReturnValue(-1_000_000);
+
+ for (let i = 0; i < 40 && !ws.terminated; i++) {
+ monotonicMs += 10;
+ await tick(10);
+ }
+
+ expect(ws.terminated).toBe(true);
+ expect(h.client.getStatus()).toBe('connecting');
+ h.client.stop();
+ } finally {
+ wallClock.mockRestore();
+ monotonic.mockRestore();
+ }
+ });
+
it('getToken 返回 null:不建连,按退避重试', async () => {
const h = makeHarness({ token: null });
h.client.start();
@@ -3370,6 +3642,64 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('畸形 invoke 仍交给业务层生成结构化拒绝', async () => {
+ const h = makeHarness();
+ const frames: Envelope[] = [];
+ h.client.onFrame((e) => frames.push(e));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'invoke',
+ id: 'malformed-invoke',
+ src: 'dev-a',
+ payload: { channel: 'maker:send' },
+ });
+
+ expect(frames).toHaveLength(1);
+ expect(frames[0]).toMatchObject({
+ kind: 'invoke',
+ id: 'malformed-invoke',
+ payload: { channel: 'maker:send' },
+ });
+ h.client.stop();
+ });
+
+ it('畸形 link-close 仍交给业务层收口但不会喂活 heartbeat', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });
+ const frames: Envelope[] = [];
+ let activity: ReturnType<typeof setInterval> | null = null;
+ try {
+ h.client.onFrame((env) => frames.push(env));
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(1);
+ const ws = h.current();
+ ws.ack();
+
+ const malformed = {
+ v: PROTOCOL_VERSION,
+ kind: 'link-close',
+ src: 'dev-a',
+ payload: {},
+ } as unknown as Envelope;
+ activity = setInterval(() => ws.push(malformed), 4);
+ await vi.advanceTimersByTimeAsync(50);
+ if (activity) clearInterval(activity);
+ activity = null;
+
+ expect(frames.length).toBeGreaterThan(0);
+ expect(ws.terminated).toBe(true);
+ expect(h.client.getStatus()).toBe('connecting');
+ } finally {
+ if (activity) clearInterval(activity);
+ h.client.stop();
+ vi.useRealTimers();
+ }
+ });
+
it('epoch 守卫:过期 socket 的迟到 close/message 回调被忽略,不触发额外重连', async () => {
const h = makeHarness();
h.client.start();
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index c4fac10447..977b567f96 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -199,7 +199,7 @@ export interface DeviceLinkTiming {
*/
reconnectStableResetMs: number;
pingIntervalMs: number;
- /** 连续无 pong 判定僵死的周期数 */
+ /** 连续无 pong 判定僵死的周期数;入站业务流量会把这组计数清零。 */
pongMissLimit: number;
/** invoke / link-open 默认等待响应时长 */
requestTimeoutMs: number;
@@ -258,7 +258,8 @@ const DEFAULT_TIMING: DeviceLinkTiming = {
reconnectMaxMs: 30_000,
reconnectStableResetMs: 10_000,
pingIntervalMs: 20_000,
- pongMissLimit: 2,
+ // 允许弱网在一个额外周期内恢复;真正无响应仍由连续 miss + 无入站流量判定。
+ pongMissLimit: 3,
requestTimeoutMs: 30_000,
getTokenTimeoutMs: 15_000,
handshakeTimeoutMs: 15_000,
@@ -567,6 +568,8 @@ export class DeviceLinkClient {
private handshakeTimeoutStreak = 0;
private pingTimer: ReturnType<typeof setInterval> | null = null;
private pongMisses = 0;
+ /** 最近一次收到任何有效 relay 帧的时刻;避免把有业务流量的 socket 误判为僵死。 */
+ private lastInboundAt = 0;
/** 当前连接的代号,用于丢弃过期 socket 的事件回调 */
private connEpoch = 0;
/** 本轮连接的最后一条 socket error message(升级失败 401 只在 error 事件里可见) */
@@ -1540,11 +1543,20 @@ export class DeviceLinkClient {
this.pingTimer = null;
}
this.pongMisses = 0;
+ this.lastInboundAt = this.monotonicNow();
this.pingTimer = setInterval(() => {
if (this.status !== 'online') return;
+ const now = this.monotonicNow();
+ // pong 之外的有效入站帧同样证明 relay/socket 仍在工作。弱网下 pong
+ // 可能丢在业务帧之后,不能因为单独的心跳计数把共享连接整条拆掉。
+ if (now - this.lastInboundAt <= this.timing.pingIntervalMs) {
+ this.pongMisses = 0;
+ }
this.pongMisses++;
if (this.pongMisses > this.timing.pongMissLimit) {
- this.log.warn('heartbeat lost, forcing reconnect');
+ this.log.warn(
+ `heartbeat lost, forcing reconnect (misses=${this.pongMisses}, idleForMs=${now - this.lastInboundAt})`,
+ );
const ws = this.ws;
this.ws = null;
this.connEpoch++;
@@ -1628,13 +1640,27 @@ export class DeviceLinkClient {
// ─── 内部:入站分发 ─────────────────────────────────────────────────────────
private handleMessage(raw: string): void {
- let env: Envelope;
+ let parsed: unknown;
try {
- env = JSON.parse(raw) as Envelope;
+ parsed = JSON.parse(raw) as unknown;
} catch {
this.log.warn('dropping unparseable frame');
return;
}
+ if (!isKnownInboundEnvelope(parsed)) {
+ this.log.warn('dropping invalid device-link frame');
+ return;
+ }
+ const env = parsed;
+ const validForHeartbeat = isValidInboundEnvelope(env);
+ // 畸形 invoke / link-close 仍须进入 Desktop 业务层:前者生成结构化拒绝,后者
+ // 走既有 fail-generic 的 peer teardown;但两者都不能因此喂活 heartbeat。
+ // 其它已知 kind 的非法 payload 直接丢弃。
+ if (!validForHeartbeat && env.kind !== 'invoke' && env.kind !== 'link-close') {
+ this.log.warn(`dropping invalid device-link frame kind=${env.kind}`);
+ return;
+ }
+ if (validForHeartbeat) this.lastInboundAt = this.monotonicNow();
const ack = parseTransportAck(env);
if (ack) {
@@ -3555,6 +3581,140 @@ function closeReasonToString(reason: unknown): string {
return text === '[object Object]' ? '' : text;
}
+const DEVICE_LINK_ENVELOPE_KINDS: ReadonlySet<string> = new Set([
+ 'hello',
+ 'hello-ack',
+ 'presence-set',
+ 'presence-changed',
+ 'ping',
+ 'pong',
+ 'notify',
+ 'link-open',
+ 'link-accept',
+ 'link-close',
+ 'invoke',
+ 'invoke-result',
+ 'push',
+ 'relay-error',
+]);
+
+function isKnownInboundEnvelope(value: unknown): value is Envelope {
+ if (!isRecord(value) || value.v !== PROTOCOL_VERSION || typeof value.kind !== 'string') {
+ return false;
+ }
+ return DEVICE_LINK_ENVELOPE_KINDS.has(value.kind);
+}
+
+/**
+ * 入站帧的轻量 heartbeat 活性校验。它不复制完整隧道协议 validator,只拦截会让
+ * heartbeat 误判为“仍有流量”的明显坏帧;业务分发仍由各自 handler 负责。
+ */
+function isValidInboundEnvelope(value: Envelope): boolean {
+ const payload = value.payload;
+ // 可靠传输帧把原业务 payload 包在 transport marker/data 中;该形状由
+ // parseTransportPayload 负责完整校验,不能再按 legacy channel/payload 解释。
+ if (isReliableKind(value.kind)) {
+ const parsed = parseTransportPayload(payload);
+ if (parsed !== null) {
+ if (value.kind !== 'invoke') return true;
+ // reliable invoke 仍要有 relay 注入的源设备和请求 id;缺任一项时
+ // ingestTransportEnvelope / Desktop dispatch 都无法把它当作可处理请求。
+ // 这类帧不能仅凭内层 channel/args 把坏连接喂活。
+ if (
+ typeof value.src !== 'string'
+ || value.src.length === 0
+ || typeof value.id !== 'string'
+ || value.id.length === 0
+ ) return false;
+ // 分片的 data 只是完整 JSON 文本的一段,不能在此处单独解析;transport
+ // 元数据已经证明 relay/socket 正在工作,重组后的完整 payload 再由接收
+ // 状态机做 JSON 与业务分发校验。
+ if (parsed.meta.segment) return true;
+ try {
+ const inner = decodeTransportJson(parsed.data);
+ return isRecord(inner)
+ && typeof inner.channel === 'string'
+ && Array.isArray(inner.args);
+ } catch {
+ return false;
+ }
+ }
+ }
+ // `isReliableKind` above narrows the union on its non-transport fallback path;
+ // switch on the wire string here so legacy invoke/push/result payloads remain
+ // eligible for their existing business-layer validation.
+ switch (value.kind as string) {
+ case 'ping':
+ case 'pong':
+ return payload === undefined || payload === null;
+ case 'hello-ack':
+ return isRecord(payload)
+ && typeof payload.serverProtocolVersion === 'number'
+ && Number.isFinite(payload.serverProtocolVersion)
+ && typeof payload.deviceId === 'string'
+ && payload.deviceId.length > 0
+ && typeof payload.userId === 'string'
+ && payload.userId.length > 0;
+ case 'presence-changed':
+ return isRecord(payload)
+ && typeof payload.deviceId === 'string'
+ && payload.deviceId.length > 0
+ && typeof payload.online === 'boolean';
+ case 'relay-error':
+ return isRecord(payload)
+ && typeof payload.code === 'string'
+ && typeof payload.message === 'string';
+ case 'invoke':
+ // Desktop dispatch requires relay-injected src + request id before it can
+ // deliver an invoke. A legacy-looking frame without either identifier is
+ // therefore not usable inbound activity and must not keep a dead socket online.
+ return typeof value.src === 'string'
+ && value.src.length > 0
+ && typeof value.id === 'string'
+ && value.id.length > 0
+ && isRecord(payload)
+ && typeof payload.channel === 'string'
+ && Array.isArray(payload.args);
+ case 'invoke-result':
+ if (!isRecord(payload) || typeof payload.ok !== 'boolean') return false;
+ if (payload.ok) return true;
+ return isRecord(payload.error)
+ && typeof payload.error.code === 'string'
+ && typeof payload.error.message === 'string';
+ case 'push':
+ return isRecord(payload)
+ && typeof payload.channel === 'string'
+ && Object.prototype.hasOwnProperty.call(payload, 'payload');
+ case 'link-open':
+ return isRecord(payload)
+ && typeof payload.controllerName === 'string'
+ && typeof payload.protocolVersion === 'number'
+ && Number.isFinite(payload.protocolVersion)
+ && typeof payload.appVersion === 'string';
+ case 'link-accept':
+ return isRecord(payload)
+ && typeof payload.appVersion === 'string'
+ && typeof payload.allowlistHash === 'string';
+ case 'link-close':
+ return isRecord(payload) && typeof payload.reason === 'string';
+ case 'presence-set':
+ return isRecord(payload)
+ && (payload.remoteControlEnabled === undefined
+ || typeof payload.remoteControlEnabled === 'boolean')
+ && (payload.busy === undefined || typeof payload.busy === 'boolean');
+ case 'notify':
+ return isRecord(payload)
+ && typeof payload.category === 'string'
+ && typeof payload.title === 'string'
+ && typeof payload.deepLink === 'string'
+ && typeof payload.collapseId === 'string';
+ case 'hello':
+ return isRecord(payload);
+ default:
+ return false;
+ }
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}