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): cancel stale recovery work on device cleanup
DavidShen03502b358505
diff --git a/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts b/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.tsindex d82d4b52b7..979dacf67f 100644--- a/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts@@ -69,6 +69,44 @@ async function openBreaker(}describe('responsivenessTracker', () => {+ it('late probe timeout cannot recover a newly opened lifecycle', async () => {+ const recoverLink = vi.fn(async () => {});+ const h = harness({ recoverLink });+ await openBreaker(h);+ let reject!: (err: Error) => void;+ h.probeInvoke.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));+ h.advance(BREAKER_PROBE_BACKOFF_BASE_MS);+ h.tracker.probeTick();+ h.tracker.clearDevice(DEV);+ await openBreaker(h);+ recoverLink.mockClear();+ reject(timeoutError());+ await new Promise<void>((resolve) => queueMicrotask(resolve));+ expect(recoverLink).not.toHaveBeenCalled();+ expect(h.tracker.isUnresponsive(DEV)).toBe(true);+ });++ it('clearing one failed peer does not signal recovery or disturb a healthy peer', async () => {+ const h = harness();+ await openBreaker(h);+ h.tracker.clearDevice(DEV);+ expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false, false);+ await expect(h.tracker.guardInvoke(OTHER_DEV, 'local-db:sessions:list', async () => ['healthy']))+ .resolves.toEqual(['healthy']);+ });++ it.each(['clearDevice', 'resetAll'] as const)('late business timeout after %s cannot restart recovery', async (action) => {+ const recoverLink = vi.fn(async () => {});+ const h = harness({ recoverLink });+ let reject!: (err: Error) => void;+ const request = h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () =>+ new Promise((_resolve, fail) => { reject = fail; }));+ if (action === 'clearDevice') h.tracker.clearDevice(DEV);+ else h.tracker.resetAll();+ reject(timeoutError());+ await expect(request).rejects.toThrow();+ expect(recoverLink).not.toHaveBeenCalled();+ });it('重连清空 presence 后 unknown 仍允许单飞探测,明确 false 与其它硬门继续阻止', () => {const base = {relayOnline: true,@@ -123,7 +161,7 @@ describe('responsivenessTracker', () => {it('连续超时达到阈值 → open,通知 UI,后续请求快速失败且不再上管道', async () => {const h = harness();await openBreaker(h);- expect(h.onUnresponsiveChanged).toHaveBeenCalledWith(DEV, true);+ expect(h.onUnresponsiveChanged).toHaveBeenCalledWith(DEV, true, false);expect(h.tracker.getUnresponsiveDeviceIds()).toEqual([DEV]);const run = vi.fn(async () => 'never');@@ -233,7 +271,7 @@ describe('responsivenessTracker', () => {await vi.waitFor(() => {expect(h.tracker.isUnresponsive(DEV)).toBe(false);});- expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false);+ expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false, true);});it('熔断已 open 时 relay 换代把 presence 从 false 清为 unknown,下一拍恢复单飞探测', async () => {@@ -398,8 +436,8 @@ describe('responsivenessTracker', () => {expect(openLinkB).toHaveBeenCalledTimes(1);// 状态翻转通知只发给 A,B 从未被标记- expect(h.onUnresponsiveChanged).toHaveBeenCalledWith(DEV, true);- expect(h.onUnresponsiveChanged).not.toHaveBeenCalledWith(DEV_B, expect.anything());+ expect(h.onUnresponsiveChanged).toHaveBeenCalledWith(DEV, true, false);+ expect(h.onUnresponsiveChanged).not.toHaveBeenCalledWith(DEV_B, expect.anything(), expect.anything());});it('clearDevice 清理在途 recovery 后允许再次触发恢复', async () => {@@ -416,17 +454,17 @@ describe('responsivenessTracker', () => {expect(recoverLink).toHaveBeenCalledTimes(2);});- it('resetAll 关闭所有 open 设备并通知恢复', async () => {+ it('resetAll clears all failed peers without claiming recovery', async () => {const h = harness();await openBreaker(h);h.tracker.resetAll();expect(h.tracker.getUnresponsiveDeviceIds()).toEqual([]);- expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false);+ expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false, false);});});describe('classifyDeviceSendFailure / classifyDeviceSendSuccess', () => {- it('INVOKE_TIMEOUT 计失败;终态 relay 应答是恢复证据;其余不定论', () => {+ it('INVOKE_TIMEOUT 计失败;终态 relay 应答是回包证据;其余不定论', () => {expect(classifyDeviceSendFailure(timeoutError())).toBe('timeout');// 终态 = relay/对端在明确应答,「无响应」不成立;presence 竞态下归不定论// 会让熔断 open 后的周期探测永远关不上(review P2)。@@ -492,7 +530,7 @@ describe('classifyDeviceSendFailure / classifyDeviceSendSuccess', () => {it('熔断 open 后探测收到终态 relay 应答 → 关熔断(终态 UI 不被「无响应」遮蔽)', async () => {// presence 未及时翻转的竞态下,终态应答(DEVICE_OFFLINE 等)是「链路在明确- // 应答」的恢复证据。open 期间业务 guard 一律快速失败,探测是唯一上管道的+ // 应答」的回包证据,不代表设备恢复。open 期间业务 guard 一律快速失败,探测是唯一上管道的// 流量,终态应答经探测失败路径进入 classifyDeviceSendFailure 关熔断,让位// 给对应终态自己的 UI。const h = harness();@@ -503,7 +541,7 @@ describe('classifyDeviceSendFailure / classifyDeviceSendSuccess', () => {await vi.waitFor(() => {expect(h.tracker.isUnresponsive(DEV)).toBe(false);});- expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false);+ expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false, false);});it('控制帧 / dispatch 特判通道的成功不定论;业务 DB 通道的成功是恢复证据', () => {diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 9fd94d5405..9ceb219be0 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -723,12 +723,12 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v}return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'));},- onUnresponsiveChanged: (deviceId, unresponsive) => {- broadcast(DEVICE_LINK_PUSH.RESPONSIVENESS_CHANGED, { deviceId, unresponsive });+ onUnresponsiveChanged: (deviceId, unresponsive, recovered) => {+ broadcast(DEVICE_LINK_PUSH.RESPONSIVENESS_CHANGED, { deviceId, unresponsive, recovered });// 恢复时主动重放该设备的订阅:熔断 open 期间 subscribe 都被快速失败挡掉了,// 不重放的话 push 驱动的列表 / 会话镜像会一直缺流,直到用户手动重试。// linkTornDown 闸:teardown 的 resetAll 也会触发本回调,那时不能再发订阅。- if (!unresponsive && !linkTornDown && client?.getStatus() === 'online') {+ if (recovered && !linkTornDown && client?.getStatus() === 'online') {replayActiveSubscriptions(`responsiveness-recovered:${deviceId.slice(0, 8)}`, deviceId);}},diff --git a/apps/desktop/src/main/device-link/responsivenessTracker.ts b/apps/desktop/src/main/device-link/responsivenessTracker.tsindex 6bc8cdb0ee..1fa7efb229 100644--- a/apps/desktop/src/main/device-link/responsivenessTracker.ts+++ b/apps/desktop/src/main/device-link/responsivenessTracker.ts@@ -143,7 +143,7 @@ export function isBreakerObservedError(err: unknown): boolean {/*** 失败 → 熔断信号:仅 INVOKE_TIMEOUT(等满超时无回包)计失败;**终态 relay 应答*** (DEVICE_OFFLINE / REMOTE_DISABLED / VERSION_MISMATCH)是「链路在明确应答」的- * 恢复证据(responded)——「无响应」语义只对无回包成立,relay 已给出终态时应+ * 回包证据(responded),但不是设备恢复证据——「无响应」语义只对无回包成立,relay 已给出终态时应* 让位给对应的终态 UI;presence 未及时翻转的竞态下,若归不定论,熔断 open 后的* 周期探测收到同类终态也永远关不上(review P2)。对**任何** channel(含嵌套* openLink 冒泡到外层业务 channel 的失败)统一适用,失败来源无需特判。@@ -185,8 +185,8 @@ export interface ResponsivenessTrackerDeps {* 拿到探测席位后调用;实现方直接走 client.invoke,不要再套 remoteInvoke)。*/probeInvoke(deviceId: string, channel: string, args: unknown[]): Promise<unknown>;- /** 熔断 open/close 翻转回调(广播给 renderer + 恢复时重放订阅)。同状态不重复触发。 */- onUnresponsiveChanged(deviceId: string, unresponsive: boolean): void;+ /** State changes always update UI; recovered is false for cleanup or terminal relay replies. */+ onUnresponsiveChanged(deviceId: string, unresponsive: boolean, recovered: boolean): void;/** 探测前置条件:本实例持有 relay、链路 online、目标设备 presence 可用。 */isProbeEligible(deviceId: string): boolean;/** 首次业务超时后的 peer 级恢复;由 Desktop 接入 openRemoteLink 去重。 */@@ -226,6 +226,10 @@ export function createResponsivenessTracker(const unresponsive = new Set<string>();const linkRecoveryInFlight = new Map<string, Promise<unknown>>();const bootstrapFanOutCohorts = new Map<string, { cohort: number; expiresAt: number }>();+ const lifecycleEpochs = new Map<string, number>();+ // Only a successful response permits recovery work. Clearing state or a relay+ // offline/revoked reply must close the breaker without replaying subscriptions.+ let recoveryEvidence = false;const breaker = createDeviceResponsivenessBreaker({now,onOpenChanged: (deviceId, open) => {@@ -234,12 +238,22 @@ export function createResponsivenessTracker(log.info(`device ${deviceId.slice(0, 8)} responsiveness circuit ${open ? 'opened' : 'closed'}`,);- deps.onUnresponsiveChanged(deviceId, open);+ deps.onUnresponsiveChanged(deviceId, open, !open && recoveryEvidence);},});- const settle = (deviceId: string, slot: BreakerSendSlot, outcome: BreakerSettleOutcome): void => {- breaker.settle(deviceId, slot, outcome);+ const settle = (+ deviceId: string,+ slot: BreakerSendSlot,+ outcome: BreakerSettleOutcome,+ responded = true,+ ): void => {+ recoveryEvidence = responded && outcome === 'responded';+ try {+ breaker.settle(deviceId, slot, outcome);+ } finally {+ recoveryEvidence = false;+ }};const triggerLinkRecovery = (deviceId: string): void => {@@ -284,6 +298,8 @@ export function createResponsivenessTracker(run: () => Promise<T>,cohortOverride?: number,): Promise<T> => {+ const lifecycleEpoch = lifecycleEpochs.get(deviceId) ?? 0;+ lifecycleEpochs.set(deviceId, lifecycleEpoch);const cohort = selectCohort(deviceId, channel, cohortOverride);const slot = breaker.acquire(deviceId, cohort, { allowProbe: false });if (slot.decision === 'reject') throw createDeviceUnresponsiveError(deviceId);@@ -305,14 +321,17 @@ export function createResponsivenessTracker(? 'inconclusive': classifyDeviceSendFailure(err);markBreakerObserved(err);- settle(deviceId, slot, outcome);- if (outcome === 'timeout') triggerLinkRecovery(deviceId);+ settle(deviceId, slot, outcome, false);+ if (outcome === 'timeout' && lifecycleEpochs.get(deviceId) === lifecycleEpoch)+ triggerLinkRecovery(deviceId);throw err;}};const probeTick = (): void => {for (const deviceId of [...unresponsive]) {+ const lifecycleEpoch = lifecycleEpochs.get(deviceId) ?? 0;+ lifecycleEpochs.set(deviceId, lifecycleEpoch);if (!breaker.probeDue(deviceId)) continue;if (!deps.isProbeEligible(deviceId)) continue;log.debug(`probing unresponsive device ${deviceId.slice(0, 8)}`);@@ -333,17 +352,21 @@ export function createResponsivenessTracker(void Promise.resolve(probePromise).then(() =>- breaker.settle(+ settle(deviceId,slot,classifyDeviceSendSuccess(DEVICE_RESPONSIVENESS_PROBE_CHANNEL, true),),(err) => {const outcome = classifyDeviceSendFailure(err);- breaker.settle(deviceId, slot, outcome);+ settle(deviceId, slot, outcome, false);// 探测是 open 后唯一会真正穿过 peer link 的流量。若它仍等满超时,// 继续按单-peer 半径重开 link;clear/reset 已翻代时 breaker 会先关闭。- if (outcome === 'timeout' && breaker.isOpen(deviceId)) {+ if (+ outcome === 'timeout' &&+ lifecycleEpochs.get(deviceId) === lifecycleEpoch &&+ breaker.isOpen(deviceId)+ ) {triggerLinkRecovery(deviceId);}throw err;@@ -361,11 +384,13 @@ export function createResponsivenessTracker(isUnresponsive: (deviceId) => unresponsive.has(deviceId),getUnresponsiveDeviceIds: () => [...unresponsive],clearDevice: (deviceId) => {+ lifecycleEpochs.set(deviceId, (lifecycleEpochs.get(deviceId) ?? 0) + 1);linkRecoveryInFlight.delete(deviceId);bootstrapFanOutCohorts.delete(deviceId);breaker.clear(deviceId);},resetAll: () => {+ for (const [deviceId, epoch] of lifecycleEpochs) lifecycleEpochs.set(deviceId, epoch + 1);linkRecoveryInFlight.clear();bootstrapFanOutCohorts.clear();breaker.resetAll();diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteRecovery.test.tsx b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteRecovery.test.tsxnew file mode 100644index 0000000000..b3f8f9e24b--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteRecovery.test.tsx@@ -0,0 +1,185 @@+// @vitest-environment jsdom+import { act, cleanup, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/contexts/AuthContext', () => ({+ useAuth: () => ({+ isAuthenticated: true,+ deviceId: 'self',+ dataOwnerId: 'test-owner',+ }),+}));+vi.mock('@/hooks/useAgentCapabilities', () => ({+ prefetchDeviceCapabilities: vi.fn(),+ evictDeviceCapabilities: vi.fn(),+}));+vi.mock('@/hooks/useDeviceProviders', () => ({+ prefetchDeviceProviders: vi.fn(),+ evictDeviceProviders: vi.fn(),+}));+vi.mock('@/hooks/useGitSafetySettings', () => ({+ prefetchDeviceGitSafetySettings: vi.fn(),+ evictDeviceGitSafetySettings: vi.fn(),+}));+vi.mock('@/features/device-link/mirrorCacheClient', () => ({+ cancelSessionListPersist: vi.fn(),+ clearCachedDevice: vi.fn(),+ clearMirrorCacheAccountState: vi.fn(),+ readCachedSessionList: vi.fn(async () => []),+ scheduleSessionListPersist: vi.fn(),+ sessionListOwnerTokensReady: () => true,+}));+vi.mock('@/lib/logger', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++import { useDeviceLinkRemoteProjects } from '@/features/device-link/useDeviceLinkRemoteProjects';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';++/** Real hook/store/refresh orchestration with independent controllable peer transports. */+const peers = ['slow', 'healthy'].map((deviceId) => ({+ deviceId,+ name: deviceId,+ online: true,+ remoteControlEnabled: true,+ isSelf: false,+}));+type Listener = (event: any) => void;+let listeners: Record<string, Listener>;+const subscribe = vi.fn();+const invoke = vi.fn();+const getState = vi.fn();+function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: Error) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+async function settle() {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+}+const control = (enabled: boolean) =>+ listeners.onControlTargetChanged({+ deviceId: 'slow',+ enabled,+ disabledControlDeviceIds: enabled ? [] : ['slow'],+ });++beforeEach(() => {+ vi.useFakeTimers();+ listeners = {};+ subscribe.mockReset().mockResolvedValue({});+ invoke+ .mockReset()+ .mockImplementation(async (_peer, channel) =>+ channel === 'maker:schedule:list-sidebar-index-runs' ? { runs: [] } : [],+ );+ getState.mockReset().mockResolvedValue({ linkStatus: 'online', disabledControlDeviceIds: [] });+ const events = Object.fromEntries(+ [+ 'onResponsivenessChanged',+ 'onPresenceChanged',+ 'onRemotePush',+ 'onStatusChanged',+ 'onAccessRevoked',+ 'onControlTargetChanged',+ ].map((name) => [+ name,+ (listener: Listener) => {+ listeners[name] = listener;+ return () => {};+ },+ ]),+ );+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ deviceLink: {+ ...events,+ subscribe,+ invoke,+ getState,+ unsubscribe: vi.fn(async () => {}),+ listDevices: vi.fn(async () => ({ devices: peers })),+ },+ },+ });+});+afterEach(() => {+ cleanup();+ remoteProjectsStore.clear();+ vi.useRealTimers();+});++describe('multi-device recovery lifecycle', () => {+ it('slow subscription does not delay a healthy peer, and disable cancels queued bootstrap', async () => {+ const slow = deferred<object>();+ subscribe.mockImplementation((peer: string) =>+ peer === 'slow' ? slow.promise : Promise.resolve({}),+ );+ renderHook(() => useDeviceLinkRemoteProjects());+ await settle();+ expect(remoteProjectsStore.hasDevice('healthy')).toBe(true);+ expect(remoteProjectsStore.hasDevice('slow')).toBe(false);+ act(() =>+ listeners.onResponsivenessChanged({ deviceId: 'slow', unresponsive: false, recovered: true }),+ );+ act(() => control(false));+ slow.resolve({});+ await settle();+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(1);+ expect(invoke.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(0);+ expect(remoteProjectsStore.hasDevice('healthy')).toBe(true);+ });++ it('clearing failure state does not bootstrap, but genuine recovery does', async () => {+ renderHook(() => useDeviceLinkRemoteProjects());+ await settle();+ subscribe.mockClear();+ act(() =>+ listeners.onResponsivenessChanged({+ deviceId: 'slow',+ unresponsive: false,+ recovered: false,+ }),+ );+ await settle();+ expect(subscribe).not.toHaveBeenCalled();+ act(() =>+ listeners.onResponsivenessChanged({ deviceId: 'slow', unresponsive: false, recovered: true }),+ );+ await settle();+ expect(subscribe).toHaveBeenCalledExactlyOnceWith('slow', ['sessions']);+ });++ it('late initial settings cannot undo a disable notification', async () => {+ const initial = deferred<object>();+ getState.mockReturnValue(initial.promise);+ renderHook(() => useDeviceLinkRemoteProjects());+ act(() => control(false));+ initial.resolve({ linkStatus: 'online', disabledControlDeviceIds: [] });+ await settle();+ expect(subscribe.mock.calls.map(([peer]) => peer)).toEqual(['healthy']);+ });++ it('disable/re-enable waits for the old subscription and rejects its late revocation', async () => {+ const old = deferred<object>();+ subscribe.mockImplementationOnce(() => old.promise);+ renderHook(() => useDeviceLinkRemoteProjects());+ await settle();+ act(() => control(false));+ act(() => control(true));+ await settle();+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(1);+ old.reject(new Error('[DEVICE_LINK_ACCESS_REVOKED] old connection'));+ await settle();+ expect(subscribe.mock.calls.filter(([peer]) => peer === 'slow')).toHaveLength(2);+ expect(remoteProjectsStore.hasDevice('slow')).toBe(true);+ expect(remoteProjectsStore.hasDevice('healthy')).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex 95b8fede07..213f2c7d53 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -99,6 +99,54 @@ function deferred<T>() {return { promise, resolve, reject };}+describe('refresh lifecycle cancellation', () => {+ it.each(['removeDevice', 'markDeviceDisconnected', 'markAllDisconnected', 'clear'] as const)(+ '%s cancels queued strong refreshes, while another peer remains usable', async (action) => {+ const device = did();+ const pending = deferred<Session[]>();+ invoke.mockImplementation((peer: string) => peer === device ? pending.promise : Promise.resolve([session('healthy')]));+ const first = refreshRemoteDeviceSessions(device);+ const queued = refreshRemoteDeviceSessions(device);+ if (action === 'removeDevice' || action === 'markDeviceDisconnected') remoteProjectsStore[action](device);+ else remoteProjectsStore[action]();+ await expect(refreshRemoteDeviceSessions(did())).resolves.toBe('ok');+ pending.resolve([session('cancelled')]);+ expect(await Promise.all([first, queued])).toEqual(['superseded', 'superseded']);+ expect(invoke.mock.calls.filter(([peer]) => peer === device)).toHaveLength(1);+ expect(remoteProjectsStore.getDeviceSessions(device)).toEqual([]);+ },+ );++ it('re-enabling waits for the old physical request, then reads a fresh snapshot', async () => {+ const device = did();+ const pending = deferred<Session[]>();+ invoke.mockReturnValueOnce(pending.promise).mockResolvedValue([session('fresh')]);+ const old = refreshRemoteDeviceSessions(device);+ const queued = refreshRemoteDeviceSessions(device);+ remoteProjectsStore.removeDevice(device);+ const renewed = refreshRemoteDeviceSessions(device);+ expect(invoke).toHaveBeenCalledTimes(1);+ pending.resolve([session('stale')]);+ expect(await Promise.all([old, queued, renewed])).toEqual(['superseded', 'superseded', 'ok']);+ expect(invoke).toHaveBeenCalledTimes(2);+ expect(remoteProjectsStore.getDeviceSessions(device).map(row => row.id)).toEqual(['fresh']);+ });++ it('weak-network reads retain a fresh follow-up for new events', async () => {+ const device = did();+ const pending = deferred<Session[]>();+ invoke.mockReturnValueOnce(pending.promise).mockResolvedValue([session('created-during-read')]);+ const old = refreshRemoteDeviceSessions(device);+ const tick = refreshRemoteDeviceSessions(device, undefined, { coalescingMode: 'weak' });+ const changed = refreshRemoteDeviceSessions(device);+ expect(invoke).toHaveBeenCalledTimes(1);+ pending.resolve([session('old')]);+ await Promise.all([old, tick, changed]);+ expect(invoke).toHaveBeenCalledTimes(2);+ expect(remoteProjectsStore.getDeviceSessions(device).map(row => row.id)).toEqual(['created-during-read']);+ });+});+describe('isTransientRemoteError', () => {it('瞬态标记 → true', () => {expect(isTransientRemoteError('Error: DbClient not ready')).toBe(true);diff --git a/apps/desktop/src/renderer/__tests__/remoteModelFavorites.test.tsx b/apps/desktop/src/renderer/__tests__/remoteModelFavorites.test.tsxindex a80a1ee7f5..de15b82511 100644--- a/apps/desktop/src/renderer/__tests__/remoteModelFavorites.test.tsx+++ b/apps/desktop/src/renderer/__tests__/remoteModelFavorites.test.tsx@@ -37,6 +37,17 @@ beforeEach(() => {root = createRoot(document.createElement('div'));});afterEach(() => act(() => root.unmount()));+it('does not refresh for an opened or administratively cleared breaker', async () => {+ await act(async () => root.render(createElement(Probe, {})));+ invoke.mockClear();+ await act(async () => {+ responsive({ deviceId: 'a', unresponsive: true, recovered: false });+ responsive({ deviceId: 'a', unresponsive: false, recovered: false });+ });+ expect(invoke).not.toHaveBeenCalled();+ await act(async () => responsive({ deviceId: 'a', unresponsive: false, recovered: true }));+ expect(invoke).toHaveBeenCalledTimes(1);+});it.each(['status', 'peer', 'responsive'])('retains keyed favorites on failed %s refresh and replaces only on success', async event => {await act(async () => root.render(createElement(Probe, {})));const refresh = () => event === 'status' ? statusChanged()diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.tsindex 0916212321..c511bd338f 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts@@ -478,10 +478,10 @@ export function useRemoteSessionSync(const offResponsiveness = window.electronAPI.deviceLink.onResponsivenessChanged((p) => {if (p.deviceId === deviceId) {const responsive = !p.unresponsive;- if (peerResponsive !== responsive) recovery.invalidate(responsive && relayAvailable !== false && peerAvailable !== false);+ if (peerResponsive !== responsive) recovery.invalidate(responsive && p.recovered !== false && relayAvailable !== false && peerAvailable !== false);peerResponsive = responsive;}- if (p.unresponsive) return;+ if (p.unresponsive || p.recovered === false) return;engine.handleResponsivenessRecovered(p.deviceId);});const offStore = makerChatStore.subscribe(sessionId, () => {diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex aed914a42d..bfe8d6c872 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -144,6 +144,7 @@ export type RefreshResult = 'ok' | 'revoked' | 'superseded' | 'gave-up';interface RefreshTask {promise: Promise<RefreshResult>;+ lifecycleEpoch: number;rerun: boolean;name?: string;opts: RefreshOptions;@@ -195,8 +196,17 @@ export async function refreshRemoteDeviceSessions(): Promise<RefreshResult> {const status = opts.status ?? 'active';const taskKey = refreshTaskKey(deviceId, status);+ const lifecycleEpoch = remoteProjectsStore.getDeviceLifecycleEpoch(deviceId);const existing = refreshTasks.get(taskKey);if (existing) {+ if (existing.lifecycleEpoch !== lifecycleEpoch) {+ // Keep the physical request single-flight across disable/re-enable. A new+ // caller may retry after it settles; the cancelled caller cannot do so.+ await existing.promise;+ if (remoteProjectsStore.getDeviceLifecycleEpoch(deviceId) !== lifecycleEpoch)+ return 'superseded';+ return refreshRemoteDeviceSessions(deviceId, name, opts);+ }const requestedSnapshotMode = opts.snapshotMode ?? 'merge';// periodic tick 是弱语义:已有任意 refresh 在途时直接复用,不能每个 interval tick// 都 bump epoch 让慢请求自取消。bootstrap/reseed 等事件型 refresh 仍走强语义补跑。@@ -225,6 +235,7 @@ export async function refreshRemoteDeviceSessions(const task: RefreshTask = {promise: Promise.resolve('gave-up'),+ lifecycleEpoch,rerun: false,name,opts,@@ -239,6 +250,8 @@ export async function refreshRemoteDeviceSessions(async function drainRefreshTask(deviceId: string, task: RefreshTask): Promise<RefreshResult> {let result: RefreshResult = 'gave-up';do {+ if (remoteProjectsStore.getDeviceLifecycleEpoch(deviceId) !== task.lifecycleEpoch)+ return 'superseded';task.rerun = false;result = await runRefreshRemoteDeviceSessions(deviceId, task.name, task.opts);// revoked 是被控端明确拒绝,不再补跑排队请求。@@ -375,6 +388,7 @@ async function runRefreshRemoteDeviceSessions(await probeMissingSessionStatuses(deviceId, epoch, missingCompanionIds, status);}}+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return 'superseded';if (opts.scope === 'schedule' || opts.scope === 'both') {try {const raw = await window.electronAPI.deviceLink.invoke(diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.tsindex a93e3e41f1..4053e2f30a 100644--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts@@ -99,9 +99,8 @@ const renameSubs = new Set<(deviceId: string, name: string) => void>();* 故 mark disconnected / remove / clear 都用自增(条目保留,仅随 distinct 设备数增长,可忽略)。*/const snapshotEpoch = new Map<string, number>();-// Detail reads do not share list epochs: sessions:list deliberately omits bots.-// Keep monotonic lifecycle/patch revisions only for devices and sessions opened-// through detail reads, including reads begun before the first shard exists.+// Lifecycle revisions are shared by detail reads and queued refreshes. Snapshot+// epochs alone cannot cancel a rerun that has not acquired its next epoch yet.const detailDeviceEpoch = new Map<string, number>();const detailPatchEpoch = new Map<string, number>();// Origin/connection restamps retain content identity. Authoritative snapshots@@ -927,6 +926,13 @@ const actions = {return status ? sessions.filter((session) => session.status === status) : sessions;},+ /** Cancel pending work on disconnect/removal without cancelling ordinary fresh reads. */+ getDeviceLifecycleEpoch(deviceId: string): number {+ const epoch = detailDeviceEpoch.get(deviceId) ?? 0;+ detailDeviceEpoch.set(deviceId, epoch);+ return epoch;+ },+/** A detail read must not roll back a newer push, deletion, or device lifecycle. */captureSessionRead(deviceId: string, sessionId: string): (() => boolean) & { mergeActivity: (detail: Session) => Session } {const beforeRow = shards.get(deviceId)?.sessions.find((session) => session.id === sessionId);diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex d79b73da5a..9e1815bb76 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -378,6 +378,7 @@ export function useDeviceLinkRemoteProjects(const eligible = new Map<string, string>();/** 本机主动关闭控制的目标设备(控制端本地偏好)。 */let disabledControlDeviceIds = new Set<string>();+ let controlTargetPushSeen = false;/** sessions:created / archived 按需加载的 per-device+status 防抖 timer */const reseedTimers = new Map<string, ReturnType<typeof setTimeout>>();/** archived 读取终态失败后的 per-device 自动重试。 */@@ -385,13 +386,21 @@ export function useDeviceLinkRemoteProjects(const archivedRetryDelayMs = new Map<string, number>();const bootstrapTasks = new Map<string,- { promise: Promise<void>; rerun: boolean; name: string }+ { promise: Promise<void>; rerun: boolean; name: string; lifecycleEpoch: number }>();/** 隧道调用是否因「访问权限已被撤销」失败(被控端逐设备黑名单)。 */const isAccessRevoked = (err: unknown): boolean =>extractIpcError(err)?.code === 'DEVICE_LINK_ACCESS_REVOKED';+ const cancelDeviceReseeds = (deviceId: string): void => {+ for (const [key, pending] of reseedTimers) {+ if (!key.startsWith(`${deviceId}\u0000`)) continue;+ clearTimeout(pending);+ reseedTimers.delete(key);+ }+ };+const clearArchivedSessionRetry = (deviceId: string): void => {const timer = archivedRetryTimers.get(deviceId);if (timer) clearTimeout(timer);@@ -425,6 +434,7 @@ export function useDeviceLinkRemoteProjects(* subscribeAndBootstrap 重试 —— 被控端恢复后即自动接回。*/const handleRevoked = (deviceId: string): void => {+ cancelDeviceReseeds(deviceId);evictTaskTagCatalog(deviceId);clearArchivedSessionRetry(deviceId);eligible.delete(deviceId);@@ -444,10 +454,11 @@ export function useDeviceLinkRemoteProjects(* bootstrap(退化为「快照可见、live 更新缺失」;被控端/控制端同版本时不会发生)。* 任一步返回 ACCESS_REVOKED → 标记已撤销并移除该设备;全程无撤销 → 清掉残留标记(恢复收尾)。*/- const canBootstrap = (deviceId: string): boolean =>- !disposed && linkOnline !== false && eligible.has(deviceId);- const runSubscribeAndBootstrap = async (deviceId: string, name: string): Promise<void> => {- if (!canBootstrap(deviceId)) return;+ const canBootstrap = (deviceId: string, lifecycleEpoch: number): boolean =>+ !disposed && linkOnline !== false && eligible.has(deviceId) &&+ remoteProjectsStore.getDeviceLifecycleEpoch(deviceId) === lifecycleEpoch;+ const runSubscribeAndBootstrap = async (deviceId: string, name: string, lifecycleEpoch: number): 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 或再次终态失败。@@ -455,15 +466,16 @@ export function useDeviceLinkRemoteProjects(try {await window.electronAPI.deviceLink.subscribe(deviceId, ['sessions']);} catch (err) {+ if (!canBootstrap(deviceId, lifecycleEpoch)) return;if (isAccessRevoked(err)) return void handleRevoked(deviceId);if (!disposed) log.debug(`subscribe(sessions) failed for ${deviceId.slice(0, 8)}`, err);}- if (!canBootstrap(deviceId)) return;+ if (!canBootstrap(deviceId, lifecycleEpoch)) return;// bootstrap 期间被撤销(subscribe 成功、list 被拒)→ refreshRemoteDeviceSessions 返 'revoked'// (而非静默 give-up)→ 这里 handleRevoked,而不是继续预取能力 / 清撤销标记无视拒绝。const result = await refreshRemoteDeviceSessions(deviceId, name, { scope: 'both' });+ if (!canBootstrap(deviceId, lifecycleEpoch)) return;if (result === 'revoked') return void handleRevoked(deviceId);- if (!canBootstrap(deviceId)) return;if (result === 'gave-up') {// 永久错误(如旧被控端 CHANNEL_NOT_ALLOWED)或瞬态重试耗尽:不是权威空列表,// 即使还有旧 shard 也必须标明本轮读取失败,不能把缓存伪装成刚返回的结果。@@ -483,21 +495,25 @@ export function useDeviceLinkRemoteProjects(revokedDevicesStore.clearRevoked(deviceId);};- const subscribeAndBootstrap = (deviceId: string, name: string): Promise<void> => {+ const subscribeAndBootstrap = (deviceId: string, name: string, refreshAfterCurrent = false): Promise<void> => {+ const lifecycleEpoch = remoteProjectsStore.getDeviceLifecycleEpoch(deviceId);const existing = bootstrapTasks.get(deviceId);if (existing) {existing.name = name;- existing.rerun = true;+ // Repeated discovery notifications share the current bootstrap. A real+ // recovery/user retry still requests one fresh follow-up, as does a new lifecycle.+ existing.rerun ||= refreshAfterCurrent || existing.lifecycleEpoch !== lifecycleEpoch;+ existing.lifecycleEpoch = lifecycleEpoch;return existing.promise;}- const task = { promise: Promise.resolve(), rerun: false, name };+ const task = { promise: Promise.resolve(), rerun: false, name, lifecycleEpoch };task.promise = (async () => {try {do {task.rerun = false;- await runSubscribeAndBootstrap(deviceId, task.name);- } while (!disposed && eligible.has(deviceId) && task.rerun);+ await runSubscribeAndBootstrap(deviceId, task.name, task.lifecycleEpoch);+ } while (canBootstrap(deviceId, task.lifecycleEpoch) && task.rerun);} finally {if (bootstrapTasks.get(deviceId) === task) bootstrapTasks.delete(deviceId);}@@ -544,6 +560,7 @@ export function useDeviceLinkRemoteProjects(disabledControl: disabledControlDeviceIds.has(d.deviceId),});if (action === 'ignore') return;+ cancelDeviceReseeds(d.deviceId);clearArchivedSessionRetry(d.deviceId);if (wasEligible) {window.electronAPI.deviceLink.unsubscribe(d.deviceId, ['sessions']).catch(() => {});@@ -594,6 +611,7 @@ export function useDeviceLinkRemoteProjects(if (isSharedTaskPeer(deviceId)) continue;if (authoritative.has(deviceId) || eligible.has(deviceId)) continue;log.debug(`removing cached shard absent from listDevices: ${deviceId.slice(0, 8)}`);+ cancelDeviceReseeds(deviceId);clearArchivedSessionRetry(deviceId);remoteProjectsStore.removeDevice(deviceId);removeRemoteSessionActivityForDevice(deviceId);@@ -631,7 +649,7 @@ export function useDeviceLinkRemoteProjects(setRemoteSessionBootstrapRetryImpl((deviceId) => {const name = eligible.get(deviceId);if (!name || disposed) return;- void subscribeAndBootstrap(deviceId, name);+ void subscribeAndBootstrap(deviceId, name, true);});// sessions:created / applyPatch 状态迁移 / 侧栏归档筛选 → 按设备+状态防抖重拉。@@ -706,9 +724,9 @@ export function useDeviceLinkRemoteProjects(if (disposed) return;responsivenessPushedDeviceIds.add(p.deviceId);unresponsiveDevicesStore.apply(p.deviceId, p.unresponsive);- if (!p.unresponsive) {+ if (!p.unresponsive && p.recovered !== false) {const name = eligible.get(p.deviceId);- if (name) void subscribeAndBootstrap(p.deviceId, name);+ if (name) void subscribeAndBootstrap(p.deviceId, name, true);}});@@ -720,7 +738,7 @@ export function useDeviceLinkRemoteProjects(// Presence can start bootstrap before this initial snapshot settles.// Reuse disconnect cleanup to clear loading and invalidate in-flight snapshots.if (!linkStatusPushSeen && !linkOnline) remoteProjectsStore.markAllDisconnected();- disabledControlDeviceIds = new Set(state.disabledControlDeviceIds ?? []);+ if (!controlTargetPushSeen) disabledControlDeviceIds = new Set(state.disabledControlDeviceIds ?? []);// 「无响应」熔断镜像的初值:按设备合并,已被 push 覆盖的设备以 push 为准// (store 初始为空,快照只需补写 unresponsive 的未覆盖设备)。for (const deviceId of state.unresponsiveDeviceIds ?? []) {@@ -805,8 +823,10 @@ export function useDeviceLinkRemoteProjects(const offControlTarget = window.electronAPI.deviceLink.onControlTargetChanged((p) => {if (disposed) return;+ controlTargetPushSeen = true;disabledControlDeviceIds = new Set(p.disabledControlDeviceIds ?? []);if (!p.enabled) {+ cancelDeviceReseeds(p.deviceId);clearArchivedSessionRetry(p.deviceId);const wasEligible = eligible.delete(p.deviceId);if (wasEligible) {diff --git a/apps/desktop/src/renderer/state/useRemoteModelFavorites.ts b/apps/desktop/src/renderer/state/useRemoteModelFavorites.tsindex 411e584b9b..359c533dfc 100644--- a/apps/desktop/src/renderer/state/useRemoteModelFavorites.ts+++ b/apps/desktop/src/renderer/state/useRemoteModelFavorites.ts@@ -63,7 +63,7 @@ export function useRemoteModelFavorites(deviceId?: string) {}});const offResponsive = api.onResponsivenessChanged?.((event) => {- if (event.deviceId === deviceId) {+ if (event.deviceId === deviceId && !event.unresponsive && event.recovered !== false) {void refresh();}});diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 55620b03ae..6c26fa9118 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3973,7 +3973,7 @@ interface ElectronAPI {onPeerLinkReset?: (cb: (payload: { deviceId: string }) => void) => () => void;/** 控制端:目标设备「无响应」熔断状态翻转(弱网 / 对端卡死;presence 可能仍在线) */onResponsivenessChanged: (- cb: (payload: { deviceId: string; unresponsive: boolean }) => void,+ cb: (payload: { deviceId: string; unresponsive: boolean; recovered?: boolean }) => void,) => () => void;/*** 控制端:远程会话镜像的本地冷缓存(main 落 userData,见diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex a23c880ff0..3f346fbe27 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -75,6 +75,11 @@ Desktop 和 Mobile 的按设备排队、并发上限、退避、取消代次由在线判断、Mobile 的后台生命周期与页面恢复仍由各端适配器负责。同一设备取消后重新请求恢复,须等待旧请求结算;旧结果不能取消新请求,也不能恢复已取消的重试。+Desktop 清理某设备的熔断状态不等于该设备已恢复。停用、离线和重置时只清理 UI+状态,不触发订阅重放或内容刷新;只有真实业务回包才触发恢复。排队中的订阅与列表+刷新同样受设备生命周期代次约束,迟到的失败不得重启已取消的恢复。周期对账复用在途+读取,新增内容等事件仍可合并成一次后续刷新;不得为了限制整轮等待而缩短弱网请求预算。+`packages/device-link/src/invokePolicy.ts` 集中维护请求策略,三个边界独立判断:- 通道执行预算:保留 Desktop / Mobile 的超时差异,超时不代表主机操作未执行。