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): 清理离线控制端的陈旧状态 (#3309)

Dash388414eb1dd4
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
index fe859873ce..2ec4983472 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
@@ -11,7 +11,14 @@
* mock 面与 dispatchSendSafety.test.ts 一致:只 mock electron + settings。
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { DeviceLinkError, INVOKE_TIMEOUT_OVERRIDES_MS } from '@cindy/device-link';
+import {
+ DeviceLinkClient,
+ DeviceLinkError,
+ DL_SUBSCRIBE_CHANNEL,
+ INVOKE_TIMEOUT_OVERRIDES_MS,
+ PROTOCOL_VERSION,
+ type Envelope,
+} from '@cindy/device-link';
vi.mock('electron', () => ({
app: {
@@ -35,19 +42,26 @@ vi.mock('../settings-store', () => ({
import {
__testing,
+ deactivateAllControllers,
+ deactivateController,
flushRemoteInvokeResultOutboxOnReconnect,
handleControllerOffline,
+ setControllersChangedListener,
setDispatchPresenceOfflineCheck,
+ wireInboundDispatch,
} from '../dispatch';
+import * as subscriptions from '../subscriptions';
function mkClient(
over: Partial<{
+ getConnectionEpoch: ReturnType<typeof vi.fn>;
getStatus: ReturnType<typeof vi.fn>;
sendInvokeResult: ReturnType<typeof vi.fn>;
sendLinkAccept: ReturnType<typeof vi.fn>;
}> = {},
) {
return {
+ getConnectionEpoch: over.getConnectionEpoch ?? vi.fn(() => 1),
getStatus: over.getStatus ?? vi.fn(() => 'online'),
sendInvokeResult: over.sendInvokeResult ?? vi.fn(),
sendLinkAccept: over.sendLinkAccept ?? vi.fn(),
@@ -60,6 +74,142 @@ function mkClient(
const backpressure = () => new DeviceLinkError('BACKPRESSURE', 'websocket send buffer is full');
const notConnected = () => new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');
+type LinkedWsHandler = (...args: never[]) => void;
+
+/** 只保留这轮回归需要的最小内存 relay:真实 DeviceLinkClient 互相建链,可按目的地注入离线。 */
+class DispatchTestWs {
+ readonly sent: Envelope[] = [];
+ readonly bufferedAmount = 0;
+ private readonly handlers = new Map<string, LinkedWsHandler[]>();
+
+ constructor(
+ private readonly relay: DispatchTestRelay,
+ readonly ownerId: string,
+ ) {}
+
+ send(data: string): void {
+ const envelope = JSON.parse(data) as Envelope;
+ this.sent.push(envelope);
+ this.relay.route(this.ownerId, this, envelope);
+ }
+
+ close(code = 1000, reason = ''): void {
+ this.emit('close', code, reason);
+ }
+
+ terminate(): void {
+ this.emit('close', 1006, 'terminated');
+ }
+
+ on(event: string, cb: LinkedWsHandler): void {
+ const handlers = this.handlers.get(event) ?? [];
+ handlers.push(cb);
+ this.handlers.set(event, handlers);
+ }
+
+ push(envelope: Envelope): void {
+ this.emit('message', { toString: () => JSON.stringify(envelope) });
+ }
+
+ open(): void {
+ this.emit('open');
+ }
+
+ private emit(event: string, ...args: unknown[]): void {
+ for (const cb of this.handlers.get(event) ?? []) cb(...(args as never[]));
+ }
+}
+
+class DispatchTestRelay {
+ private readonly sockets = new Map<string, DispatchTestWs>();
+ private holdPredicate: ((senderId: string, envelope: Envelope) => boolean) | null = null;
+ private readonly held: Array<{ senderId: string; envelope: Envelope }> = [];
+ readonly offline = new Set<string>();
+
+ makeWebSocket(deviceId: string): DispatchTestWs {
+ const socket = new DispatchTestWs(this, deviceId);
+ this.sockets.set(deviceId, socket);
+ setTimeout(() => socket.open(), 0);
+ return socket;
+ }
+
+ holdNext(predicate: (senderId: string, envelope: Envelope) => boolean): void {
+ this.holdPredicate = predicate;
+ }
+
+ heldCount(): number {
+ return this.held.length;
+ }
+
+ releaseHeld(): void {
+ const held = this.held.splice(0);
+ this.holdPredicate = null;
+ for (const item of held) this.deliver(item.senderId, item.envelope);
+ }
+
+ route(senderId: string, socket: DispatchTestWs, envelope: Envelope): void {
+ if (envelope.kind === 'hello') {
+ socket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'hello-ack',
+ payload: {
+ serverProtocolVersion: PROTOCOL_VERSION,
+ deviceId: senderId,
+ userId: 'test-user',
+ },
+ });
+ return;
+ }
+ if (!envelope.dst) return;
+ if (this.offline.has(envelope.dst)) {
+ socket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'target device offline',
+ dst: envelope.dst,
+ },
+ });
+ return;
+ }
+ if (this.holdPredicate?.(senderId, envelope)) {
+ this.held.push({ senderId, envelope });
+ this.holdPredicate = null;
+ return;
+ }
+ this.deliver(senderId, envelope);
+ }
+
+ private deliver(senderId: string, envelope: Envelope): void {
+ const destination = envelope.dst ? this.sockets.get(envelope.dst) : undefined;
+ if (!destination) return;
+ destination.push({ ...envelope, src: senderId });
+ }
+}
+
+function makeDispatchTestClient(relay: DispatchTestRelay, deviceId: string): DeviceLinkClient {
+ return new DeviceLinkClient({
+ getWsUrl: () => 'ws://test/api/device-link/ws',
+ getToken: async () => 'jwt-token',
+ getHello: () => ({
+ deviceName: deviceId,
+ platform: 'darwin',
+ appVersion: '1.0.0',
+ remoteControlEnabled: true,
+ busy: false,
+ }),
+ createWebSocket: () => relay.makeWebSocket(deviceId) as never,
+ timing: {
+ reconnectBaseMs: 5,
+ reconnectMaxMs: 20,
+ pingIntervalMs: 60_000,
+ pongMissLimit: 4,
+ requestTimeoutMs: 2_000,
+ },
+ });
+}
+
beforeEach(() => {
vi.useFakeTimers();
deviceLinkSettings.value = {
@@ -472,3 +622,121 @@ describe('[5] orphan 截止时间按 channel 收窄', () => {
);
});
});
+
+describe('[6] active controller 生命周期与故障半径', () => {
+ it('真实双 peer 链路中 A 的 DEVICE_OFFLINE 不清 B,B 的在途请求仍能完成', async () => {
+ vi.useRealTimers();
+ const relay = new DispatchTestRelay();
+ const target = makeDispatchTestClient(relay, 'target');
+ const controllerA = makeDispatchTestClient(relay, 'ctrl-a');
+ const controllerB = makeDispatchTestClient(relay, 'ctrl-b');
+
+ wireInboundDispatch(target);
+ __testing.setActiveClient(target);
+ const routeChanges: string[] = [];
+ target.onPeerRouteStateChanged((change) => {
+ routeChanges.push(`${change.deviceId}:${change.state}`);
+ if (change.state === 'offline') handleControllerOffline(change.deviceId, change);
+ });
+ target.start();
+ controllerA.start();
+ controllerB.start();
+ await vi.waitFor(() => {
+ expect(target.getStatus()).toBe('online');
+ expect(controllerA.getStatus()).toBe('online');
+ expect(controllerB.getStatus()).toBe('online');
+ });
+
+ const openPayload = {
+ controllerName: 'controller',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ };
+ await Promise.all([
+ controllerA.openLink('target', openPayload),
+ controllerB.openLink('target', openPayload),
+ ]);
+ await expect(controllerA.invoke('target', {
+ channel: DL_SUBSCRIBE_CHANNEL,
+ args: [{ topics: ['session:a'], controllerName: 'A', capabilities: ['cap-a'] }],
+ })).resolves.toMatchObject({ ok: true });
+
+ relay.holdNext((senderId, envelope) => (
+ senderId === 'target' && envelope.dst === 'ctrl-b' && envelope.kind === 'invoke-result'
+ ));
+ const pendingFromB = controllerB.invoke('target', {
+ channel: DL_SUBSCRIBE_CHANNEL,
+ args: [{ topics: ['session:b'], controllerName: 'B', capabilities: ['cap-b'] }],
+ });
+ await vi.waitFor(() => expect(relay.heldCount()).toBe(1));
+
+ // 模拟 relay 对 target→A 的真实路由错误:DeviceLinkClient 先发 typed offline,
+ // 再由 host 接入唯一的 deactivateController 状态转换。
+ relay.offline.add('ctrl-a');
+ target.sendInvokeResult('ctrl-a', 'offline-probe', { ok: true, result: null });
+
+ expect(routeChanges).toContain('ctrl-a:offline');
+ expect(__testing.getActiveControllers().map((controller) => controller.deviceId).sort()).toEqual([
+ 'ctrl-b',
+ ]);
+ expect(subscriptions.getKnownControllersForTopic('session:a')).toEqual(['ctrl-a']);
+ expect(subscriptions.getKnownControllersForTopic('session:b')).toEqual(['ctrl-b']);
+ expect(__testing.controllerSupports('ctrl-a', 'cap-a')).toBe(true);
+
+ relay.releaseHeld();
+ await expect(pendingFromB).resolves.toMatchObject({ ok: true });
+ // B 的 invoke 在 A 失活期间仍完成,证明同一 relay 上的 B 控制方向未被拆掉。
+
+ target.stop();
+ controllerA.stop();
+ controllerB.stop();
+ });
+
+ it('relay 断开清空所有 active projection,但保留 remembered topics/capabilities', () => {
+ subscriptions.subscribe('ctrl-a', ['session:a'], 'A', ['cap-a']);
+ subscriptions.subscribe('ctrl-b', ['fs-watch:/repo'], 'B', ['cap-b']);
+ const changes: Array<{ active: string[]; updateRelaunch: string[] }> = [];
+ setControllersChangedListener((active, updateRelaunch) => {
+ changes.push({
+ active: active.map((controller) => controller.deviceId),
+ updateRelaunch: updateRelaunch.map((controller) => controller.deviceId),
+ });
+ });
+
+ deactivateAllControllers('relay-disconnected');
+
+ expect(__testing.getActiveControllers()).toEqual([]);
+ expect(__testing.getUpdateRelaunchControllers()).toEqual([]);
+ expect(subscriptions.getKnownControllersForTopic('session:a')).toEqual(['ctrl-a']);
+ expect(subscriptions.getKnownControllersForTopic('fs-watch:/repo')).toEqual(['ctrl-b']);
+ expect(__testing.controllerSupports('ctrl-a', 'cap-a')).toBe(true);
+ expect(__testing.controllerSupports('ctrl-b', 'cap-b')).toBe(true);
+ expect(changes.at(-1)).toEqual({ active: [], updateRelaunch: [] });
+ });
+
+ it('旧 connection epoch 的 offline 事件不能清掉新 link-open 的 active controller', () => {
+ let connectionEpoch = 1;
+ const client = mkClient({ getConnectionEpoch: vi.fn(() => connectionEpoch) });
+ __testing.setActiveClient(client as never);
+
+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-old', undefined);
+ connectionEpoch = 2;
+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-new', undefined);
+
+ handleControllerOffline('ctrl-a', {
+ deviceId: 'ctrl-a',
+ state: 'offline',
+ connectionEpoch: 1,
+ });
+ expect(__testing.getActiveControllers().map((controller) => controller.deviceId)).toEqual([
+ 'ctrl-a',
+ ]);
+
+ handleControllerOffline('ctrl-a', {
+ deviceId: 'ctrl-a',
+ state: 'offline',
+ connectionEpoch: 2,
+ });
+ expect(__testing.getActiveControllers()).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 667de15226..91a51229d0 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -44,6 +44,7 @@ import {
DeviceLinkError,
parseFsWatchTopic,
type Envelope,
+ type DeviceLinkPeerRouteStateChanged,
type InvokePayload,
type InvokeResultPayload,
type LinkClosePayload,
@@ -558,6 +559,11 @@ const remoteInvokeLinkEpoch = new Map<string, number>();
const topicSubscriptionControllers = new Set<string>();
/** 已成功 accept、尚未显式 close 的控制端;可无 active topic(现代重连等待 subscribe)。 */
const acceptedLinkControllers = new Set<string>();
+/**
+ * 当前 active controller 所属的 relay connection generation。
+ * DEVICE_OFFLINE 事件带 generation,旧 socket 的迟到事实不能清掉新链路。
+ */
+const controllerConnectionEpochByDevice = new Map<string, number>();
/**
* relay presence 按 server 盖章的 deviceId 提供设备数据库展示名。它比控制端在
* link-open / subscribe 里自报的主机名更权威,用于让被控提示与设备列表一致。
@@ -605,6 +611,18 @@ function clearReportedControllerName(deviceId: string): void {
reportedControllerNameByDevice.delete(deviceId);
}
+function readConnectionEpoch(client: DeviceLinkClient): number | undefined {
+ const candidate = client as DeviceLinkClient & {
+ getConnectionEpoch?: () => number;
+ };
+ return candidate.getConnectionEpoch?.();
+}
+
+function markControllerLinkActive(client: DeviceLinkClient, deviceId: string): void {
+ const epoch = readConnectionEpoch(client);
+ if (epoch !== undefined) controllerConnectionEpochByDevice.set(deviceId, epoch);
+}
+
/**
* presence 设备名变化(含设置页重命名)时更新展示真相;已有活跃订阅立即重发
* controlled-state,让横幅不用等下一次 subscribe / 重连才改名。
@@ -1521,6 +1539,7 @@ export function dropAllControllers(
subscriptions.clearAll();
topicSubscriptionControllers.clear();
acceptedLinkControllers.clear();
+ controllerConnectionEpochByDevice.clear();
reportedControllerNameByDevice.clear();
offlinePushQueue.clear();
clearAllSessionActivityStages();
@@ -1529,21 +1548,82 @@ export function dropAllControllers(
syncForwarding();
}
-/**
- * host 收到对等控制端 presence-changed(online:false)→ 清其全部订阅。
- * server 把 presence-changed 广播给同账号所有连接(含本机),这是控制端崩溃 / 拔网
- * 后回收僵尸订阅的兜底信号(正常路径是控制端显式 unsubscribe / link-close)。
- * 不清 invoke result/outbox:presence offline 可能只是弱网重连,控制端可靠请求仍在等回包。
- */
-export function handleControllerOffline(deviceId: string): void {
- acceptedLinkControllers.delete(deviceId);
+function deactivateControllerState(
+ deviceId: string,
+ observedConnectionEpoch?: number,
+): boolean {
+ const activeEpoch = controllerConnectionEpochByDevice.get(deviceId);
+ if (
+ observedConnectionEpoch !== undefined
+ && activeEpoch !== undefined
+ && observedConnectionEpoch < activeEpoch
+ ) {
+ log.debug(
+ `ignoring stale controller offline event for ${shortId(deviceId)} (event=${observedConnectionEpoch}, active=${activeEpoch})`,
+ );
+ return false;
+ }
+ let changed = false;
+ changed = acceptedLinkControllers.delete(deviceId) || changed;
+ changed = controllerConnectionEpochByDevice.delete(deviceId) || changed;
+ changed = reportedControllerNameByDevice.has(deviceId) || changed;
+ changed = subscriptions.getControllerIds().includes(deviceId) || changed;
clearReportedControllerName(deviceId);
clearSessionActivityStage(deviceId);
clearMakerEventBatchStage(deviceId);
cancelLinkAcceptRetry(deviceId);
- if (subscriptions.clearController(deviceId)) {
+ return subscriptions.clearController(deviceId) || changed;
+}
+
+/**
+ * Active → inactive 的唯一单 peer 状态转换。
+ *
+ * 清 accepted link、active topics、横幅/更新重启 busy 与短期发送 stage;保留
+ * remembered topics/capabilities、可靠 pending、invoke-result outbox 和离线队列,
+ * 让控制端回来后按既有 link-open + subscribe 路径恢复。
+ */
+export function deactivateController(
+ deviceId: string,
+ reason: string,
+ observedConnectionEpoch?: number,
+): boolean {
+ const changed = deactivateControllerState(deviceId, observedConnectionEpoch);
+ if (changed) {
+ log.info(`controller ${shortId(deviceId)} deactivated (${reason})`);
syncForwarding();
}
+ return changed;
+}
+
+/** Relay 连接离开 online:清本连接代所有 active controller,但保留恢复意图。 */
+export function deactivateAllControllers(reason: string): void {
+ const controllerIds = new Set([
+ ...subscriptions.getControllerIds(),
+ ...topicSubscriptionControllers,
+ ...acceptedLinkControllers,
+ ...controllerConnectionEpochByDevice.keys(),
+ ...reportedControllerNameByDevice.keys(),
+ ]);
+ let changed = false;
+ for (const deviceId of controllerIds) {
+ changed = deactivateControllerState(deviceId) || changed;
+ }
+ if (changed) {
+ log.info(`all active controllers deactivated (${reason}, count=${controllerIds.size})`);
+ syncForwarding();
+ }
+}
+
+/** presence offline remains an authoritative single-peer deactivation edge. */
+export function handleControllerOffline(
+ deviceId: string,
+ routeChange?: DeviceLinkPeerRouteStateChanged,
+): void {
+ deactivateController(
+ deviceId,
+ routeChange ? 'relay-device-offline' : 'presence-offline',
+ routeChange?.connectionEpoch,
+ );
}
/** 显式解链/撤权才丢弃该控制端的去重缓存与待发送结果。 */
@@ -1553,15 +1633,15 @@ export function forgetControllerInvokeState(deviceId: string): void {
/** 显式撤销时清理短时离线队列与 remembered topic,避免恢复后重放撤权期间数据。 */
export function purgeRevokedController(deviceId: string): void {
- clearReportedControllerName(deviceId);
+ const changed = deactivateControllerState(deviceId);
+ topicSubscriptionControllers.delete(deviceId);
offlinePushQueue.clear(deviceId);
- clearSessionActivityStage(deviceId);
- clearMakerEventBatchStage(deviceId);
- cancelLinkAcceptRetry(deviceId);
+ const wasKnown = subscriptions.getKnownControllerIds().includes(deviceId);
subscriptions.forgetKnownController(deviceId);
- topicSubscriptionControllers.delete(deviceId);
- acceptedLinkControllers.delete(deviceId);
- syncForwarding();
+ if (changed || wasKnown) {
+ log.info(`controller ${shortId(deviceId)} deactivated (revoked)`);
+ syncForwarding();
+ }
}
/**
@@ -1602,17 +1682,13 @@ async function handleFrame(client: DeviceLinkClient, env: Envelope): Promise<voi
}
clearRemoteInvokeStateFor(src);
offlinePushQueue.clear(src);
- clearSessionActivityStage(src);
- clearMakerEventBatchStage(src);
- cancelLinkAcceptRetry(src);
- acceptedLinkControllers.delete(src);
- clearReportedControllerName(src);
+ const deactivated = deactivateControllerState(src);
// Keep the protocol-capability marker, but discard all remembered routing.
// A modern controller must reconnect and explicitly subscribe; restoring the
// legacy wildcard here would silently re-enable broad delivery.
- subscriptions.clearController(src);
+ const wasKnown = subscriptions.getKnownControllerIds().includes(src);
subscriptions.forgetKnownController(src);
- syncForwarding();
+ if (deactivated || wasKnown) syncForwarding();
log.info(`control link closed by ${shortId(src)}`);
return;
case 'invoke':
@@ -1737,6 +1813,7 @@ function handleLinkOpen(
scheduleLinkAcceptRetry(client, src, requestId, payload, acceptAttempt + 1);
return;
}
+ markControllerLinkActive(client, src);
acceptedLinkControllers.add(src);
if (knownModernController) {
subscriptions.updateControllerMetadata(src, name, capabilities);
@@ -2985,6 +3062,7 @@ export const __testing = {
remoteInvokeLinkEpoch.clear();
topicSubscriptionControllers.clear();
acceptedLinkControllers.clear();
+ controllerConnectionEpochByDevice.clear();
controllerDisplayNameByDevice.clear();
reportedControllerNameByDevice.clear();
onSessionsSubscribed = null;
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 8939488f8a..34db6b86f1 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -73,6 +73,7 @@ import {
setControllersChangedListener,
setRemoteInvokeBusyChangedListener,
dropAllControllers,
+ deactivateAllControllers,
flushMakerEventBatchesOnReconnect,
flushRemoteInvokeResultOutboxOnReconnect,
forgetControllerInvokeState,
@@ -705,8 +706,18 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
}, RESPONSIVENESS_PROBE_TICK_MS);
responsivenessProbeTimer.unref();
+ client.onPeerRouteStateChanged((change) => {
+ if (change.state === 'offline') {
+ handleControllerOffline(change.deviceId, change);
+ }
+ });
+
client.onStatusChange((status) => {
if (status !== 'online') {
+ // The shared relay connection is a larger fault domain than one peer:
+ // release every active controller projection, but keep remembered topics
+ // so reconnect recovery can still replay them explicitly.
+ deactivateAllControllers('relay-disconnected');
controllerDisplayNameRefreshGeneration += 1;
// 不清 openLinkInFlight:登记生命周期的唯一判据是 promise settle(每个
// 请求 settle 时自清理,closeRemoteLink 的显式删除有取消代次兜底)。建链
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 2add2c80f6..44eeb61651 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -3003,6 +3003,8 @@ describe('DeviceLinkClient', () => {
it('同 id relay-error → 带 code reject', async () => {
const h = makeHarness();
+ const routeChanges: unknown[] = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
h.client.start();
await tick();
h.current().ack();
@@ -3016,6 +3018,56 @@ describe('DeviceLinkClient', () => {
payload: { code: 'REMOTE_DISABLED', message: 'off' },
});
await expect(p).rejects.toMatchObject({ code: 'REMOTE_DISABLED' });
+ expect(routeChanges).toHaveLength(0);
+ h.client.stop();
+ });
+
+ it('pending DEVICE_OFFLINE 在 reject 前发出 peer route offline 事件', async () => {
+ const h = makeHarness();
+ const routeChanges: unknown[] = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ const invoke = h.client.invoke('dev-b', { channel: 'x', args: [] });
+ const sent = h.current().sent.find((e) => e.kind === 'invoke')!;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: sent.id,
+ payload: { code: 'DEVICE_OFFLINE', message: 'offline' },
+ });
+
+ expect(routeChanges).toHaveLength(1);
+ expect(routeChanges[0]).toMatchObject({
+ deviceId: 'dev-b',
+ state: 'offline',
+ connectionEpoch: expect.any(Number),
+ });
+ await expect(invoke).rejects.toMatchObject({ code: 'DEVICE_OFFLINE' });
+ h.client.stop();
+ });
+
+ it('无 pending 的 DEVICE_OFFLINE 也发出单次 peer route offline 事件', async () => {
+ const h = makeHarness();
+ const routeChanges: unknown[] = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ h.client.sendPush('dev-b', 'maker:event', { stale: true });
+ const error = {
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ payload: { code: 'DEVICE_OFFLINE', message: 'offline', dst: 'dev-b' },
+ } as const;
+ h.current().push(error);
+ h.current().push(error);
+
+ expect(routeChanges).toHaveLength(1);
+ expect(routeChanges[0]).toMatchObject({ deviceId: 'dev-b', state: 'offline' });
h.client.stop();
});
@@ -3702,6 +3754,8 @@ describe('DeviceLinkClient', () => {
it('epoch 守卫:过期 socket 的迟到 close/message 回调被忽略,不触发额外重连', async () => {
const h = makeHarness();
+ const routeChanges: unknown[] = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
h.client.start();
await tick();
h.current().ack();
@@ -3716,8 +3770,16 @@ describe('DeviceLinkClient', () => {
// 把 this.ws=socket2 误清并再排一次重连 → socket3)。
stale.emit('close', 1006);
stale.emit('message', { toString: () => 'garbage-from-stale' });
+ stale.emit('message', {
+ toString: () => JSON.stringify({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ payload: { code: 'DEVICE_OFFLINE', message: 'stale', dst: 'dev-b' },
+ }),
+ });
await tick(25);
expect(h.sockets.length).toBe(2); // 没有因 stale 迟到事件多建连
+ expect(routeChanges).toHaveLength(0); // 旧 connection epoch 不能清新链路
fresh.ack();
expect(h.client.getStatus()).toBe('online'); // fresh 不受 stale 影响,正常 online
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 977b567f96..79f425f682 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -372,6 +372,20 @@ export interface DeviceLinkConnectionIssue {
at: number;
}
+/**
+ * Peer route lifecycle signal for host-side active-state cleanup.
+ *
+ * `DEVICE_OFFLINE` is a routing fact, not a request-level error only: the host
+ * must release the peer's active controller projection while retaining its
+ * remembered recovery intent. The connection epoch lets hosts ignore a late
+ * signal from an older WebSocket generation.
+ */
+export interface DeviceLinkPeerRouteStateChanged {
+ deviceId: string;
+ state: 'offline';
+ connectionEpoch: number;
+}
+
/**
* 从断连信息分类连接问题。返回 null = 普通断线(网络抖动 / 服务重启 / 4401 token
* 轮换),按既有退避重连兜底即可,不打扰用户。
@@ -614,6 +628,11 @@ export class DeviceLinkClient {
private presenceHandlers = new Set<(snap: PresenceSnapshot) => void>();
private frameHandlers = new Set<InboundFrameHandler>();
private issueHandlers = new Set<(issue: DeviceLinkConnectionIssue | null) => void>();
+ private peerRouteStateHandlers = new Set<
+ (change: DeviceLinkPeerRouteStateChanged) => void
+ >();
+ /** Avoid emitting the same authoritative route failure once per queued frame. */
+ private peerOfflineNotifiedEpoch = new Map<string, number>();
constructor(opts: DeviceLinkClientOptions) {
this.opts = opts;
@@ -833,6 +852,19 @@ export class DeviceLinkClient {
return () => this.statusHandlers.delete(cb);
}
+ /** Current WebSocket connection generation; useful for host-side stale-event guards. */
+ getConnectionEpoch(): number {
+ return this.connEpoch;
+ }
+
+ /** Subscribe to typed peer route lifecycle changes (currently authoritative offline). */
+ onPeerRouteStateChanged(
+ cb: (change: DeviceLinkPeerRouteStateChanged) => void,
+ ): () => void {
+ this.peerRouteStateHandlers.add(cb);
+ return () => this.peerRouteStateHandlers.delete(cb);
+ }
+
getConnectionIssue(): DeviceLinkConnectionIssue | null {
return this.connectionIssue;
}
@@ -848,6 +880,28 @@ export class DeviceLinkClient {
return () => this.presenceHandlers.delete(cb);
}
+ private notifyPeerRouteOffline(deviceId: string): void {
+ if (this.peerOfflineNotifiedEpoch.get(deviceId) === this.connEpoch) return;
+ this.peerOfflineNotifiedEpoch.set(deviceId, this.connEpoch);
+ if (this.peerRouteStateHandlers.size === 0) return;
+ const change: DeviceLinkPeerRouteStateChanged = {
+ deviceId,
+ state: 'offline',
+ connectionEpoch: this.connEpoch,
+ };
+ for (const cb of this.peerRouteStateHandlers) {
+ try {
+ cb(change);
+ } catch (err) {
+ this.log.error('device-link peer route state handler failed', err);
+ }
+ }
+ }
+
+ private markPeerRouteOnline(deviceId: string): void {
+ this.peerOfflineNotifiedEpoch.delete(deviceId);
+ }
+
/** 订阅入站隧道帧(invoke / link-open / link-close / push / 未配对的响应帧) */
onFrame(cb: InboundFrameHandler): () => void {
this.frameHandlers.add(cb);
@@ -1091,6 +1145,7 @@ export class DeviceLinkClient {
: {}),
},
});
+ this.markPeerRouteOnline(dst);
if (matchingOffer) {
this.pendingInboundLinkOffers.delete(dst);
this.setPeerCapabilities(
@@ -1847,6 +1902,7 @@ export class DeviceLinkClient {
'outbound-accept',
);
const peer = this.getPeerTransport(env.src);
+ this.markPeerRouteOnline(env.src);
peer.outboundExplicitlyClosed = false;
// 注意:不得在此将 linkAcceptedInbound 改回 false。互控场景下本机可能
// 既是对端的被控端(入站已 accept)又是其控制端(本帧 accept 出站
@@ -1877,8 +1933,16 @@ export class DeviceLinkClient {
payload.code === 'DEVICE_OFFLINE'
|| payload.code === 'REMOTE_DISABLED'
);
- if (env.id && this.pending.has(env.id)) {
- const p = this.pending.get(env.id)!;
+ const pending = env.id ? this.pending.get(env.id) : undefined;
+ const routeDeviceId = payload.dst ?? pending?.dst;
+ // DEVICE_OFFLINE is a peer route transition, not merely a rejected
+ // request. Emit it before the pending fast path so the host cannot
+ // miss it when the relay error is paired with an in-flight request.
+ if (payload.code === 'DEVICE_OFFLINE' && routeDeviceId) {
+ this.notifyPeerRouteOffline(routeDeviceId);
+ }
+ if (env.id && pending) {
+ const p = pending;
this.pending.delete(env.id);
// relay-error 代表原 invoke 没有交付到 peer。若它占用了可靠 stream 的 seq,
// 不能只 reject 上层后把原请求留到重连重放,否则一个已向用户报错的写操作