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): 修复设备状态未知时订阅恢复停止 (#3941)

Dash22b3c4073731
diff --git a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
index c567ec8331..4398273804 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
@@ -44,11 +44,18 @@ describe('mobile voice credential sync desktop bootstrap path', () => {
expect(deviceLinkHost).toContain('const available = snap.online && snap.remoteControlEnabled;');
// `!== true` 而非 `=== false`:断线时 availability 视图整体清空,重连后首帧
- // presence(wasAvailable=undefined)同样必须触发重放——它是 DEVICE_OFFLINE
- // 永久放弃后的唯一恢复事件(#1520 review P1)。
+ // presence(wasAvailable=undefined)同样必须触发重放,接续 DEVICE_OFFLINE
+ // 结束的恢复轮次(#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({');
+ // Preserve unknown after reconnect; only explicit unavailability stops retries.
+ expect(deviceLinkHost).toContain(
+ 'getPresenceAvailability: (deviceId) => presenceAvailableByDevice.get(deviceId)',
+ );
+ expect(deviceLinkHost).toContain('?? (presenceOnlineByDevice.get(deviceId) === false ? false : undefined)');
+ expect(deviceLinkHost).toContain("replayActiveSubscriptions('directory-online', deviceId);");
+ expect(deviceLinkHost).toContain('isPermanentSubscriptionReplayError(error, presenceAvailableByDevice.get(deviceId))');
});
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
index 8d58c8bdd8..6e82431477 100644
--- a/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts
@@ -1,6 +1,8 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { createSubscriptionReplayScheduler } from '../subscriptionReplayScheduler';
+import { DeviceLinkError } from '@cindy/device-link';
+
+import { createSubscriptionReplayScheduler, isPermanentSubscriptionReplayError } from '../subscriptionReplayScheduler';
function deferred<T>() {
let resolve!: (value: T) => void;
@@ -13,6 +15,176 @@ function deferred<T>() {
}
describe('subscription replay scheduler', () => {
+ describe('recovery before presence arrives', () => {
+ const deviceId = 'device-a';
+ let presence: Map<string, boolean>;
+ let directoryOnline: Map<string, boolean>;
+ let relayOnline: boolean;
+ let unresponsive: boolean;
+ let tornDown: boolean;
+ let refs: Array<{ deviceId: string; topics: string[] }>;
+ let remoteSubscribe: ReturnType<typeof vi.fn<(id: string, topics: string[]) => Promise<unknown>>>;
+ let scheduler: ReturnType<typeof createSubscriptionReplayScheduler>;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ presence = new Map();
+ directoryOnline = new Map();
+ relayOnline = true;
+ unresponsive = false;
+ tornDown = false;
+ refs = [{ deviceId, topics: ['session:one'] }];
+ remoteSubscribe = vi.fn<(id: string, topics: string[]) => Promise<unknown>>()
+ .mockRejectedValue(new Error('temporary'));
+ scheduler = createSubscriptionReplayScheduler({
+ snapshotSubscriptions: (id) => refs.filter((ref) => !id || ref.deviceId === id),
+ remoteSubscribe,
+ isLinkTornDown: () => tornDown,
+ isRelayOnline: () => relayOnline,
+ isDeviceUnresponsive: () => unresponsive,
+ getPresenceAvailability: (id) => presence.get(id)
+ ?? (directoryOnline.get(id) === false ? false : undefined),
+ isPermanentError: (error, id) => isPermanentSubscriptionReplayError(error, presence.get(id)),
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+ });
+
+ afterEach(() => {
+ scheduler.teardown();
+ vi.useRealTimers();
+ });
+
+ it('recovers after reconnect without a presence event or replaying a healthy peer', async () => {
+ presence.set(deviceId, true);
+ presence.clear(); // The old connection verdict is invalidated on disconnect.
+ refs.push({ deviceId: 'device-b', topics: ['sessions'] });
+ const healthy = deferred<unknown>();
+ let attempts = 0;
+ remoteSubscribe.mockImplementation((id) => {
+ if (id === 'device-b') return healthy.promise;
+ return ++attempts === 1 ? Promise.reject(new Error('temporary')) : Promise.resolve();
+ });
+
+ scheduler.replay('ws-online');
+ await vi.advanceTimersByTimeAsync(2_999);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+ refs[0].topics = ['session:one', 'session:two'];
+ await vi.advanceTimersByTimeAsync(1);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(3);
+ expect(remoteSubscribe).toHaveBeenLastCalledWith(deviceId, ['session:one', 'session:two']);
+ healthy.resolve(undefined);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(remoteSubscribe.mock.calls.filter(([id]) => id === 'device-b')).toHaveLength(1);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(3);
+ });
+
+ it('keeps exponential backoff capped at 30 seconds while presence stays unknown', async () => {
+ scheduler.replay('ws-online');
+ let attempts = 1;
+ for (const delay of [3_000, 6_000, 12_000, 24_000, 30_000, 30_000]) {
+ await vi.advanceTimersByTimeAsync(delay - 1);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(attempts);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(++attempts);
+ }
+ });
+
+ it('stops on explicit unavailability and resumes on the next online trigger', async () => {
+ scheduler.replay('ws-online');
+ await vi.advanceTimersByTimeAsync(0);
+ presence.set(deviceId, false);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(1);
+
+ presence.set(deviceId, true);
+ remoteSubscribe.mockResolvedValue(undefined);
+ scheduler.replay('presence-online', deviceId);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+ });
+
+ it.each(['relay-offline', 'torn-down', 'unresponsive', 'unsubscribed', 'cancel', 'teardown'])(
+ 'does not retry unknown presence after %s', async (gate) => {
+ scheduler.replay('ws-online');
+ await vi.advanceTimersByTimeAsync(0);
+ if (gate === 'relay-offline') relayOnline = false;
+ if (gate === 'torn-down') tornDown = true;
+ if (gate === 'unresponsive') unresponsive = true;
+ if (gate === 'unsubscribed') refs = [];
+ if (gate === 'cancel') scheduler.cancel(deviceId);
+ if (gate === 'teardown') scheduler.teardown();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('stops when an unknown peer retry receives a permanent rejection', async () => {
+ remoteSubscribe.mockRejectedValueOnce(new Error('temporary'))
+ .mockRejectedValue(new Error('[ACCESS_REVOKED] denied'));
+ scheduler.replay('ws-online');
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([
+ new Error('[DEVICE_OFFLINE] offline'),
+ new DeviceLinkError('DEVICE_OFFLINE', 'offline'),
+ ])('stops unknown recovery on explicit offline response %s and resumes on directory online', async (error) => {
+ remoteSubscribe.mockRejectedValue(error);
+ scheduler.replay('ws-online');
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(presence.has(deviceId)).toBe(false);
+
+ directoryOnline.set(deviceId, true);
+ remoteSubscribe.mockResolvedValue(undefined);
+ scheduler.replay('directory-online', deviceId);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+ });
+
+ it('stops on directory offline and retries again after the directory reports online', async () => {
+ scheduler.replay('ws-online');
+ await vi.advanceTimersByTimeAsync(0);
+ directoryOnline.set(deviceId, false);
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(1);
+
+ directoryOnline.set(deviceId, true);
+ scheduler.replay('directory-online', deviceId);
+ await vi.advanceTimersByTimeAsync(3_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(3);
+ expect(presence.has(deviceId)).toBe(false);
+ });
+
+ it.each(['before request', 'while request pending'])(
+ 'preserves the existing policy when presence becomes true %s', async (when) => {
+ const first = deferred<unknown>();
+ remoteSubscribe.mockReturnValueOnce(first.promise).mockResolvedValue(undefined);
+ if (when === 'before request') presence.set(deviceId, true);
+ scheduler.replay('ws-online');
+ if (when === 'while request pending') presence.set(deviceId, true);
+ first.reject(new DeviceLinkError('DEVICE_OFFLINE', 'route offline without a presence update'));
+ await vi.advanceTimersByTimeAsync(3_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+ expect(presence.get(deviceId)).toBe(true);
+ },
+ );
+
+ it('does not lose an online trigger queued before the offline response settles', async () => {
+ const first = deferred<unknown>();
+ remoteSubscribe.mockReturnValueOnce(first.promise).mockResolvedValue(undefined);
+ scheduler.replay('ws-online');
+ directoryOnline.set(deviceId, true);
+ scheduler.replay('directory-online', deviceId);
+ first.reject(new DeviceLinkError('DEVICE_OFFLINE', 'late response'));
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ });
+
it('coalesces ws/presence triggers and replays the latest snapshot after settle', async () => {
const deviceId = 'device-a';
let refs = [{ deviceId, topics: ['session:one'] }];
@@ -30,7 +202,7 @@ describe('subscription replay scheduler', () => {
isLinkTornDown: () => false,
isRelayOnline: () => true,
isDeviceUnresponsive: () => false,
- isPresenceAvailable: () => true,
+ getPresenceAvailability: () => true,
isPermanentError: () => false,
log: { debug: vi.fn(), warn: vi.fn() },
});
@@ -62,7 +234,7 @@ describe('subscription replay scheduler', () => {
isLinkTornDown: () => false,
isRelayOnline: () => true,
isDeviceUnresponsive: () => false,
- isPresenceAvailable: () => true,
+ getPresenceAvailability: () => true,
isPermanentError: () => false,
log: { debug: vi.fn(), warn: vi.fn() },
});
@@ -96,7 +268,7 @@ describe('subscription replay scheduler', () => {
isLinkTornDown: () => false,
isRelayOnline: () => true,
isDeviceUnresponsive: () => false,
- isPresenceAvailable: () => true,
+ getPresenceAvailability: () => true,
isPermanentError: () => false,
log: { debug: vi.fn(), warn: vi.fn() },
retryBaseMs: 10,
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 02f289cbf2..41197832b7 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -128,7 +128,7 @@ import {
buildSessionNotifyPayload,
type MobileSessionEventKind,
} from './mobileNotify';
-import { createSubscriptionReplayScheduler } from './subscriptionReplayScheduler';
+import { createSubscriptionReplayScheduler, isPermanentSubscriptionReplayError } from './subscriptionReplayScheduler';
import { getSessionNotificationBody } from '../sessionNotificationCopy';
import { getClientEndpoint } from '../clientEndpointsService';
import {
@@ -268,6 +268,7 @@ export function applyControllerPresenceListSnapshot(
onPeerBecameOnline: (deviceId, platform) => {
if (isMobilePlatform(platform)) handleMobilePeerOnline(deviceId);
else handleDesktopPeerOnline(deviceId);
+ replayActiveSubscriptions('directory-online', deviceId);
},
});
}
@@ -1259,41 +1260,15 @@ function replayActiveSubscriptions(reason: string, deviceId?: string): void {
subscriptionReplayScheduler.replay(reason, deviceId);
}
-/**
- * 订阅重放的永久失败判据:这些码代表「重试同一动作不可能改变结果」的终态
- * (协议不符 / 对端明确拒绝 / 授权被收回 / 本机 fail-closed 门),各自有独立的
- * 恢复事件,不归退避循环管。DeviceLinkError.code 优先,兜底解析 message 里的
- * [CODE] 编码(本机门禁抛的是普通 Error)。
- */
-const PERMANENT_SUBSCRIPTION_REPLAY_CODES: ReadonlySet<string> = new Set([
- 'VERSION_MISMATCH',
- 'REMOTE_DISABLED',
- 'ACCESS_REVOKED',
- 'CHANNEL_NOT_ALLOWED',
- 'DEVICE_LINK_CONTROL_DISABLED',
- 'DEVICE_LINK_STANDBY',
- // DEVICE_OFFLINE 刻意不在列(MOBILE-PARITY-CHECKLIST §2 归瞬态):presence
- // 滞后窗口内 subscribe 可能先吃到 DEVICE_OFFLINE,归永久会在「presence 仍
- // available」期间放弃收敛;归瞬态则退避循环续跑,presence 补到 offline 时由
- // 重试前置门(presenceAvailableByDevice !== true)自然终止,设备回归再由
- // presence 翻转重放接棒——两个终止/恢复信号都已存在,无泄漏风险(review P2)。
-]);
-
-function isPermanentSubscriptionReplayError(err: unknown): boolean {
- if (err instanceof DeviceLinkError) return PERMANENT_SUBSCRIPTION_REPLAY_CODES.has(err.code);
- const message = err instanceof Error ? err.message : String(err);
- const code = /\[([A-Z_]+)\]/.exec(message)?.[1];
- return code !== undefined && PERMANENT_SUBSCRIPTION_REPLAY_CODES.has(code);
-}
-
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,
+ getPresenceAvailability: (deviceId) => presenceAvailableByDevice.get(deviceId)
+ ?? (presenceOnlineByDevice.get(deviceId) === false ? false : undefined),
+ isPermanentError: (error, deviceId) => isPermanentSubscriptionReplayError(error, presenceAvailableByDevice.get(deviceId)),
log: {
debug: (message) => log.debug(message),
warn: (message) => log.warn(message),
diff --git a/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts b/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts
index d62b788cb1..7bd1db7dbd 100644
--- a/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts
+++ b/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts
@@ -1,3 +1,28 @@
+import { DeviceLinkError } from '@cindy/device-link';
+
+const PERMANENT_SUBSCRIPTION_REPLAY_CODES: ReadonlySet<string> = new Set([
+ 'VERSION_MISMATCH',
+ 'REMOTE_DISABLED',
+ 'ACCESS_REVOKED',
+ 'CHANNEL_NOT_ALLOWED',
+ 'DEVICE_LINK_CONTROL_DISABLED',
+ 'DEVICE_LINK_STANDBY',
+]);
+
+/** Terminal for this replay; later online/reconnect triggers can start another. */
+export function isPermanentSubscriptionReplayError(err: unknown, available: boolean | undefined): boolean {
+ const message = err instanceof Error ? err.message : String(err);
+ const code = err instanceof DeviceLinkError ? err.code : /\[([A-Z_]+)\]/.exec(message)?.[1];
+ // Bound the newly enabled unknown-state recovery on an explicit offline result.
+ // For known-available peers, preserve the pre-existing transient policy. This
+ // cached boolean does not establish event ordering; it may itself be stale.
+ // Route/presence reconciliation is outside this unknown-state recovery fix.
+ return code !== undefined && (
+ PERMANENT_SUBSCRIPTION_REPLAY_CODES.has(code)
+ || (code === 'DEVICE_OFFLINE' && available !== true)
+ );
+}
+
export type SubscriptionReplayRef = {
deviceId: string;
topics: string[];
@@ -17,8 +42,9 @@ type SubscriptionReplaySchedulerOptions = {
isLinkTornDown: () => boolean;
isRelayOnline: () => boolean;
isDeviceUnresponsive: (deviceId: string) => boolean;
- isPresenceAvailable: (deviceId: string) => boolean;
- isPermanentError: (error: unknown) => boolean;
+ /** undefined means this relay generation has not observed the peer yet. */
+ getPresenceAvailability: (deviceId: string) => boolean | undefined;
+ isPermanentError: (error: unknown, deviceId: string) => boolean;
log: {
debug(message: string): void;
warn(message: string): void;
@@ -73,7 +99,7 @@ export function createSubscriptionReplayScheduler(
inFlight.set(deviceId, requestToken);
void options.remoteSubscribe(deviceId, topics).catch((error: unknown) => {
if (currentGeneration(deviceId) !== gen) return;
- if (options.isPermanentError(error)) {
+ if (options.isPermanentError(error, deviceId)) {
options.log.warn(
`device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, permanent, giving up: ${String(error)}`,
);
@@ -89,7 +115,9 @@ export function createSubscriptionReplayScheduler(
if (currentGeneration(deviceId) !== gen) return;
if (options.isLinkTornDown() || !options.isRelayOnline()) return;
if (options.isDeviceUnresponsive(deviceId)) return;
- if (!options.isPresenceAvailable(deviceId)) return;
+ // Presence is incremental and resets on reconnect. Unknown must keep the
+ // existing backoff alive; only an explicit offline/disabled verdict stops it.
+ if (options.getPresenceAvailability(deviceId) === false) return;
const current = options
.snapshotSubscriptions(deviceId)
.find((ref) => ref.deviceId === deviceId);