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): sessions 订阅瞬时失败后由周期对账补订 (#5861)
Dash62d0c54df2fb
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteRecovery.test.tsx b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteRecovery.test.tsxindex 33c1c1cf10..9635cce970 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteRecovery.test.tsx+++ b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteRecovery.test.tsx@@ -177,6 +177,96 @@ describe('multi-device recovery lifecycle', () => {expect(subscribe).toHaveBeenCalledExactlyOnceWith('slow', ['sessions']);});+ it('transient sessions subscribe failure is retried by the periodic reconcile', async () => {+ subscribe.mockImplementation((peer: string) =>+ peer === 'slow' && subscribe.mock.calls.filter(([p]) => p === 'slow').length === 1+ ? Promise.reject(new Error('[DEVICE_LINK_BUSY] request expired before socket write'))+ : Promise.resolve({}),+ );+ renderHook(() => useDeviceLinkRemoteProjects());+ await settle();+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(1);+ // The list still bootstraps; only live pushes (running activity / island) were missing.+ expect(remoteProjectsStore.hasDevice('slow')).toBe(true);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(2);+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'healthy')).toHaveLength(1);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(2);+ });++ /** slow 首次 subscribe 报 BUSY,第二次(周期补订)交给返回的 deferred 手动收尾。 */+ async function startPendingResubscribe() {+ const retry = deferred<object>();+ let slowCalls = 0;+ let inFlight = 0;+ let maxInFlight = 0;+ subscribe.mockImplementation((peer: string) => {+ if (peer !== 'slow') return Promise.resolve({});+ slowCalls += 1;+ if (slowCalls === 1) {+ return Promise.reject(new Error('[DEVICE_LINK_BUSY] request expired before socket write'));+ }+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ const pending = slowCalls === 2 ? retry.promise : Promise.resolve({});+ return pending.finally(() => {+ inFlight -= 1;+ });+ });+ renderHook(() => useDeviceLinkRemoteProjects());+ await settle();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(2);+ return { retry, maxInFlight: () => maxInFlight };+ }++ it('a late resubscribe revocation cannot remove a device that re-entered', async () => {+ const { retry } = await startPendingResubscribe();+ act(() => control(false));+ act(() => control(true));+ await settle();+ retry.reject(new Error('[DEVICE_LINK_ACCESS_REVOKED] old connection'));+ await settle();+ expect(revokedDevicesStore.has('slow')).toBe(false);+ expect(remoteProjectsStore.hasDevice('slow')).toBe(true);+ // The re-entered lifecycle still runs its own full bootstrap after the stale request.+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(3);+ });++ it('a bootstrap requested during resubscribe waits instead of subscribing concurrently', async () => {+ const { retry, maxInFlight } = await startPendingResubscribe();+ act(() =>+ listeners.onResponsivenessChanged({ deviceId: 'slow', unresponsive: false, recovered: true }),+ );+ await settle();+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(2);+ retry.resolve({});+ await settle();+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(3);+ expect(maxInFlight()).toBe(1);+ });++ it('unsupported sessions subscribe is not retried', async () => {+ subscribe.mockImplementation((peer: string) =>+ peer === 'slow'+ ? Promise.reject(new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] old peer'))+ : Promise.resolve({}),+ );+ renderHook(() => useDeviceLinkRemoteProjects());+ await settle();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20_000);+ });+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(1);+ });+it('late initial settings cannot undo a disable notification', async () => {const initial = deferred<object>();getState.mockReturnValue(initial.promise);diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex df390ff141..927eee2778 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -288,6 +288,8 @@ export function startRemoteSessionsReconciler(};}+type BootstrapMode = 'full' | 'resubscribe';+type IneligibleRemoteProjectAction = 'disconnect' | 'remove' | 'ignore';export function resolveIneligibleRemoteProjectAction(input: {@@ -390,14 +392,39 @@ export function useDeviceLinkRemoteProjects(/** archived 读取终态失败后的 per-device 自动重试。 */const archivedRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();const archivedRetryDelayMs = new Map<string, number>();+ /**+ * 每设备一条串行任务:full = subscribe + 拉列表 + 预取;resubscribe = 只补 sessions 订阅。+ * 补订也走这里,保证同一设备同一时刻只有一路 subscribe,迟到结果由 lifecycleEpoch 挡掉。+ */const bootstrapTasks = new Map<string,- { promise: Promise<void>; rerun: boolean; name: string; lifecycleEpoch: number }+ {+ promise: Promise<void>;+ rerun: boolean;+ name: string;+ lifecycleEpoch: number;+ mode: BootstrapMode;+ }>();+ /**+ * sessions 订阅瞬时失败(如重连瞬间 DEVICE_LINK_BUSY)、待周期对账补订的设备。+ * 列表靠周期 sessions:list 仍会刷新,但运行活动(侧栏运行图标、灵动岛)只走 sessions push;+ * 不补订就会一直「列表可见、运行状态全无」,直到下一次重连 / 熔断恢复重跑 bootstrap。+ */+ const sessionsSubscribeRetry = new Set<string>();/** 隧道调用是否因「访问权限已被撤销」失败(被控端逐设备黑名单)。 */const isAccessRevoked = (err: unknown): boolean =>extractIpcError(err)?.code === 'DEVICE_LINK_ACCESS_REVOKED';+ /** 被控端明确不支持 / 已关闭被控时,重试 sessions 订阅没有意义。 */+ const isPermanentSubscribeError = (err: unknown): boolean => {+ const code = extractIpcError(err)?.code;+ return (+ code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED' ||+ code === 'DEVICE_LINK_REMOTE_DISABLED' ||+ code === 'DEVICE_LINK_VERSION_MISMATCH'+ );+ };const cancelDeviceReseeds = (deviceId: string): void => {for (const [key, pending] of reseedTimers) {@@ -444,6 +471,7 @@ export function useDeviceLinkRemoteProjects(evictTaskTagCatalog(deviceId);clearArchivedSessionRetry(deviceId);eligible.delete(deviceId);+ sessionsSubscribeRetry.delete(deviceId);revokedDevicesStore.markRevoked(deviceId);remoteProjectsStore.removeDevice(deviceId);removeRemoteSessionActivityForDevice(deviceId);@@ -457,18 +485,26 @@ export function useDeviceLinkRemoteProjects(/*** 订阅 sessions topic(push 驱动列表)+ bootstrap 拉一次全量。subscribe 失败不阻断- * bootstrap(退化为「快照可见、live 更新缺失」;被控端/控制端同版本时不会发生)。+ * bootstrap(暂时退化为「快照可见、live 更新缺失」);瞬时失败记入 sessionsSubscribeRetry,+ * 由周期对账补订,永久不支持的被控端不重试。* 任一步返回 ACCESS_REVOKED → 标记已撤销并移除该设备;全程无撤销 → 清掉残留标记(恢复收尾)。*/const canBootstrap = (deviceId: string, lifecycleEpoch: number): boolean =>!disposed && linkOnline !== false && eligible.has(deviceId) && !unresponsiveDevicesStore.has(deviceId) &&remoteProjectsStore.getDeviceLifecycleEpoch(deviceId) === lifecycleEpoch;- const runSubscribeAndBootstrap = async (deviceId: string, name: string, lifecycleEpoch: number): Promise<void> => {+ const runSubscribeAndBootstrap = async (+ deviceId: string,+ name: string,+ lifecycleEpoch: number,+ mode: BootstrapMode,+ ): Promise<void> => {if (!canBootstrap(deviceId, lifecycleEpoch)) return;- log.debug(`sessions refresh trigger=bootstrap window=${windowRole} peer=${deviceId.slice(0, 8)} visible=${periodicReconcileActiveRef.current}`);- // 新一轮 bootstrap 是有意义的重试:即使还保留旧 shard 也要显式进入- // loading,直到本轮落下 snapshot 或再次终态失败。- remoteProjectsStore.markBootstrapLoading(deviceId);+ if (mode === 'full') {+ log.debug(`sessions refresh trigger=bootstrap window=${windowRole} peer=${deviceId.slice(0, 8)} visible=${periodicReconcileActiveRef.current}`);+ // 新一轮 bootstrap 是有意义的重试:即使还保留旧 shard 也要显式进入+ // loading,直到本轮落下 snapshot 或再次终态失败。补订不进 loading:列表一直可用。+ remoteProjectsStore.markBootstrapLoading(deviceId);+ }const canContinue = (): boolean => {if (canBootstrap(deviceId, lifecycleEpoch)) return true;// An open circuit can interrupt bootstrap between reads. Settle its@@ -481,11 +517,18 @@ export function useDeviceLinkRemoteProjects(};try {await window.electronAPI.deviceLink.subscribe(deviceId, ['sessions']);+ if (sessionsSubscribeRetry.delete(deviceId) && mode === 'resubscribe') {+ log.debug(`subscribe(sessions) recovered for ${deviceId.slice(0, 8)}`);+ }} catch (err) {if (!canContinue()) return;if (isAccessRevoked(err)) return void handleRevoked(deviceId);+ if (isPermanentSubscribeError(err)) sessionsSubscribeRetry.delete(deviceId);+ else sessionsSubscribeRetry.add(deviceId);if (!disposed) log.debug(`subscribe(sessions) failed for ${deviceId.slice(0, 8)}`, err);}+ // 补订成功后被控端会定向重放当前活动快照,运行图标与灵动岛随之恢复;列表由周期对账负责。+ if (mode === 'resubscribe') return;if (!canContinue()) return;// bootstrap 期间被撤销(subscribe 成功、list 被拒)→ refreshRemoteDeviceSessions 返 'revoked'// (而非静默 give-up)→ 这里 handleRevoked,而不是继续预取能力 / 清撤销标记无视拒绝。@@ -519,7 +562,12 @@ export function useDeviceLinkRemoteProjects(revokedDevicesStore.clearRevoked(deviceId);};- const subscribeAndBootstrap = (deviceId: string, name: string, refreshAfterCurrent = false): Promise<void> => {+ const subscribeAndBootstrap = (+ deviceId: string,+ name: string,+ refreshAfterCurrent = false,+ mode: BootstrapMode = 'full',+ ): Promise<void> => {const lifecycleEpoch = remoteProjectsStore.getDeviceLifecycleEpoch(deviceId);const existing = bootstrapTasks.get(deviceId);if (existing) {@@ -528,15 +576,20 @@ export function useDeviceLinkRemoteProjects(// recovery/user retry still requests one fresh follow-up, as does a new lifecycle.existing.rerun ||= refreshAfterCurrent || existing.lifecycleEpoch !== lifecycleEpoch;existing.lifecycleEpoch = lifecycleEpoch;+ // A full bootstrap requested while only a resubscribe runs must still run in full.+ if (mode === 'full' && existing.mode === 'resubscribe') {+ existing.rerun = true;+ existing.mode = 'full';+ }return existing.promise;}- const task = { promise: Promise.resolve(), rerun: false, name, lifecycleEpoch };+ const task = { promise: Promise.resolve(), rerun: false, name, lifecycleEpoch, mode };task.promise = (async () => {try {do {task.rerun = false;- await runSubscribeAndBootstrap(deviceId, task.name, task.lifecycleEpoch);+ await runSubscribeAndBootstrap(deviceId, task.name, task.lifecycleEpoch, task.mode);} while (canBootstrap(deviceId, task.lifecycleEpoch) && task.rerun);} finally {if (bootstrapTasks.get(deviceId) === task) bootstrapTasks.delete(deviceId);@@ -575,6 +628,7 @@ export function useDeviceLinkRemoteProjects(}} else {const wasEligible = eligible.delete(d.deviceId);+ sessionsSubscribeRetry.delete(d.deviceId);const action = resolveIneligibleRemoteProjectAction({wasEligible,hasCachedShard: remoteProjectsStore.hasDevice(d.deviceId),@@ -721,6 +775,11 @@ export function useDeviceLinkRemoteProjects(() => (linkOnline ? [...eligible].filter(([id]) => !unresponsiveDevicesStore.has(id)) : []),async (deviceId, name) => {log.debug(`sessions refresh trigger=periodic window=${windowRole} peer=${deviceId.slice(0, 8)} visible=${periodicReconcileActiveRef.current}`);+ if (sessionsSubscribeRetry.has(deviceId)) {+ // 与 bootstrap 同一串行任务:在途的 bootstrap 直接复用,不并发第二路 subscribe。+ await subscribeAndBootstrap(deviceId, name ?? eligible.get(deviceId) ?? deviceId, false, 'resubscribe');+ if (disposed || !eligible.has(deviceId)) return 'superseded';+ }// sessions:list 是 200 条有界窗口;refresh 层会保留窗口外 active 行,并有界补查// 缺席缓存 id 的终态,不能直接把响应缺席解释成删除。const result = await refreshRemoteDeviceSessions(deviceId, name, {