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): clear breaker and coalesce concurrent timeouts
DavidShen425e10b93a41
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex 0be030bf62..feba57933b 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -26,6 +26,7 @@ vi.mock('../serverApiClient', () => {});vi.mock('./index', () => ({getDeviceLinkStatus: () => 'online',+ clearDeviceResponsiveness: vi.fn(),setRemoteControlEnabled: vi.fn(),openRemoteLink: vi.fn(),closeRemoteLink: vi.fn(),@@ -117,6 +118,7 @@ function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {revoke: vi.fn(),restore: vi.fn(),setDeviceControlEnabled: vi.fn(async () => []),+ clearDeviceResponsiveness: vi.fn(),broadcast: vi.fn(),readLastKnownDeviceNames: vi.fn(() => ({})),rememberLastKnownDeviceName: vi.fn(async () => false),@@ -207,6 +209,7 @@ describe('device-link IPC handlers', () => {disabledControlDeviceIds: ['dev-1'],});expect(deps.setDeviceControlEnabled).toHaveBeenCalledWith('dev-1', false);+ expect(deps.clearDeviceResponsiveness).toHaveBeenCalledWith('dev-1');expect(deps.closeLink).toHaveBeenCalledWith('dev-1');expect(deps.broadcast).toHaveBeenCalledWith('device-link:control-target-changed', {deviceId: 'dev-1',@@ -223,6 +226,7 @@ describe('device-link IPC handlers', () => {disabledControlDeviceIds: [],});expect(deps.closeLink).not.toHaveBeenCalled();+ expect(deps.clearDeviceResponsiveness).not.toHaveBeenCalled();await expect(handleSetDeviceControlEnabled(deps, '', true)).rejects.toThrowError(/\[INVALID_PARAMS\]/);await expect(handleSetDeviceControlEnabled(deps, 'dev-1', 'yes')).rejects.toThrowError(/\[INVALID_PARAMS\]/);});diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex 7adb59a6f8..769d9837f7 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -71,6 +71,7 @@ vi.mock('../../serverApiClient', () => ({vi.mock('../index', () => ({getDeviceLinkStatus: () => 'online',getDeviceLinkConnectionIssue: () => null,+ clearDeviceResponsiveness: vi.fn(),setRemoteControlEnabled: vi.fn(),setKeepAwakeEnabled: vi.fn(),openRemoteLink: vi.fn(),diff --git a/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts b/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.tsindex 41eeafe1d2..9a94965113 100644--- a/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts@@ -131,6 +131,23 @@ describe('responsivenessTracker', () => {expect(recoverLink).toHaveBeenCalledWith(DEV);});+ it('同一设备的并发超时共享 cohort,一次链路故障只计一次 strike', async () => {+ const h = harness();+ const requests = Array.from({ length: BREAKER_FAILURE_THRESHOLD }, () =>+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () => Promise.reject(timeoutError())),+ );+ await expect(Promise.all(requests)).rejects.toThrow('no invoke-result');+ expect(h.tracker.isUnresponsive(DEV)).toBe(false);++ await expect(+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () => Promise.reject(timeoutError())),+ ).rejects.toThrow();+ await expect(+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () => Promise.reject(timeoutError())),+ ).rejects.toThrow();+ expect(h.tracker.isUnresponsive(DEV)).toBe(true);+ });+it('探测窗口未到 / 前置条件不满足时 probeTick 不发探测;窗口到且合格才单飞', async () => {let eligible = false;const h = harness({ isProbeEligible: () => eligible });diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex e4d6f532cf..bef0284487 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -889,6 +889,11 @@ export function getUnresponsiveDeviceIds(): string[] {return responsivenessTracker?.getUnresponsiveDeviceIds() ?? [];}+/** 本机禁用目标设备控制时清除响应性熔断,避免重新启用后继承旧的 open 状态。 */+export function clearDeviceResponsiveness(deviceId: string): void {+ responsivenessTracker?.clearDevice(deviceId);+}+/*** 系统睡眠唤醒:立即重建连接而不是干等退避计时器(最坏 30s)+ 心跳判死(~45s)。* 状态仍是 online 也要重建 —— 睡眠期间 socket 大概率已半开假活(对端早没了,diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex dbd67d77de..6e4ade406f 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -26,6 +26,7 @@ import {getDeviceLinkStatus,getDeviceLinkConnectionIssue,getUnresponsiveDeviceIds,+ clearDeviceResponsiveness,setRemoteControlEnabled,setKeepAwakeEnabled,openRemoteLink,@@ -98,6 +99,8 @@ export interface DeviceLinkIpcDeps {revoke(deviceId: string): Promise<void>;restore(deviceId: string): Promise<void>;setDeviceControlEnabled(deviceId: string, enabled: boolean): Promise<string[]>;+ /** 清理本机禁用目标的响应性熔断状态。 */+ clearDeviceResponsiveness?(deviceId: string): void;broadcast(channel: string, payload: unknown): void;readLastKnownDeviceNames(): Record<string, string>;rememberLastKnownDeviceName(deviceId: string, name: string): Promise<boolean>;@@ -140,6 +143,7 @@ export function defaultDeps(): DeviceLinkIpcDeps {revoke: revokeController,restore: restoreController,setDeviceControlEnabled,+ clearDeviceResponsiveness,broadcast,readLastKnownDeviceNames,rememberLastKnownDeviceName,@@ -269,6 +273,7 @@ export async function handleSetDeviceControlEnabled(const disabledControlDeviceIds = await deps.setDeviceControlEnabled(normalizedDeviceId, enabled);if (!enabled) {resetSubscriptionRefcountForDevice(normalizedDeviceId);+ deps.clearDeviceResponsiveness?.(normalizedDeviceId);deps.closeLink(normalizedDeviceId);}deps.broadcast(DEVICE_LINK_PUSH.CONTROL_TARGET_CHANGED, {diff --git a/apps/desktop/src/main/device-link/responsivenessTracker.ts b/apps/desktop/src/main/device-link/responsivenessTracker.tsindex 4411a5a609..f2b9e52a11 100644--- a/apps/desktop/src/main/device-link/responsivenessTracker.ts+++ b/apps/desktop/src/main/device-link/responsivenessTracker.ts@@ -134,6 +134,8 @@ export function createResponsivenessTracker(const now = deps.now ?? Date.now;const unresponsive = new Set<string>();const linkRecoveryInFlight = new Map<string, Promise<unknown>>();+ /** 同一设备在途业务请求共享一个 timeout cohort,避免一次链路故障重复计 strike。 */+ const activeCohorts = new Map<string, { cohort: number; count: number }>();const breaker = createDeviceResponsivenessBreaker({now: deps.now,onOpenChanged: (deviceId, open) => {@@ -150,23 +152,12 @@ export function createResponsivenessTracker(breaker.settle(deviceId, slot, outcome);};- // 同一设备短时间窗内的并发请求共享一个熔断批次(cohort):renderer 的 fan-out- // 预取(capabilities / providers / git-safety 同 tick 并发)在一次短暂链路中断里- // 会同时超时,逐请求独立记账会让单轮并发直接凑满 3 次阈值误开熔断(review P2)。- // 窗口取 250ms:真实 fan-out 在同一事件循环 tick 或几十 ms 内发出,250ms 足够- // 覆盖;而用户手动发起的独立操作极少落进同一 250ms,不至于把独立超时误并- // (review P1 权衡)。更根本地,窗口内"独立"操作若同时超时,反映的也是同一- // 时刻的链路状态,证据价值与一次 fan-out 等同——阈值语义要的是时间上分离的- // 多次观察。窗口从批首请求起算,不滑动。- const COHORT_WINDOW_MS = 250;- const activeCohorts = new Map<string, { id: number; startedAt: number }>();- const cohortFor = (deviceId: string): number => {- const nowMs = now();- const entry = activeCohorts.get(deviceId);- if (entry && nowMs - entry.startedAt < COHORT_WINDOW_MS) return entry.id;- const id = breaker.createCohort(deviceId);- activeCohorts.set(deviceId, { id, startedAt: nowMs });- return id;+ const releaseCohort = (deviceId: string, slot: BreakerSendSlot): void => {+ if (slot.decision !== 'allow') return;+ const active = activeCohorts.get(deviceId);+ if (!active || active.cohort !== slot.cohort) return;+ if (active.count <= 1) activeCohorts.delete(deviceId);+ else active.count -= 1;};const guardInvoke = async <T>(@@ -174,16 +165,24 @@ export function createResponsivenessTracker(channel: string,run: () => Promise<T>,): Promise<T> => {- const slot = breaker.acquire(deviceId, cohortFor(deviceId));+ const cohort = activeCohorts.get(deviceId)?.cohort ?? breaker.createCohort(deviceId);+ const slot = breaker.acquire(deviceId, cohort);if (slot.decision === 'reject') throw createDeviceUnresponsiveError(deviceId);+ if (slot.decision === 'allow') {+ const current = activeCohorts.get(deviceId);+ if (current?.cohort === cohort) current.count += 1;+ else activeCohorts.set(deviceId, { cohort, count: 1 });+ }const wasProbe = slot.decision === 'probe';try {const result = await run();settle(deviceId, slot, classifyDeviceSendSuccess(channel, wasProbe));+ releaseCohort(deviceId, slot);return result;} catch (err) {const outcome = classifyDeviceSendFailure(err);settle(deviceId, slot, outcome);+ releaseCohort(deviceId, slot);if (outcome === 'timeout' && deps.recoverLink && !linkRecoveryInFlight.has(deviceId)) {let recovery: Promise<unknown>;try {diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 37bffe08fe..578a3d2b54 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -1643,6 +1643,18 @@ export class DeviceLinkClient {// 光靠沉默丢弃两边会互等(死锁的另一半)。节流通知 host,由控制端// 决定是否主动重新 link-open 让双方 stream 重新对齐。this.notifyReliableFrameBeforeLink(env.src);+ if (!peer.explicitlyClosed) {+ const now = Date.now();+ const last = this.staleLinkRepairAt.get(env.src) ?? 0;+ if (now - last >= 5_000) {+ this.staleLinkRepairAt.set(env.src, now);+ try {+ this.opts.onPeerLinkNeedsReopen?.(env.src);+ } catch (err) {+ this.log.debug(`peer link reopen callback failed for ${env.src.slice(0, 8)}`, err);+ }+ }+ }return { handled: true };}if (peer.remoteStreamId && peer.remoteStreamId !== parsed.meta.streamId) {