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): 弱网下收敛控制端请求风暴并显性化降级状态 (#1418)
Dash25d68a54fc9e
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex 6c8b966ebd..0be030bf62 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -103,6 +103,7 @@ function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],+ unresponsiveDeviceIds: [],}),setEnabled: vi.fn(),setKeepAwake: vi.fn(),@@ -138,6 +139,7 @@ describe('device-link IPC handlers', () => {controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],+ unresponsiveDeviceIds: [],});});@@ -157,6 +159,7 @@ describe('device-link IPC handlers', () => {controlledBy: [{ deviceId: 'controller-1', name: 'Other device' }],revokedControllers: ['revoked-1'],disabledControlDeviceIds: ['disabled-1'],+ unresponsiveDeviceIds: ['unresponsive-1'],}),});@@ -168,6 +171,7 @@ describe('device-link IPC handlers', () => {controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],+ unresponsiveDeviceIds: [],});});@@ -329,6 +333,7 @@ describe('device-link IPC handlers', () => {controlledBy: [],revokedControllers: [],disabledControlDeviceIds: ['dev-1'],+ unresponsiveDeviceIds: [],}),apiFetch: vi.fn().mockResolvedValue({devices: [@@ -424,6 +429,7 @@ describe('device-link controller handlers', () => {controlledBy: [],revokedControllers: [],disabledControlDeviceIds: ['dev-2'],+ unresponsiveDeviceIds: [],}),});@@ -528,6 +534,7 @@ describe('device-link controller handlers', () => {controlledBy: [],revokedControllers: [],disabledControlDeviceIds: disabled ? ['dev-2'] : [],+ unresponsiveDeviceIds: [],}),invoke,rewriteOutboundMedia: vi.fn().mockImplementation(async (_channel, args) => {diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 1b37661cbf..198af20889 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -297,7 +297,11 @@ import { initHeartbeatService } from './heartbeatService';import { initAnalyticsSettingsService, noteAuthColdStartState } from './analyticsSettingsService';import { WindowManualDragController } from './windowManualDrag';// 设备互联(跨设备远程控制): relay 连接 host + 开关/设备列表 IPC-import { initDeviceLinkService, releaseDeviceLinkOwnershipBeforeLogout } from './device-link';+import {+ initDeviceLinkService,+ releaseDeviceLinkOwnershipBeforeLogout,+ handleDeviceLinkSystemResume,+} from './device-link';import {getUpdateRelaunchControllers,hasInFlightRemoteInvokes,@@ -6269,6 +6273,8 @@ app.on('ready', async () => {powerMonitor.on('resume', () => {authManager.handleResume();handleProviderModelSystemResume();+ // device-link:睡醒立即重连 relay,不干等退避计时器 + 心跳判死(最坏合计 ~75s)。+ handleDeviceLinkSystemResume();});powerMonitor.on('unlock-screen', handleProviderModelScreenUnlock);diff --git a/apps/desktop/src/main/device-link/__tests__/dnsFallbackLookup.test.ts b/apps/desktop/src/main/device-link/__tests__/dnsFallbackLookup.test.tsnew file mode 100644index 0000000000..9d1be36011--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/dnsFallbackLookup.test.ts@@ -0,0 +1,131 @@+/**+ * DNS 回退层单测:成功缓存 / 失败回退 / 慢解析回退 / all 形态透传 / 单次回调。+ */+import { describe, it, expect, vi } from 'vitest';+import type dns from 'node:dns';+import { createDnsFallbackLookup, type DnsLookupFn } from '../dnsFallbackLookup';++type LookupCallback = (+ err: NodeJS.ErrnoException | null,+ address?: string | dns.LookupAddress[],+ family?: number,+) => void;++/** 可编程 lookup 桩:按调用顺序弹出预设行为。 */+function makeLookupStub(+ behaviors: Array<+ | { ok: string; family?: number; delayMs?: number }+ | { err: string }+ | { hang: true }+ >,+) {+ let calls = 0;+ const impl: DnsLookupFn = (_hostname, _options, callback) => {+ const behavior = behaviors[Math.min(calls, behaviors.length - 1)];+ calls++;+ const cb = callback as LookupCallback;+ if ('hang' in behavior) return;+ if ('err' in behavior) {+ const error = new Error(behavior.err) as NodeJS.ErrnoException;+ error.code = behavior.err;+ cb(error);+ return;+ }+ const respond = () => cb(null, behavior.ok, behavior.family ?? 4);+ if (behavior.delayMs) setTimeout(respond, behavior.delayMs);+ else respond();+ };+ return { impl, callCount: () => calls };+}++function lookupOnce(+ lookup: DnsLookupFn,+ hostname = 'relay.example',+ options: dns.LookupOptions = {},+): Promise<{ err: NodeJS.ErrnoException | null; address?: unknown; family?: number }> {+ return new Promise((resolve) => {+ lookup(hostname, options, (err, address, family) => resolve({ err, address, family }));+ });+}++describe('createDnsFallbackLookup', () => {+ it('成功解析透传结果;随后失败回退到缓存地址', async () => {+ const stub = makeLookupStub([{ ok: '1.2.3.4' }, { err: 'EAI_AGAIN' }]);+ const lookup = createDnsFallbackLookup({ lookupImpl: stub.impl });++ const first = await lookupOnce(lookup);+ expect(first.err).toBeNull();+ expect(first.address).toBe('1.2.3.4');++ const second = await lookupOnce(lookup);+ expect(second.err).toBeNull();+ expect(second.address).toBe('1.2.3.4'); // 回退缓存+ expect(second.family).toBe(4);+ });++ it('失败且无缓存 → 原样透传错误', async () => {+ const stub = makeLookupStub([{ err: 'ENOTFOUND' }]);+ const lookup = createDnsFallbackLookup({ lookupImpl: stub.impl });+ const result = await lookupOnce(lookup);+ expect(result.err?.code).toBe('ENOTFOUND');+ expect(result.address).toBeUndefined();+ });++ it('慢解析且有缓存 → slowFallbackMs 后先回缓存,迟到结果仍刷新缓存且不二次回调', async () => {+ vi.useFakeTimers();+ try {+ const stub = makeLookupStub([{ ok: '1.2.3.4' }, { ok: '5.6.7.8', delayMs: 500 }, { err: 'EAI_AGAIN' }]);+ const lookup = createDnsFallbackLookup({ lookupImpl: stub.impl, slowFallbackMs: 100 });++ await lookupOnce(lookup); // 灌缓存 1.2.3.4++ const callback = vi.fn();+ lookup('relay.example', {}, callback);+ await vi.advanceTimersByTimeAsync(100); // 触发慢回退+ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback).toHaveBeenCalledWith(null, '1.2.3.4', 4);++ await vi.advanceTimersByTimeAsync(500); // 真实结果 5.6.7.8 迟到+ expect(callback).toHaveBeenCalledTimes(1); // 不二次回调++ // 迟到结果已刷新缓存:下一次失败回退到 5.6.7.8+ const next = await lookupOnce(lookup);+ expect(next.address).toBe('5.6.7.8');+ } finally {+ vi.useRealTimers();+ }+ });++ it('慢解析但无缓存 → 不提前失败,等原生结果', async () => {+ vi.useFakeTimers();+ try {+ const stub = makeLookupStub([{ ok: '9.9.9.9', delayMs: 300 }]);+ const lookup = createDnsFallbackLookup({ lookupImpl: stub.impl, slowFallbackMs: 100 });+ const callback = vi.fn();+ lookup('relay.example', {}, callback);+ await vi.advanceTimersByTimeAsync(150);+ expect(callback).not.toHaveBeenCalled(); // 无缓存不介入+ await vi.advanceTimersByTimeAsync(200);+ expect(callback).toHaveBeenCalledWith(null, '9.9.9.9', 4);+ } finally {+ vi.useRealTimers();+ }+ });++ it('options.all 形态直接透传,不参与缓存回退', async () => {+ const stub = makeLookupStub([{ err: 'EAI_AGAIN' }]);+ const lookup = createDnsFallbackLookup({ lookupImpl: stub.impl });+ // 先灌一个非 all 的缓存也不该被 all 使用+ const result = await lookupOnce(lookup, 'relay.example', { all: true });+ expect(result.err?.code).toBe('EAI_AGAIN');+ });++ it('缓存按 hostname+family 隔离', async () => {+ const stub = makeLookupStub([{ ok: '1.2.3.4', family: 4 }, { err: 'EAI_AGAIN' }]);+ const lookup = createDnsFallbackLookup({ lookupImpl: stub.impl });+ await lookupOnce(lookup, 'relay.example', { family: 4 });+ // family 6 无缓存 → 错误透传,不误用 v4 缓存+ const v6 = await lookupOnce(lookup, 'relay.example', { family: 6 });+ expect(v6.err?.code).toBe('EAI_AGAIN');+ });+});diff --git a/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts b/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.tsnew file mode 100644index 0000000000..269aa81e8d--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/responsivenessTracker.test.ts@@ -0,0 +1,228 @@+/**+ * responsivenessTracker.test.ts —— 桌面控制端「目标设备无响应」熔断接线的行为锁。+ *+ * 状态机本体(阈值 / 退避 / 代数作废)在 maker-shared 的 deviceResponsiveness.test.ts;+ * 这里锁 main 接线层的语义:门禁快速失败、探测 tick 的单飞与前置条件、恢复回调、+ * 成功 / 失败分类(超时计失败、控制帧成功不定论、探测通道回包关熔断)。+ */+import { describe, expect, it, vi } from 'vitest';+import { DeviceLinkError } from '@cindy/device-link';+import {+ BREAKER_FAILURE_THRESHOLD,+ BREAKER_PROBE_BACKOFF_BASE_MS,+} from '@cindy/maker-shared/device-responsiveness';+import {+ DEVICE_RESPONSIVENESS_PROBE_CHANNEL,+ classifyDeviceSendFailure,+ classifyDeviceSendSuccess,+ createResponsivenessTracker,+} from '../responsivenessTracker';++const DEV = 'device-under-test';++function timeoutError(): DeviceLinkError {+ return new DeviceLinkError('INVOKE_TIMEOUT', 'no invoke-result within 12000ms');+}++function harness(overrides?: {+ probeInvoke?: ReturnType<typeof vi.fn>;+ isProbeEligible?: () => boolean;+}) {+ let at = 1_000_000;+ const probeInvoke = overrides?.probeInvoke ?? vi.fn(async () => [{ id: 's1' }]);+ const onUnresponsiveChanged = vi.fn();+ const tracker = createResponsivenessTracker({+ probeInvoke,+ onUnresponsiveChanged,+ isProbeEligible: overrides?.isProbeEligible ?? (() => true),+ now: () => at,+ });+ return {+ tracker,+ probeInvoke,+ onUnresponsiveChanged,+ advance: (ms: number) => {+ at += ms;+ },+ };+}++/** 连续 N 个超时批次把熔断打开(批次间推进时钟越过 1s 归批窗口,构成独立故障证据)。 */+async function openBreaker(h: ReturnType<typeof harness>): Promise<void> {+ for (let i = 0; i < BREAKER_FAILURE_THRESHOLD; i++) {+ await expect(+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () => Promise.reject(timeoutError())),+ ).rejects.toThrow('no invoke-result');+ h.advance(1_100);+ }+ expect(h.tracker.isUnresponsive(DEV)).toBe(true);+}++describe('responsivenessTracker', () => {+ it('成功请求直通,不改变状态', async () => {+ const h = harness();+ await expect(+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', async () => 'result'),+ ).resolves.toBe('result');+ expect(h.tracker.isUnresponsive(DEV)).toBe(false);+ expect(h.onUnresponsiveChanged).not.toHaveBeenCalled();+ });++ it('连续超时达到阈值 → open,通知 UI,后续请求快速失败且不再上管道', async () => {+ const h = harness();+ await openBreaker(h);+ expect(h.onUnresponsiveChanged).toHaveBeenCalledWith(DEV, true);+ expect(h.tracker.getUnresponsiveDeviceIds()).toEqual([DEV]);++ const run = vi.fn(async () => 'never');+ await expect(h.tracker.guardInvoke(DEV, 'local-db:sessions:list', run)).rejects.toThrow(+ 'unresponsive',+ );+ expect(run).not.toHaveBeenCalled();+ });++ it('同一 1s 窗口内的并发超时归入同一批次,单轮 fan-out 不会误开熔断', async () => {+ const h = harness();+ // 同 tick 并发 3 个请求(capabilities/providers/git-safety 预取形态)同时超时:+ // 只算一次独立故障证据,熔断保持关闭。+ await Promise.all(+ Array.from({ length: BREAKER_FAILURE_THRESHOLD }, () =>+ expect(+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () =>+ Promise.reject(timeoutError()),+ ),+ ).rejects.toThrow('no invoke-result'),+ ),+ );+ expect(h.tracker.isUnresponsive(DEV)).toBe(false);+ // 再来两个跨窗口的独立超时批次才凑满阈值。+ for (let i = 0; i < BREAKER_FAILURE_THRESHOLD - 1; i++) {+ h.advance(1_100);+ await expect(+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () => Promise.reject(timeoutError())),+ ).rejects.toThrow('no invoke-result');+ }+ expect(h.tracker.isUnresponsive(DEV)).toBe(true);+ });++ it('非超时失败(NOT_CONNECTED 等)不定论,不累计熔断', async () => {+ const h = harness();+ for (let i = 0; i < BREAKER_FAILURE_THRESHOLD + 1; i++) {+ await expect(+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () =>+ Promise.reject(new DeviceLinkError('NOT_CONNECTED', 'relay connection lost')),+ ),+ ).rejects.toThrow('relay connection lost');+ }+ expect(h.tracker.isUnresponsive(DEV)).toBe(false);+ });++ it('探测窗口未到 / 前置条件不满足时 probeTick 不发探测;窗口到且合格才单飞', async () => {+ let eligible = false;+ const h = harness({ isProbeEligible: () => eligible });+ await openBreaker(h);++ h.tracker.probeTick(); // 窗口未到+ expect(h.probeInvoke).not.toHaveBeenCalled();++ h.advance(BREAKER_PROBE_BACKOFF_BASE_MS);+ h.tracker.probeTick(); // 窗口已到但不合格(relay 掉线 / presence 不可用)+ expect(h.probeInvoke).not.toHaveBeenCalled();++ eligible = true;+ let resolveProbe!: (v: unknown) => void;+ h.probeInvoke.mockImplementationOnce(+ () => new Promise((res) => {+ resolveProbe = res;+ }),+ );+ h.tracker.probeTick();+ expect(h.probeInvoke).toHaveBeenCalledTimes(1);+ expect(h.probeInvoke).toHaveBeenCalledWith(+ DEV,+ DEVICE_RESPONSIVENESS_PROBE_CHANNEL,+ [1, 'all', { includePinned: true }],+ );+ // 在途探测占住单飞席位:再 tick 不重复发+ h.tracker.probeTick();+ expect(h.probeInvoke).toHaveBeenCalledTimes(1);++ resolveProbe([]);+ await vi.waitFor(() => {+ expect(h.tracker.isUnresponsive(DEV)).toBe(false);+ });+ expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false);+ });++ it('探测超时 → 保持 open 并加深退避(下个基础窗口不再探测)', async () => {+ const h = harness();+ await openBreaker(h);+ h.advance(BREAKER_PROBE_BACKOFF_BASE_MS);+ h.probeInvoke.mockRejectedValueOnce(timeoutError());+ h.tracker.probeTick();+ await vi.waitFor(() => {+ expect(h.probeInvoke).toHaveBeenCalledTimes(1);+ });+ expect(h.tracker.isUnresponsive(DEV)).toBe(true);++ h.advance(BREAKER_PROBE_BACKOFF_BASE_MS); // 退避已 ×2,一个基础窗口不够+ h.tracker.probeTick();+ expect(h.probeInvoke).toHaveBeenCalledTimes(1);+ h.advance(BREAKER_PROBE_BACKOFF_BASE_MS);+ h.tracker.probeTick();+ expect(h.probeInvoke).toHaveBeenCalledTimes(2);+ });++ it('clearDevice 作废在途请求的晚到超时:清除后旧超时不得重建计数', async () => {+ const h = harness();+ let rejectSlow!: (err: unknown) => void;+ const slow = h.tracker.guardInvoke(+ DEV,+ 'local-db:sessions:list',+ () =>+ new Promise((_res, rej) => {+ rejectSlow = rej;+ }),+ );+ h.tracker.clearDevice(DEV);+ rejectSlow(timeoutError());+ await expect(slow).rejects.toThrow('no invoke-result');+ // 旧代结果被忽略:后续仍需完整阈值才会 open+ for (let i = 0; i < BREAKER_FAILURE_THRESHOLD - 1; i++) {+ await expect(+ h.tracker.guardInvoke(DEV, 'local-db:sessions:list', () => Promise.reject(timeoutError())),+ ).rejects.toThrow();+ }+ expect(h.tracker.isUnresponsive(DEV)).toBe(false);+ });++ it('resetAll 关闭所有 open 设备并通知恢复', async () => {+ const h = harness();+ await openBreaker(h);+ h.tracker.resetAll();+ expect(h.tracker.getUnresponsiveDeviceIds()).toEqual([]);+ expect(h.onUnresponsiveChanged).toHaveBeenLastCalledWith(DEV, false);+ });+});++describe('classifyDeviceSendFailure / classifyDeviceSendSuccess', () => {+ it('仅 INVOKE_TIMEOUT 计失败,其余不定论', () => {+ expect(classifyDeviceSendFailure(timeoutError())).toBe('timeout');+ expect(+ classifyDeviceSendFailure(new DeviceLinkError('NOT_CONNECTED', 'lost')),+ ).toBe('inconclusive');+ expect(classifyDeviceSendFailure(new Error('random'))).toBe('inconclusive');+ });++ it('控制帧 / dispatch 特判通道的成功不定论;业务 DB 通道的成功是恢复证据', () => {+ expect(classifyDeviceSendSuccess('device-link:subscribe')).toBe('inconclusive');+ expect(classifyDeviceSendSuccess('device-link:media:fetch')).toBe('inconclusive');+ expect(classifyDeviceSendSuccess('local-db:sessions:list')).toBe('responded');+ expect(classifyDeviceSendSuccess('maker:send')).toBe('responded');+ });++ it('持有探测席位时只有探测通道的回包算恢复', () => {+ expect(classifyDeviceSendSuccess('maker:list-agent-commands', true)).toBe('inconclusive');+ expect(classifyDeviceSendSuccess(DEVICE_RESPONSIVENESS_PROBE_CHANNEL, true)).toBe('responded');+ });+});diff --git a/apps/desktop/src/main/device-link/dnsFallbackLookup.ts b/apps/desktop/src/main/device-link/dnsFallbackLookup.tsnew file mode 100644index 0000000000..79c656fc4a--- /dev/null+++ b/apps/desktop/src/main/device-link/dnsFallbackLookup.ts@@ -0,0 +1,106 @@+/**+ * device-link relay 建连的 DNS 回退层。+ *+ * 弱网(尤其 VPN 接管 DNS)下 getaddrinfo 可能直接失败或挂起数秒,把 15s 握手+ * 窗口整段吃掉(2026-08-02/03 实测:DNS 单段 5s 超时,relay 握手连续 25 分钟+ * 全部失败)。而 relay 域名的解析结果在一次会话内基本稳定,所以:+ *+ * - 每次成功解析都刷新 host(+family)→ 地址 的内存缓存(不落盘);+ * - 解析**失败**且有缓存 → 回退最近成功地址。stale-ok:地址若已轮换,后果只是+ * TCP/TLS 连接失败走既有退避,与没有缓存时相同,不会更糟;+ * - 解析**超过 slowFallbackMs** 且有缓存 → 先用缓存建连,不等原生结果;原生+ * 结果迟到后仍刷新缓存,供下一轮使用;+ * - `options.all`(多地址形态,net 直连不走)与「无缓存的慢解析」不介入,+ * 保持原生行为。+ *+ * 只挂在 device-link 的 WebSocket 工厂上(代理模式下由代理解析域名,本层自然+ * 旁路),不影响 auth / heartbeat 等 HTTP 链路。+ */+import dns from 'node:dns';++type LookupCallback = (+ err: NodeJS.ErrnoException | null,+ address?: string | dns.LookupAddress[],+ family?: number,+) => void;++/** net/tls 的 lookup 注入点形态(net 总是传 options 对象;宽容函数形态以防万一)。 */+export type DnsLookupFn = (+ hostname: string,+ options: dns.LookupOptions | LookupCallback,+ callback?: LookupCallback,+) => void;++export interface DnsFallbackLookupOptions {+ /** 测试注入;默认 node:dns 的 lookup。 */+ lookupImpl?: DnsLookupFn;+ /** 原生解析超过该时长且有缓存时,先用缓存建连。 */+ slowFallbackMs?: number;+ log?: {+ info(...args: unknown[]): void;+ warn(...args: unknown[]): void;+ };+}++export const DNS_SLOW_FALLBACK_MS = 4_000;++interface CachedAddress {+ address: string;+ family: number;+}++export function createDnsFallbackLookup(opts: DnsFallbackLookupOptions = {}): DnsLookupFn {+ const lookupImpl: DnsLookupFn = opts.lookupImpl ?? (dns.lookup as unknown as DnsLookupFn);+ const slowFallbackMs = opts.slowFallbackMs ?? DNS_SLOW_FALLBACK_MS;+ const log = opts.log;+ const cache = new Map<string, CachedAddress>();++ return (hostname, optionsOrCb, maybeCb) => {+ const options: dns.LookupOptions = typeof optionsOrCb === 'function' ? {} : optionsOrCb;+ const callback = (typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb) as LookupCallback;++ // all 形态(回调收数组)极少出现在 socket 建连路径;不缓存、不回退,原样透传。+ if (options.all) {+ lookupImpl(hostname, options, callback);+ return;+ }++ const cacheKey = `${hostname}|${options.family ?? 0}`;+ const cached = cache.get(cacheKey);+ let settled = false;++ const settle = (err: NodeJS.ErrnoException | null, address?: string, family?: number): void => {+ if (settled) return;+ settled = true;+ if (slowTimer) clearTimeout(slowTimer);+ callback(err, address, family);+ };++ // 有缓存才 arm 慢解析回退:无缓存时提前失败只会更糟,等原生结果。+ const slowTimer = cached+ ? setTimeout(() => {+ log?.warn(+ `DNS lookup slow (>${slowFallbackMs}ms) for ${hostname}; using cached ${cached.address}`,+ );+ settle(null, cached.address, cached.family);+ }, slowFallbackMs)+ : null;+ (slowTimer as unknown as { unref?: () => void } | null)?.unref?.();++ lookupImpl(hostname, options, (err, address, family) => {+ // 迟到的原生结果(慢回退已建连)仍然刷新缓存,供下一轮使用。+ if (!err && typeof address === 'string' && address) {+ cache.set(cacheKey, { address, family: typeof family === 'number' ? family : 4 });+ }+ if (settled) return;+ if (err && cached) {+ log?.warn(+ `DNS lookup failed for ${hostname} (${err.code ?? err.message}); falling back to cached ${cached.address}`,+ );+ settle(null, cached.address, cached.family);+ return;+ }+ settle(err, typeof address === 'string' ? address : undefined, family);+ });+ };+}diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex e4ad5be179..3cc29c801b 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -54,6 +54,7 @@ import {writeDeviceLinkSetting,} from './settings-store';import { keepAwakeController } from './power-blocker';+import { createDnsFallbackLookup } from './dnsFallbackLookup';import {wireInboundDispatch,setControllersChangedListener,@@ -96,11 +97,17 @@ import {invokeWithClosedLinkRecovery,requiresSessionLink,} from './linkRecovery';+import {+ createResponsivenessTracker,+ type DeviceResponsivenessTracker,+} from './responsivenessTracker';// register.ts 从 device-link/index 导入 setBusyProbe;改用 busyReporter 后在此 re-export 保持其导入不变。export { setBusyProbe };const log = createLogger('device-link');+// relay 建连专用的 DNS 回退(成功缓存 / 失败与慢解析回退最近成功地址)。+const relayDnsLookup = createDnsFallbackLookup({ log });// device-link 独立部署后的 relay 地址:走运行期端点清单(烘焙值已含 dev fallback// localhost:3335)。惰性函数而非模块级常量——远程清单在 app.ready 内解析。@@ -164,6 +171,14 @@ let appliedKeepAwake: boolean | null = null;let pendingQuitOwnershipRelease: Promise<void> | null = null;const openLinkInFlight = new Map<string, Promise<LinkAcceptPayload>>();const presenceAvailableByDevice = new Map<string, boolean>();+/**+ * 「目标设备无响应」熔断(弱网 / 对端卡死时收敛请求风暴,见 responsivenessTracker)。+ * 随 initDeviceLinkService 创建;null(极早期)时门禁直通,不影响行为。+ */+let responsivenessTracker: DeviceResponsivenessTracker | null = null;+/** 熔断探测的周期 tick(单飞探测由 tracker 内部的退避窗口控制,这里只是驱动时钟)。 */+let responsivenessProbeTimer: ReturnType<typeof setInterval> | null = null;+const RESPONSIVENESS_PROBE_TICK_MS = 5_000;/*** 词典同步的对端选择只看「在线 + 是桌面」,不看 remoteControlEnabled ——* push 帧不属于 relay 的控制类帧,自己设备之间同步词典不该要求对方开放被控。@@ -306,15 +321,62 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v}),// agent:`ws` 不吃系统代理,relay 在代理网络下会连不上;直连时为 undefined,// 行为与不传一致(见 maker-host/outbound-fetch)。+ // lookup:DNS 失败/慢解析时回退最近成功地址(弱网 VPN 下 DNS 单段可吃掉+ // 大半个握手窗口);代理模式下由代理解析域名,本层自然旁路。createWebSocket: async (url, headers) =>- new WebSocket(url, { headers, agent: await createOutboundHttpAgent(url) }),+ new WebSocket(url, {+ headers,+ agent: await createOutboundHttpAgent(url),+ // ClientOptions 类型未声明 lookup,但 ws 会把额外选项透传给+ // http.request(其 RequestOptions 原生支持 lookup)→ net/tls 建连。+ lookup: relayDnsLookup,+ } as WebSocket.ClientOptions),logger: {debug: (...args) => log.debug(...args),info: (...args) => log.info(...args),warn: (...args) => log.warn(...args),error: (...args) => log.error(...args),},+ // 弱网收紧:默认 20s ping × (2+1) tick 要 ~60s 才判死半开连接,期间所有请求黑洞。+ // 15s ping 把判死缩到 ~45s;不动 pongMissLimit——高延迟链路(实测响应性可达 ~10s)+ // 下更激进的宽限会把「慢但活着」误判成死链,造成重连循环(mobile 用 10s×1 是因为+ // 手机端 TCP 半开假活远比桌面常见,桌面不照搬)。+ timing: { pingIntervalMs: 15_000 },+ });++ responsivenessTracker = createResponsivenessTracker({+ // 探测直接走 client.invoke(guardInvoke 已在 tracker 内持有探测席位,不能再套+ // remoteInvoke 的外层门禁,否则自旋)。sessions:list 属 UNLINKED legacy 通道,无需 link。+ probeInvoke: (deviceId, channel, args) => {+ if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');+ return client.invoke(deviceId, { channel, args }, INVOKE_TIMEOUT_OVERRIDES_MS[channel]);+ },+ onUnresponsiveChanged: (deviceId, unresponsive) => {+ broadcast(DEVICE_LINK_PUSH.RESPONSIVENESS_CHANGED, { deviceId, unresponsive });+ // 恢复时主动重放该设备的订阅:熔断 open 期间 subscribe 都被快速失败挡掉了,+ // 不重放的话 push 驱动的列表 / 会话镜像会一直缺流,直到用户手动重试。+ // linkTornDown 闸:teardown 的 resetAll 也会触发本回调,那时不能再发订阅。+ if (!unresponsive && !linkTornDown && client?.getStatus() === 'online') {+ replayActiveSubscriptions(`responsiveness-recovered:${deviceId.slice(0, 8)}`, deviceId);+ }+ },+ // 探测同样遵守本机「关闭对该设备的控制」的 fail-closed 偏好,不给禁用目标发任何帧。+ isProbeEligible: (deviceId) =>+ client?.getStatus() === 'online' &&+ arbiter?.isOwner() === true &&+ presenceAvailableByDevice.get(deviceId) === true &&+ !readDeviceLinkSettings().disabledControlDeviceIds.includes(deviceId),+ log: {+ info: (...args) => log.info(...args),+ warn: (...args) => log.warn(...args),+ debug: (...args) => log.debug(...args),+ },});+ if (responsivenessProbeTimer) clearInterval(responsivenessProbeTimer);+ responsivenessProbeTimer = setInterval(() => {+ responsivenessTracker?.probeTick();+ }, RESPONSIVENESS_PROBE_TICK_MS);+ responsivenessProbeTimer.unref();client.onStatusChange((status) => {if (status !== 'online') {@@ -342,12 +404,27 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v// 鉴权失效不能只在设置页可见:主动 refresh,把「被顶下线」汇入全局会话过期出口。if (issue?.kind === 'auth-failed') recoverFromRelayAuthFailure();});+ // 死锁自愈(控制端半):对端还在按可靠流给本机发帧,但本机侧 link 未就绪 ——+ // 沉默丢弃会让两边互等(发送端等 ACK、接收端等 link)。只对本机确实在控制+ // (有活跃订阅)的设备主动重建链路;client 侧已 30s/peer 节流,openRemoteLink+ // 自带 in-flight 去重。被控端方向(控制端给本机发帧)没有订阅记录,自然忽略。+ client.onReliableFrameBeforeLink((deviceId) => {+ if (snapshotSubscriptions(deviceId).length === 0) return;+ if (readDeviceLinkSettings().disabledControlDeviceIds.includes(deviceId)) return;+ log.info(`re-opening control link for ${deviceId.slice(0, 8)} after before-link reliable frame`);+ openRemoteLink(deviceId).catch((err) => {+ log.debug(`re-open link for ${deviceId.slice(0, 8)} failed`, err);+ });+ });client.onPresenceChanged((snap: PresenceSnapshot) => {const wasAvailable = presenceAvailableByDevice.get(snap.deviceId);const available = snap.online && snap.remoteControlEnabled;const wasOnline = presenceOnlineByDevice.get(snap.deviceId);presenceAvailableByDevice.set(snap.deviceId, available);presenceOnlineByDevice.set(snap.deviceId, snap.online);+ // 权威 presence 已宣布不可用(离线 / 关被控):「响应性」判定失去意义,清熔断状态+ // 并作废在途结果,让离线态自己的 UI 接管;设备回来后首个请求再超时会重新累计。+ if (!available && wasAvailable === true) responsivenessTracker?.clearDevice(snap.deviceId);presencePlatformByDevice.set(snap.deviceId, snap.platform);presenceNameByDevice.set(snap.deviceId, snap.selfName || snap.deviceName);void rememberLastKnownDeviceName(snap.deviceId, snap.deviceName); // best-effort 名称缓存,不阻塞 presence 处理@@ -411,6 +488,9 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v// 循环,否则刚被断开的控制链会被退避重试重新建起。routeLinkCloseForReopen(reason, transportTimeoutReopen, env.src);if (reason === 'revoked') {+ // 撤权后在途请求会陆续超时——那不是「设备无响应」,是访问被收回。清熔断并+ // 作废在途结果(翻代),避免 unresponsive 状态与撤权状态并存(对齐 mobile 语义)。+ responsivenessTracker?.clearDevice(env.src);broadcast(DEVICE_LINK_PUSH.ACCESS_REVOKED, { deviceId: env.src });}return;@@ -560,6 +640,10 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vclearInterval(busyTimer);busyTimer = null;}+ if (responsivenessProbeTimer) {+ clearInterval(responsivenessProbeTimer);+ responsivenessProbeTimer = null;+ }// 先释放持有权(删行),幸存实例在下一轮 tick 内接管,无需等心跳过期。// sync 阶段只发起 DELETE(RPC 已入 worker 队列),真正的落盘等待交给下面// async 阶段的 disposer —— sync 阶段不 await,直接退出会与 DbClient@@ -691,6 +775,10 @@ function teardownActiveLink(): void {relayAuthRecoveryRetryTimer = null;}dropAllControllers(client, 'shutdown');+ // 熔断状态是账号 / 链路作用域的:登出或失去持有权后全部翻篇,不串到下一段链路。+ responsivenessTracker?.resetAll();+ for (const timer of subscriptionReplayRetryTimers.values()) clearTimeout(timer);+ subscriptionReplayRetryTimers.clear();presenceAvailableByDevice.clear();// 词典同步驱动是进程级的,**不随单次链路起停**:多实例仲裁的 demote → acquire// 只会 client.start(),不会重跑 initDeviceLinkService,在这里 stop 掉它会让词典@@ -712,18 +800,81 @@ function replayActiveSubscriptions(reason: string, deviceId?: string): void {`device-link replay subscriptions (${reason}): devices=${refs.length} topics=${topicCount}`,);for (const { deviceId, topics } of refs) {- void remoteSubscribe(deviceId, topics).catch((err) => {+ replayDeviceSubscription(deviceId, topics, reason, 0);+ }+}++/**+ * 重放失败的有限重试(弱网修复,2026-08):重连后的 subscribe 若恰好赶上链路抖动+ * 失败,此前只留一行 warn —— push 流静默缺失,直到下一次重连或用户手动操作。+ * 每设备最多补 2 次(3s / 9s),重试前重新校验前置条件并取当前订阅快照;熔断 open+ * 的设备不重试(恢复时 tracker 自会触发一次定向重放)。+ */+const SUBSCRIPTION_REPLAY_RETRY_DELAYS_MS = [3_000, 9_000] as const;+const subscriptionReplayRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();++function replayDeviceSubscription(+ deviceId: string,+ topics: string[],+ reason: string,+ attempt: number,+): void {+ // 新一轮重放顶掉该设备挂起的重试,避免多路触发(ws-online / presence / 熔断恢复)叠加。+ const prev = subscriptionReplayRetryTimers.get(deviceId);+ if (prev) {+ clearTimeout(prev);+ subscriptionReplayRetryTimers.delete(deviceId);+ }+ void remoteSubscribe(deviceId, topics).catch((err) => {+ const delay = SUBSCRIPTION_REPLAY_RETRY_DELAYS_MS[attempt];+ if (delay === undefined) {log.warn(- `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}: ${String(err)}`,+ `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, giving up: ${String(err)}`,);- });- }+ return;+ }+ log.warn(+ `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, retrying in ${delay}ms: ${String(err)}`,+ );+ const timer = setTimeout(() => {+ subscriptionReplayRetryTimers.delete(deviceId);+ if (linkTornDown || client?.getStatus() !== 'online') return;+ if (responsivenessTracker?.isUnresponsive(deviceId)) return;+ if (presenceAvailableByDevice.get(deviceId) !== true) return;+ // 快照可能已变(窗口退订 / 新增 topic):按该设备当前的订阅快照重放。+ const current = snapshotSubscriptions(deviceId).find((ref) => ref.deviceId === deviceId);+ if (!current || current.topics.length === 0) return;+ replayDeviceSubscription(deviceId, current.topics, `${reason}-retry`, attempt + 1);+ }, delay);+ timer.unref?.();+ subscriptionReplayRetryTimers.set(deviceId, timer);+ });}export function getDeviceLinkStatus(): DeviceLinkStatus {return client?.getStatus() ?? 'stopped';}+/** 当前被熔断判定为「无响应」的目标设备(控制端本地判定,供 getState / UI 镜像)。 */+export function getUnresponsiveDeviceIds(): string[] {+ return responsivenessTracker?.getUnresponsiveDeviceIds() ?? [];+}++/**+ * 系统睡眠唤醒:立即重建连接而不是干等退避计时器(最坏 30s)+ 心跳判死(~45s)。+ * 状态仍是 online 也要重建 —— 睡眠期间 socket 大概率已半开假活(对端早没了,+ * 本端没收到 close、心跳未累计到判死),此时只解除退避救不了半开黑洞+ * (review P1/P2:connectNow 对 online 是空操作)。restartConnection 对 stopped+ * client 不拉起,但持有权 / 登录双闸仍在前面,不绕过仲裁。+ */+export function handleDeviceLinkSystemResume(): void {+ if (!client || linkTornDown) return;+ if (arbiter && !arbiter.isOwner()) return;+ if (!authManager.getAuthState().isAuthenticated) return;+ log.info('system resume: rebuilding device-link connection immediately');+ client.restartConnection('system-resume');+}+export function getDeviceLinkConnectionIssue(): DeviceLinkConnectionIssue | null {return client?.getConnectionIssue() ?? null;}@@ -988,12 +1139,17 @@ export async function remoteInvoke(if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');return client.invoke(deviceId, { channel, args }, INVOKE_TIMEOUT_OVERRIDES_MS[channel]);};- return invokeWithClosedLinkRecovery(- invoke,- () => openRemoteLink(deviceId),- () => assertRemoteControlTargetEnabled(deviceId),- () => closeRemoteLink(deviceId),- );+ const run = (): Promise<InvokeResultPayload> =>+ invokeWithClosedLinkRecovery(+ invoke,+ () => openRemoteLink(deviceId),+ () => assertRemoteControlTargetEnabled(deviceId),+ () => closeRemoteLink(deviceId),+ );+ // 熔断门禁:目标设备连续超时判定无响应后,新请求立即以 DEVICE_UNRESPONSIVE 快速失败+ // (不占管道、不等 12~30s 超时),恢复由周期单飞探测驱动。tracker 未初始化时直通。+ if (!responsivenessTracker) return run();+ return responsivenessTracker.guardInvoke(deviceId, channel, run);}/**@@ -1007,21 +1163,28 @@ export async function remoteSubscribe(assertNotStandby();assertRemoteControlTargetEnabled(deviceId);if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');- if (requiresSessionLink(topics) && !client.isLinkReady(deviceId)) {- await openRemoteLink(deviceId);- }- assertRemoteControlTargetEnabledAfterReopen(deviceId);- if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');- return client.invoke(deviceId, {- channel: DL_SUBSCRIBE_CHANNEL,- args: [- {- topics,- controllerName: deviceName(),- capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],- },- ],- });+ const run = async (): Promise<InvokeResultPayload> => {+ if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');+ if (requiresSessionLink(topics) && !client.isLinkReady(deviceId)) {+ await openRemoteLink(deviceId);+ }+ assertRemoteControlTargetEnabledAfterReopen(deviceId);+ if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');+ return client.invoke(deviceId, {+ channel: DL_SUBSCRIBE_CHANNEL,+ args: [+ {+ topics,+ controllerName: deviceName(),+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],+ },+ ],+ });+ };+ // 同一张熔断门禁盖住「重开 link + subscribe」整段(单席位,内部 openLink 的失败不+ // 重复计 strike):设备无响应期间 bootstrap 快速失败,恢复后由 tracker 重放订阅。+ if (!responsivenessTracker) return run();+ return responsivenessTracker.guardInvoke(deviceId, DL_SUBSCRIBE_CHANNEL, run);}/** 控制端:取消订阅被控端某 topic。 */diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex b6a19add69..dbd67d77de 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -25,6 +25,7 @@ import {import {getDeviceLinkStatus,getDeviceLinkConnectionIssue,+ getUnresponsiveDeviceIds,setRemoteControlEnabled,setKeepAwakeEnabled,openRemoteLink,@@ -121,6 +122,7 @@ export function defaultDeps(): DeviceLinkIpcDeps {controlledBy: getActiveControllers(),revokedControllers: s.revokedControllers,disabledControlDeviceIds: s.disabledControlDeviceIds,+ unresponsiveDeviceIds: getUnresponsiveDeviceIds(),};},setEnabled: setRemoteControlEnabled,@@ -153,6 +155,7 @@ const DEVICE_LINK_CODE_MAP: Record<string, IpcErrorCode> = {CHANNEL_NOT_ALLOWED: 'DEVICE_LINK_CHANNEL_NOT_ALLOWED',ACCESS_REVOKED: 'DEVICE_LINK_ACCESS_REVOKED',INVOKE_TIMEOUT: 'DEVICE_LINK_TIMEOUT',+ DEVICE_UNRESPONSIVE: 'DEVICE_LINK_DEVICE_UNRESPONSIVE',VERSION_MISMATCH: 'DEVICE_LINK_VERSION_MISMATCH',NOT_CONNECTED: 'DEVICE_LINK_NOT_CONNECTED',LINK_NOT_OPEN: 'DEVICE_LINK_NOT_CONNECTED',@@ -225,6 +228,7 @@ export function handleGetState(deps: DeviceLinkIpcDeps): DeviceLinkState {controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],+ unresponsiveDeviceIds: [],};}diff --git a/apps/desktop/src/main/device-link/responsivenessTracker.ts b/apps/desktop/src/main/device-link/responsivenessTracker.tsnew file mode 100644index 0000000000..2d2660d1f9--- /dev/null+++ b/apps/desktop/src/main/device-link/responsivenessTracker.ts@@ -0,0 +1,218 @@+/**+ * responsivenessTracker.ts — 桌面控制端「目标设备无响应」熔断的 main 侧接线(可注入依赖,免 Electron 单测)。+ * ---------------------------------------------------------------------------+ * 状态机本体在 @cindy/maker-shared/device-responsiveness(与 mobile 控制端共享):+ * 连续 INVOKE_TIMEOUT 熔断 → 新请求快速失败(DEVICE_UNRESPONSIVE)→ 周期单飞探测+ * (10s 起 ×2 封顶 120s)→ 真实回包自动恢复。+ *+ * 弱网背景(2026-08 实测):控制端 10s 周期对账 + 超时重试链在链路劣化时把请求堆成+ * 风暴(单日 2253 次 sessions:list 等满 30s 超时),而 UI 因 presence 仍在线毫无感知。+ * 门禁收口在 main 的 remoteInvoke / remoteSubscribe:单实例覆盖所有窗口,且能直接+ * 看到原始 DeviceLinkError 码(renderer 只能拿到映射后的 IPC 码)。+ *+ * 与 mobile 接线的一处刻意差异:探测由 main 的周期 tick 主动驱动(probeTick),不依赖+ * 业务流量被动触发——桌面控制端的 reconciler 在熔断 open 时会快速失败,不再产生+ * 可借用的探测流量。+ */+import {+ createDeviceResponsivenessBreaker,+ type BreakerSendSlot,+ type BreakerSettleOutcome,+} from '@cindy/maker-shared/device-responsiveness';+import {+ DeviceLinkError,+ DL_SUBSCRIBE_CHANNEL,+ DL_UNSUBSCRIBE_CHANNEL,+ type DeviceLinkErrorCode,+} from '@cindy/device-link';++/**+ * DEVICE_UNRESPONSIVE 尚未收编进 @cindy/device-link 的 DeviceLinkErrorCode 联合+ * (与 mobile 同一口径:零接触共享协议包)。下游分类按字符串匹配(maker-shared 的+ * PERMANENT_REMOTE_ERROR_MARKERS / renderer 的 isTransientRemoteError),不依赖联合类型。+ */+export const DEVICE_UNRESPONSIVE_ERROR_CODE = 'DEVICE_UNRESPONSIVE';++export function createDeviceUnresponsiveError(deviceId: string): DeviceLinkError {+ return new DeviceLinkError(+ DEVICE_UNRESPONSIVE_ERROR_CODE as DeviceLinkErrorCode,+ `target device ${deviceId} is unresponsive (circuit open)`,+ );+}++/**+ * 代表性探测请求:half-open 探测必须穿过被控端 runInvoke → dispatchLocalInvoke →+ * local-db 读路径才算数(subscribe / unsubscribe / link-accept 在被控端 dispatch 里+ * 于 runInvoke 之前特判应答,IPC/DB 卡死时它们照常回包,不能作恢复证据)。+ * sessions:list limit=1 是最便宜的真实 DB 读;与 mobile 的探测通道一致。+ */+export const DEVICE_RESPONSIVENESS_PROBE_CHANNEL = 'local-db:sessions:list';++export function buildDeviceResponsivenessProbeArgs(): unknown[] {+ return [1, 'all', { includePinned: true }];+}++/**+ * 被控端 dispatch 在进入 dispatchLocalInvoke(IPC/DB 路径)之前特判应答的通道:+ * 它们的成功只证明对端进程与 device-link 服务活着,不证明 IPC/DB 子系统健康,+ * 统一按不定论收尾(与 mobile 同语义;desktop 额外把 subscribe / unsubscribe 也+ * 列入——它们同样是 pre-runInvoke 特判应答的控制帧)。超时分类不受影响。+ */+export const BREAKER_NEUTRAL_INVOKE_CHANNELS: ReadonlySet<string> = new Set([+ 'device-link:media:fetch',+ 'device-link:voice:credential-sync',+ 'device-link:voice:dictionary-learning',+ 'device-link:voice:transcribe',+ DL_SUBSCRIBE_CHANNEL,+ DL_UNSUBSCRIBE_CHANNEL,+]);++/**+ * 失败 → 熔断信号:仅 INVOKE_TIMEOUT(等满超时无回包)计失败;NOT_CONNECTED /+ * relay 层错误 / 发送前本地中止是本机链路问题,不定论。纯函数,便于单测。+ */+export function classifyDeviceSendFailure(error: unknown): BreakerSettleOutcome {+ return error instanceof DeviceLinkError && error.code === 'INVOKE_TIMEOUT'+ ? 'timeout'+ : 'inconclusive';+}++/**+ * 成功 → 熔断信号:持有探测席位时只有代表性探测通道的回包才允许关熔断(普通 IPC+ * handler 里有大量纯内存实现,DB 卡死时照常应答);闭合态按通道分类,dispatch+ * 特判通道不定论,其余为真实恢复证据。+ */+export function classifyDeviceSendSuccess(channel: string, wasProbe = false): BreakerSettleOutcome {+ if (wasProbe && channel !== DEVICE_RESPONSIVENESS_PROBE_CHANNEL) return 'inconclusive';+ return BREAKER_NEUTRAL_INVOKE_CHANNELS.has(channel) ? 'inconclusive' : 'responded';+}++interface TrackerLogger {+ info(...args: unknown[]): void;+ warn(...args: unknown[]): void;+ debug(...args: unknown[]): void;+}++export interface ResponsivenessTrackerDeps {+ /**+ * 探测请求的发送函数(绕开 guardInvoke 的外层门禁,由 probeTick 内部经 acquire+ * 拿到探测席位后调用;实现方直接走 client.invoke,不要再套 remoteInvoke)。+ */+ probeInvoke(deviceId: string, channel: string, args: unknown[]): Promise<unknown>;+ /** 熔断 open/close 翻转回调(广播给 renderer + 恢复时重放订阅)。同状态不重复触发。 */+ onUnresponsiveChanged(deviceId: string, unresponsive: boolean): void;+ /** 探测前置条件:本实例持有 relay、链路 online、目标设备 presence 可用。 */+ isProbeEligible(deviceId: string): boolean;+ /** 时钟注入(测试用;默认 Date.now)。 */+ now?: () => number;+ log?: TrackerLogger;+}++export interface DeviceResponsivenessTracker {+ /**+ * 发送门禁 + 收尾上报,包住一次对目标设备的隧道请求:+ * 熔断 open 且无探测窗口 → 立即抛 DEVICE_UNRESPONSIVE(不占管道、不等超时);+ * 否则执行 run 并按结果 settle(超时计失败,真实回包按通道分类)。+ */+ guardInvoke<T>(deviceId: string, channel: string, run: () => Promise<T>): Promise<T>;+ /** 周期探测 tick:对每个熔断 open、探测窗口已到且前置条件满足的设备发一发单飞探测。 */+ probeTick(): void;+ isUnresponsive(deviceId: string): boolean;+ getUnresponsiveDeviceIds(): string[];+ /** 撤权 / presence 不可用等「响应性已无意义」的场景:清单个设备并作废其在途结果。 */+ clearDevice(deviceId: string): void;+ /** 登出 / 失去持有权:清空全部状态(open 中的设备会触发 onUnresponsiveChanged(false))。 */+ resetAll(): void;+}++export function createResponsivenessTracker(+ deps: ResponsivenessTrackerDeps,+): DeviceResponsivenessTracker {+ const log = deps.log ?? { info: () => {}, warn: () => {}, debug: () => {} };+ const now = deps.now ?? Date.now;+ const unresponsive = new Set<string>();+ const breaker = createDeviceResponsivenessBreaker({+ now: deps.now,+ onOpenChanged: (deviceId, open) => {+ if (open) unresponsive.add(deviceId);+ else unresponsive.delete(deviceId);+ log.info(+ `device ${deviceId.slice(0, 8)} responsiveness circuit ${open ? 'opened' : 'closed'}`,+ );+ deps.onUnresponsiveChanged(deviceId, open);+ },+ });++ const settle = (deviceId: string, slot: BreakerSendSlot, outcome: BreakerSettleOutcome): void => {+ 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 guardInvoke = async <T>(+ deviceId: string,+ channel: string,+ run: () => Promise<T>,+ ): Promise<T> => {+ const slot = breaker.acquire(deviceId, cohortFor(deviceId));+ if (slot.decision === 'reject') throw createDeviceUnresponsiveError(deviceId);+ const wasProbe = slot.decision === 'probe';+ try {+ const result = await run();+ settle(deviceId, slot, classifyDeviceSendSuccess(channel, wasProbe));+ return result;+ } catch (err) {+ settle(deviceId, slot, classifyDeviceSendFailure(err));+ throw err;+ }+ };++ const probeTick = (): void => {+ for (const deviceId of [...unresponsive]) {+ if (!breaker.probeDue(deviceId)) continue;+ if (!deps.isProbeEligible(deviceId)) continue;+ log.debug(`probing unresponsive device ${deviceId.slice(0, 8)}`);+ void guardInvoke(deviceId, DEVICE_RESPONSIVENESS_PROBE_CHANNEL, () =>+ deps.probeInvoke(+ deviceId,+ DEVICE_RESPONSIVENESS_PROBE_CHANNEL,+ buildDeviceResponsivenessProbeArgs(),+ ),+ ).catch((err) => {+ log.debug(`responsiveness probe failed for ${deviceId.slice(0, 8)}`, err);+ });+ }+ };++ return {+ guardInvoke,+ probeTick,+ isUnresponsive: (deviceId) => unresponsive.has(deviceId),+ getUnresponsiveDeviceIds: () => [...unresponsive],+ clearDevice: (deviceId) => {+ activeCohorts.delete(deviceId);+ breaker.clear(deviceId);+ },+ resetAll: () => {+ activeCohorts.clear();+ breaker.resetAll();+ },+ };+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex fbbd43ef58..049ff77fe6 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -531,6 +531,8 @@ const fanOutDeviceLinkControlledState = createIpcFanOut('device-link:controlled-const fanOutDeviceLinkAccessRevoked = createIpcFanOut('device-link:access-revoked');const fanOutDeviceLinkControlTargetChanged = createIpcFanOut('device-link:control-target-changed');const fanOutDeviceLinkKeepAwakeChanged = createIpcFanOut('device-link:keep-awake-changed');+// 控制端:目标设备「无响应」熔断状态翻转(payload = { deviceId, unresponsive })+const fanOutDeviceLinkResponsivenessChanged = createIpcFanOut('device-link:responsiveness-changed');// device-link 模型列表写穿:被控端本地 main → 自身 renderer,把控制端写穿的草稿 / 会话 pref// 交给 renderer 调它原来的本地 setter。仅被控端进程会收到(控制端从不收 → 监听不误触发)。@@ -3238,6 +3240,7 @@ contextBridge.exposeInMainWorld('electronAPI', {controlledBy: Array<{ deviceId: string; name: string }>;revokedControllers: string[];disabledControlDeviceIds: string[];+ unresponsiveDeviceIds: string[];}> => ipcRenderer.invoke('device-link:get-state'),setEnabled: (enabled: boolean): Promise<{ remoteControlEnabled: boolean }> =>ipcRenderer.invoke('device-link:set-enabled', enabled),@@ -3309,6 +3312,8 @@ contextBridge.exposeInMainWorld('electronAPI', {onControlTargetChanged: fanOutDeviceLinkControlTargetChanged,/** 「保持电脑唤醒」在其它共享 userData 实例被翻转后推送,payload: { keepAwake: boolean } */onKeepAwakeChanged: fanOutDeviceLinkKeepAwakeChanged,+ /** 控制端:目标设备「无响应」熔断状态翻转,payload: { deviceId, unresponsive } */+ onResponsivenessChanged: fanOutDeviceLinkResponsivenessChanged,/*** 控制端:远程会话镜像的本地冷缓存(main 落 userData,见 main/device-link/mirrorCacheStore.ts)。* 只做首屏加速,非权威;fresh 数据一到由 renderer 整体接管。diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.tsindex 6a8ecc3e08..8d64b1df76 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest';import {+ createReconcileBackoff,resolveIneligibleRemoteProjectAction,startRemoteSessionsReconciler,} from '@/features/device-link/useDeviceLinkRemoteProjects';@@ -34,6 +35,132 @@ describe('startRemoteSessionsReconciler', () => {await vi.advanceTimersByTimeAsync(2_000);expect(refresh).toHaveBeenCalledTimes(3);});++ it('连续 gave-up 的设备按指数退避放慢,成功后复位;其它设备不受影响', async () => {+ vi.useFakeTimers();+ const eligible = new Map([+ ['dev-bad', 'Mac Bad'],+ ['dev-good', 'Mac Good'],+ ]);+ let badResult: string = 'gave-up';+ const refresh = vi.fn(async (deviceId: string) =>+ deviceId === 'dev-bad' ? badResult : 'ok',+ );+ // 无抖动 + 假时钟,退避序列确定:失败 1 次后推迟 1s(=base),2 次后 2s,3 次后 4s…+ const backoff = createReconcileBackoff({+ baseMs: 1_000,+ maxMs: 8_000,+ jitter: (d) => d,+ now: () => Date.now(),+ });+ const stop = startRemoteSessionsReconciler(() => eligible, refresh, 1_000, backoff);++ const badCalls = () => refresh.mock.calls.filter(([id]) => id === 'dev-bad').length;+ const goodCalls = () => refresh.mock.calls.filter(([id]) => id === 'dev-good').length;++ // tick1: bad 尝试并失败(退避 1s) → tick2(t=2s)已过退避,再试(失败,退避 2s)+ // → tick3(t=3s)在退避中跳过,tick4(t=4s)再试(失败,退避 4s)→ t=5s/6s/7s 跳过,t=8s 再试+ await vi.advanceTimersByTimeAsync(1_000);+ expect(badCalls()).toBe(1);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(badCalls()).toBe(2);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(badCalls()).toBe(2); // 退避中+ await vi.advanceTimersByTimeAsync(1_000);+ expect(badCalls()).toBe(3);+ await vi.advanceTimersByTimeAsync(3_000);+ expect(badCalls()).toBe(3); // 退避 4s 中+ await vi.advanceTimersByTimeAsync(1_000);+ expect(badCalls()).toBe(4);++ // good 设备每个 tick 照常对账,不被 bad 的退避拖累+ expect(goodCalls()).toBe(8);++ // bad 恢复:下一次尝试成功后退避复位,恢复逐 tick 对账+ badResult = 'ok';+ await vi.advanceTimersByTimeAsync(8_000);+ const afterRecovery = badCalls();+ await vi.advanceTimersByTimeAsync(2_000);+ expect(badCalls()).toBe(afterRecovery + 2);++ stop();+ });++ it('单次刷新横跨多个 tick 时只发一次、只记账一次(在途合并不重复累计退避)', async () => {+ vi.useFakeTimers();+ const eligible = new Map([['dev-slow', 'Mac Slow']]);+ let settle: ((r: string) => void) | null = null;+ const refresh = vi.fn(+ () => new Promise<string>((resolve) => {+ settle = resolve;+ }),+ );+ const failures: string[] = [];+ const backoff = createReconcileBackoff({ baseMs: 1_000, maxMs: 8_000, jitter: (d) => d });+ const origReport = backoff.report.bind(backoff);+ backoff.report = (deviceId, outcome) => {+ if (outcome === 'failure') failures.push(deviceId);+ origReport(deviceId, outcome);+ };+ const stop = startRemoteSessionsReconciler(() => eligible, refresh, 1_000, backoff);++ // 三个 tick 过去,刷新仍在途:不再重复发起,也没有任何记账+ await vi.advanceTimersByTimeAsync(3_000);+ expect(refresh).toHaveBeenCalledTimes(1);+ expect(failures).toEqual([]);++ // 在途请求最终 gave-up:恰好记一次失败+ settle!('gave-up');+ await vi.advanceTimersByTimeAsync(0);+ expect(failures).toEqual(['dev-slow']);+ stop();+ });++ it('抖动结果被 clamp 在 maxMs 内(封顶是硬上限,+15% 不得越过)', () => {+ let at = 0;+ const backoff = createReconcileBackoff({+ baseMs: 1_000,+ maxMs: 8_000,+ jitter: (d) => d * 1.15, // 模拟上向抖动+ now: () => at,+ });+ for (let i = 0; i < 10; i++) backoff.report('dev-a', 'failure');+ at = 8_000; // 恰到封顶值:若 jitter 越过 maxMs,这里仍会是退避中+ expect(backoff.shouldAttempt('dev-a')).toBe(true);+ // 负值抖动防御:不会把 nextEligibleAt 推到过去之前(行为上等价于立即可试)+ const negBackoff = createReconcileBackoff({+ baseMs: 1_000,+ maxMs: 8_000,+ jitter: () => -5_000,+ now: () => 100,+ });+ negBackoff.report('dev-b', 'failure');+ expect(negBackoff.shouldAttempt('dev-b')).toBe(true);+ });++ it('设备移出合格集后退避账本随之清理,重新合格时从零开始', () => {+ let at = 0;+ const backoff = createReconcileBackoff({+ baseMs: 1_000,+ maxMs: 8_000,+ jitter: (d) => d,+ now: () => at,+ });+ backoff.report('dev-a', 'failure');+ backoff.report('dev-a', 'failure');+ expect(backoff.shouldAttempt('dev-a')).toBe(false);+ backoff.retainOnly(new Set(['dev-b']));+ expect(backoff.shouldAttempt('dev-a')).toBe(true);+ // neutral 不改变账本+ backoff.report('dev-b', 'neutral');+ expect(backoff.shouldAttempt('dev-b')).toBe(true);+ // 封顶:多次失败后延迟不超过 maxMs+ for (let i = 0; i < 10; i++) backoff.report('dev-b', 'failure');+ at = 7_999;+ expect(backoff.shouldAttempt('dev-b')).toBe(false);+ at = 8_000;+ expect(backoff.shouldAttempt('dev-b')).toBe(true);+ });});describe('resolveIneligibleRemoteProjectAction', () => {diff --git a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.tsindex 73a5bc12c1..9ee7030021 100644--- a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts+++ b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts@@ -89,10 +89,12 @@ describe('Dialogue sidebar section', () => {const connectingIndex = sidebarSource.indexOf('selectedMachineConnecting ?');expect(failureIndex).toBeGreaterThanOrEqual(0);expect(connectingIndex).toBeGreaterThan(failureIndex);- expect(sidebarSource).toContain('retryRemoteSessionBootstrap(device.deviceId)');expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksLoadFailed'");expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksPartiallyFailed'");- expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.retryTasks'");+ // 任务读取失败是「自动重试进行中」的状态说明(reconciler 退避重试 + 熔断探测恢复+ // 自动补拉),不再提供手动重试按钮(2026-08 弱网实测反馈:重连必须全自动)。+ expect(sidebarSource).not.toContain('retryRemoteSessionBootstrap(device.deviceId)');+ expect(sidebarSource).not.toContain("'ccAgent.sidebar.machineSwitcher.retryTasks'");expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksLoading'");expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.devicesLoadFailed'");expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.devicesLoading'");diff --git a/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx b/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsxindex 5cfdf5ef6c..69e80d28d5 100644--- a/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx+++ b/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx@@ -45,6 +45,7 @@ const getState = vi.fn<() => Promise<DeviceLinkState>>(async () => ({controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],+ unresponsiveDeviceIds: [],}));const listDevices = vi.fn(async () => ({devices: [@@ -465,6 +466,7 @@ describe('MobileDownloadDialog', () => {controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],+ unresponsiveDeviceIds: [],};getState.mockImplementationOnce(diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex fb58cd40c4..f31d73639d 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -223,6 +223,37 @@ describe('refreshRemoteDeviceSessions retry', () => {expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);});+ it('超时类失败只额外重试 1 次:每次都吃满隧道超时,不许按完整预算连打 6 个', async () => {+ const d = did();+ invoke.mockRejectedValue(new Error('[DEVICE_LINK_TIMEOUT] no invoke-result within 12000ms'));+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(+ 'gave-up',+ );+ expect(invoke).toHaveBeenCalledTimes(2);+ });++ it('超时账本独立:一次超时不吞掉快速失败瞬态错误的完整预算', async () => {+ const d = did();+ invoke+ .mockRejectedValueOnce(new Error('[DEVICE_LINK_TIMEOUT] no invoke-result within 12000ms'))+ .mockRejectedValueOnce(new Error('DbClient not ready'))+ .mockRejectedValueOnce(new Error('DbClient not ready'))+ .mockResolvedValueOnce([session('s1')]);+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe('ok');+ expect(invoke).toHaveBeenCalledTimes(4);+ });++ it('熔断快速失败(DEVICE_LINK_DEVICE_UNRESPONSIVE)→ 不重试,立即放弃', async () => {+ const d = did();+ invoke.mockRejectedValue(+ new Error('[DEVICE_LINK_DEVICE_UNRESPONSIVE] target device is unresponsive (circuit open)'),+ );+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(+ 'gave-up',+ );+ expect(invoke).toHaveBeenCalledTimes(1);+ });+it('重试耗尽 → 放弃,不抛(返回 gave-up,尝试次数 = maxAttempts)', async () => {const d = did();invoke.mockRejectedValue(new Error('DbClient not ready'));diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 12a6e9d1d8..adca150199 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -3165,16 +3165,19 @@ export function CCAgentSessionView({</div>)}- {/* device-link 远程会话状态 banner:断链重连 / 被控离线时提示 + 重新同步(以被控端为准重拉对账)。- suspect-stall(链路在线但本轮久未更新且核实不到被控端)优先 —— 它可能在 connected 时触发,- 额外给「结束本轮」手动收尾。connected / local 且无 stall 时不渲染。 */}+ {/* device-link 远程会话状态 banner:断链重连 / 被控离线 / 通路不稳定(degraded,弱网熔断)+ 时提示 + 重新同步(以被控端为准重拉对账)。suspect-stall(链路在线但本轮久未更新且核实+ 不到被控端)优先 —— 它可能在 connected 时触发,额外给「结束本轮」手动收尾。+ connected / local 且无 stall 时不渲染。 */}{remoteSync.suspectStall ? (<RemoteSessionBannerstatus="suspect-stall"onResync={remoteSync.resync}onFinalize={remoteSync.forceFinalize}/>- ) : remoteConn === 'reconnecting' || remoteConn === 'host-offline' ? (+ ) : remoteConn === 'reconnecting' ||+ remoteConn === 'host-offline' ||+ remoteConn === 'degraded' ? (<RemoteSessionBannerstatus={remoteConn}issue={remoteLinkIssue}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex f09c859b96..88e6fef026 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -151,10 +151,7 @@ import type {AutomationScheduleSessionInfo,AutomationSessionGroup,} from './lib/automationSidebarGrouping';-import {- getSessionDeviceId,- retryRemoteSessionBootstrap,-} from '@/features/device-link/remoteProjectsStore';+import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';import {useRemoteSessionActivity,useRemoteSessionActivityRevision,@@ -275,6 +272,13 @@ function RemoteSidebarLoadNotice({}) {const { t } = useTranslation();const isError = status === 'error';+ // tasks 的读取失败有完整自动恢复链路(10s 起对账退避重试 + 熔断探测恢复后自动重新+ // bootstrap),失败态只是「自动重试进行中」的状态说明,不是要求用户行动的告警——+ // 用中性样式 + role=status,且**不提供手动按钮**(2026-08 弱网实测反馈:重连必须+ // 全自动,红色 alert + 按钮读起来像必须人工干预)。devices 目录失败没有等价的+ // 自动重试,保持告警 + 手动重试。+ const autoRetrying = isError && kind === 'tasks';+ const alarming = isError && !autoRetrying;const messageKey =kind === 'tasks'? status === 'loading'@@ -289,10 +293,10 @@ function RemoteSidebarLoadNotice({: 'ccAgent.sidebar.machineSwitcher.devicesLoadFailed';return (<div- role={isError ? 'alert' : 'status'}+ role={alarming ? 'alert' : 'status'}className={cn('border',- isError+ alarming? 'border-[var(--error-border)] bg-[var(--error-bg)] text-[var(--error-fg)]': 'border-[var(--border-default)] bg-[var(--surface-chip)] text-[var(--text-secondary)]',partial@@ -312,7 +316,7 @@ function RemoteSidebarLoadNotice({{t(messageKey, { device: deviceLabel })}</p></div>- {isError && onRetry && (+ {alarming && onRetry && (<buttontype="button"onClick={onRetry}@@ -324,11 +328,7 @@ function RemoteSidebarLoadNotice({)}><RefreshCw size={12} />- {t(- kind === 'tasks'- ? 'ccAgent.sidebar.machineSwitcher.retryTasks'- : 'ccAgent.sidebar.machineSwitcher.retryDevices',- )}+ {t('ccAgent.sidebar.machineSwitcher.retryDevices')}</button>)}</div>@@ -1063,11 +1063,6 @@ function ExpandedView({),[i18n.language, remoteSessionBootstrapFailures],);- const handleRetryRemoteTasks = useCallback(() => {- for (const device of remoteSessionBootstrapFailures) {- retryRemoteSessionBootstrap(device.deviceId);- }- }, [remoteSessionBootstrapFailures]);const isLoadingSidebarSessions =sessionsHook.isLoading ||remoteSessionBootstrapLoading ||@@ -2737,7 +2732,6 @@ function ExpandedView({status="error"deviceLabel={failedRemoteDeviceLabel}partial={false}- onRetry={handleRetryRemoteTasks}/>) : remoteDeviceDirectoryStatus === 'loading' && !hasVisibleSidebarContent ? (<RemoteSidebarLoadNotice kind="devices" status="loading" partial={false} />@@ -2772,7 +2766,6 @@ function ExpandedView({status="error"deviceLabel={failedRemoteDeviceLabel}partial- onRetry={handleRetryRemoteTasks}/>)}{remoteDeviceDirectoryStatus === 'loading' && (diff --git a/apps/desktop/src/renderer/features/cc-agent/RemoteSessionBanner.tsx b/apps/desktop/src/renderer/features/cc-agent/RemoteSessionBanner.tsxindex 49a8312b75..cbac082188 100644--- a/apps/desktop/src/renderer/features/cc-agent/RemoteSessionBanner.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/RemoteSessionBanner.tsx@@ -1,10 +1,15 @@/*** RemoteSessionBanner —— 控制端打开的远程会话状态提示条。*- * 让"连接 / 同步有问题"可见而非静默卡住,在会话视图顶部显示一条 strip,带「重新同步」按钮- * (经隧道以被控端为准重拉对账)。三种 status:+ * 让"连接 / 同步有问题"可见而非静默卡住,在会话视图顶部显示一条 strip。+ * 连接类状态(reconnecting / host-offline / degraded)的恢复全自动(重连 / presence /+ * 熔断探测 + 恢复后自动 resync),不提供手动按钮(2026-08 弱网实测反馈:重连必须全自动);+ * 只有 suspect-stall 保留「重新同步」「结束本轮」——那是自动机制无法核实的卡死回合,+ * 需要用户裁决。四种 status:* - reconnecting : 本机断链重连中。* - host-offline : 被控设备离线。+ * - degraded : 两端 presence 均在线但被控端连续超时被熔断判定无响应(弱网 / 对端+ * 卡死),正在自动探测恢复 —— 区别于 host-offline,设备并没有离线。* - suspect-stall : 链路在线但本轮久未更新、且无法向被控端核实其真实运行态(不可达 / 旧端 /* 超时)→ 可能已断流。额外给「结束本轮」让用户手动收尾卡死的 Generating。* 连接 / 同步恢复后由上层据状态自动隐藏。@@ -16,7 +21,7 @@ import { useTranslation } from 'react-i18next';import { RotateCw, Square } from 'lucide-react';interface Props {- status: 'reconnecting' | 'host-offline' | 'suspect-stall';+ status: 'reconnecting' | 'host-offline' | 'degraded' | 'suspect-stall';/*** 本机到 relay 的连接问题(鉴权失效/被顶号/超限/版本不符)。仅 reconnecting 态消费:* 有明确原因时把笼统的「重连中」替换成具体原因文案,避免无限重连横幅无法行动。@@ -40,8 +45,12 @@ export function RemoteSessionBanner({ status, issue, onResync, onFinalize }: Pro? t('ccAgent.remoteSession.reconnecting'): status === 'host-offline'? t('ccAgent.remoteSession.hostOffline')- : t('ccAgent.remoteSession.suspectStall');- const pulse = !activeIssue && (status === 'reconnecting' || status === 'suspect-stall');+ : status === 'degraded'+ ? t('ccAgent.remoteSession.degraded')+ : t('ccAgent.remoteSession.suspectStall');+ const pulse =+ !activeIssue &&+ (status === 'reconnecting' || status === 'degraded' || status === 'suspect-stall');return (<div className="flex select-none items-center gap-2 border-b border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-1.5">@@ -65,14 +74,16 @@ export function RemoteSessionBanner({ status, issue, onResync, onFinalize }: Pro{t('ccAgent.remoteSession.finalizeStuck')}</button>)}- <button- type="button"- onClick={onResync}- className="flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-[12px] text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)]"- >- <RotateCw size={12} />- {t('ccAgent.remoteSession.resync')}- </button>+ {status === 'suspect-stall' && (+ <button+ type="button"+ onClick={onResync}+ className="flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-[12px] text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)]"+ >+ <RotateCw size={12} />+ {t('ccAgent.remoteSession.resync')}+ </button>+ )}</div>);}diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionConnection.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionConnection.tsindex 669cdd5bd3..1d3a628529 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionConnection.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionConnection.ts@@ -15,21 +15,30 @@import { useEffect, useState, useSyncExternalStore } from 'react';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import { unresponsiveDevicesStore } from '@/features/device-link/unresponsiveDevicesStore';type LinkStatus = 'stopped' | 'connecting' | 'online';-export type RemoteConnectionStatus = 'local' | 'connected' | 'reconnecting' | 'host-offline';+export type RemoteConnectionStatus =+ | 'local'+ | 'connected'+ | 'reconnecting'+ | 'host-offline'+ | 'degraded';/*** 纯派生:本机链路非 online → reconnecting(本机断链,优先级最高);本机在线但被控端不在线- * → host-offline;都在线 → connected。便于单测。+ * → host-offline;两端都「在线」但被控端被熔断判定无响应(连续 invoke 超时,弱网 / 对端+ * 卡死)→ degraded;否则 connected。便于单测。*/export function deriveRemoteConnectionStatus(linkStatus: LinkStatus,hostOnline: boolean,+ hostUnresponsive = false,): Exclude<RemoteConnectionStatus, 'local'> {if (linkStatus !== 'online') return 'reconnecting';if (!hostOnline) return 'host-offline';+ if (hostUnresponsive) return 'degraded';return 'connected';}@@ -112,6 +121,13 @@ export function useRemoteSessionConnection(deviceId: string | undefined): Remote() => (deviceId ? remoteProjectsStore.getDeviceIds().includes(deviceId) : false),);+ // 「无响应」熔断镜像(main 权威,useDeviceLinkRemoteProjects 接线):presence 在线但+ // 连续 invoke 超时 → degraded,让弱网不再表现为「界面不动 + 每次操作干等超时」。+ const hostUnresponsive = useSyncExternalStore(+ unresponsiveDevicesStore.subscribe,+ () => (deviceId ? unresponsiveDevicesStore.getSnapshot().has(deviceId) : false),+ );+if (!deviceId) return 'local';- return deriveRemoteConnectionStatus(linkStatus, hostOnline);+ return deriveRemoteConnectionStatus(linkStatus, hostOnline, hostUnresponsive);}diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex f95b4a801d..f8d2759b21 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -52,6 +52,19 @@ const MISSING_STATUS_PROBE_LIMIT = 8;/** 默认重试次数(含首次):退避 250→500→1000→2000→3000ms,总窗口 ~6.75s,覆盖被控端冷启动迁移。 */const DEFAULT_MAX_ATTEMPTS = 6;+/**+ * 超时类失败(DEVICE_LINK_TIMEOUT)的独立预算(含首次):超时不是快速失败——每次都+ * 吃满隧道超时(sessions:list 现为 12s)。按 DEFAULT_MAX_ATTEMPTS 重试的话,一轮对账+ * 最坏连打 6 个满超时请求(2026-08 弱网实测:30s 超时时代一轮 ~187s,单日 2253 次超时+ * 堆成请求风暴)。超时说明链路不通,原地重试大概率还是超时:只再试 1 次,其余交给+ * 下一轮 reconciler / push / 熔断探测兜底。DbClient not ready 等毫秒级快速失败仍走+ * 完整预算(它们才是这条重试链的原始动机:覆盖被控端冷启动迁移窗口)。+ */+const MAX_TIMEOUT_ATTEMPTS = 2;++/** 超时标记(renderer 看到的是 main IPC 层映射后的码,见 TRANSIENT_MARKERS 注释)。 */+const TIMEOUT_MARKER = 'DEVICE_LINK_TIMEOUT';+/** 永久错误标记:命中即立即放弃(被控开关关 / channel 不在白名单)—— 重试也不会变。 */const PERMANENT_MARKERS = ['REMOTE_DISABLED', 'CHANNEL_NOT_ALLOWED'] as const;@@ -357,6 +370,7 @@ async function runRefreshRemoteDeviceSessions(const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;const deviceName = name ?? remoteProjectsStore.getDeviceName(deviceId) ?? deviceId;const epoch = remoteProjectsStore.nextSnapshotEpoch(deviceId);+ let timeoutAttempts = 0;for (let attempt = 0; attempt < maxAttempts; attempt++) {// 被一次更新的重拉取代(期间又发起了新的 refresh)→ 停手,交给那一次(也避免无谓重试)。@@ -400,7 +414,12 @@ async function runRefreshRemoteDeviceSessions(log.debug(`refreshRemoteDeviceSessions access revoked for ${deviceId.slice(0, 8)}`);return 'revoked';}- const canRetry = attempt < maxAttempts - 1 && isTransientRemoteError(message);+ // 超时单独记账:它每次都吃满隧道超时,不能像快速失败那样按完整预算原地重试。+ if (message.includes(TIMEOUT_MARKER)) timeoutAttempts++;+ const canRetry =+ attempt < maxAttempts - 1 &&+ timeoutAttempts < MAX_TIMEOUT_ATTEMPTS &&+ isTransientRemoteError(message);if (!canRetry) {// 永久错误 / 重试耗尽:放弃(push / 下一次 reconnect 仍会兜底补上,只是慢一拍)。log.debug(`refreshRemoteDeviceSessions gave up for ${deviceId.slice(0, 8)}`, err);diff --git a/apps/desktop/src/renderer/features/device-link/unresponsiveDevicesStore.ts b/apps/desktop/src/renderer/features/device-link/unresponsiveDevicesStore.tsnew file mode 100644index 0000000000..49f19ab8f8--- /dev/null+++ b/apps/desktop/src/renderer/features/device-link/unresponsiveDevicesStore.ts@@ -0,0 +1,58 @@+/**+ * unresponsiveDevicesStore —— 控制端内存镜像:哪些目标设备被熔断判定为「无响应」。+ * ---------------------------------------------------------------------------+ * 真相源在 main 的 responsivenessTracker(连续 invoke 超时熔断,探测恢复):renderer+ * 只镜像 getState().unresponsiveDeviceIds 初值 + RESPONSIVENESS_CHANGED push 增量,+ * 由 useDeviceLinkRemoteProjects 统一接线(每窗口一份,与 remoteProjectsStore 同生命期)。+ * 消费方:+ * - useRemoteSessionConnection:presence 在线但设备无响应 → 'degraded'(弱网降级 banner);+ * - useDeviceLinkRemoteProjects:恢复(unresponsive=false)时重跑 subscribe + bootstrap。+ *+ * getSnapshot 返回稳定引用(仅内容变化时换新),契合 useSyncExternalStore(无 tearing)。+ */++const unresponsive = new Set<string>();+let snapshot: ReadonlySet<string> = new Set();+const listeners = new Set<() => void>();++function recompute(): void {+ snapshot = new Set(unresponsive);+ for (const l of listeners) l();+}++export const unresponsiveDevicesStore = {+ /** 用 main 的权威快照整体替换(getState 初值 / 重连对齐)。 */+ replaceAll(deviceIds: readonly string[]): void {+ if (deviceIds.length === unresponsive.size && deviceIds.every((id) => unresponsive.has(id))) {+ return;+ }+ unresponsive.clear();+ for (const id of deviceIds) unresponsive.add(id);+ recompute();+ },+ /** 应用一条 RESPONSIVENESS_CHANGED push(幂等)。 */+ apply(deviceId: string, isUnresponsive: boolean): void {+ if (isUnresponsive ? unresponsive.has(deviceId) : !unresponsive.has(deviceId)) return;+ if (isUnresponsive) unresponsive.add(deviceId);+ else unresponsive.delete(deviceId);+ recompute();+ },+ /** 全清(登出 / 卸载;重挂载时由 getState 初值重建)。 */+ clearAll(): void {+ if (unresponsive.size === 0) return;+ unresponsive.clear();+ recompute();+ },+ has(deviceId: string): boolean {+ return unresponsive.has(deviceId);+ },+ subscribe(cb: () => void): () => void {+ listeners.add(cb);+ return () => {+ listeners.delete(cb);+ };+ },+ getSnapshot(): ReadonlySet<string> {+ return snapshot;+ },+};diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex 832de0a1d0..b32edfaa55 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -44,6 +44,7 @@ import {removeRemoteSessionActivityForDevice,} from './remoteSessionActivityStore';import { revokedDevicesStore } from './revokedDevicesStore';+import { unresponsiveDevicesStore } from './unresponsiveDevicesStore';import { collectSessionListSnapshot, refreshRemoteDeviceSessions } from './refreshRemoteSessions';import {cancelSessionListPersist,@@ -67,23 +68,101 @@ const RESEED_DEBOUNCE_MS = 300;/** best-effort push 的窗口内 anti-entropy 周期。窗口外终态按有界轮询分批收敛。 */const RECONCILE_INTERVAL_MS = 10_000;+/** 连续失败退避封顶:失败设备最低仍保持约 2 分钟一次的对账,恢复靠 push / 熔断探测先行。 */+const RECONCILE_BACKOFF_MAX_MS = 120_000;+type RemoteSessionsRefresh = (deviceId: string, name?: string) => Promise<unknown>;+/**+ * per-device 对账退避账本(纯逻辑,可单测)。+ *+ * 弱网教训(2026-08):固定 10s 无退避的对账循环在链路劣化时永不放慢,叠加超时重试+ * 变成请求风暴。这里按设备记连续失败:失败后下一次尝试推迟 base×2^(n-1)(封顶 maxMs,+ * ±15% 抖动打散多设备齐步),成功即复位;'superseded' / 'revoked' 不计失败——前者是+ * 并发合并的正常路径,后者有自己的终态处理。+ */+export function createReconcileBackoff(opts?: {+ baseMs?: number;+ maxMs?: number;+ /** 抖动注入(测试用;默认 ±15% 随机)。 */+ jitter?: (delayMs: number) => number;+ now?: () => number;+}) {+ const baseMs = opts?.baseMs ?? RECONCILE_INTERVAL_MS;+ const maxMs = opts?.maxMs ?? RECONCILE_BACKOFF_MAX_MS;+ const jitter =+ opts?.jitter ?? ((delay: number) => Math.round(delay * (0.85 + Math.random() * 0.3)));+ const now = opts?.now ?? Date.now;+ const state = new Map<string, { failures: number; nextEligibleAt: number }>();+ return {+ /** 本 tick 是否应该对该设备发起对账。 */+ shouldAttempt(deviceId: string): boolean {+ const entry = state.get(deviceId);+ return !entry || now() >= entry.nextEligibleAt;+ },+ /** 上报一次对账结果。failure 加深退避,success 复位,neutral 不动。 */+ report(deviceId: string, outcome: 'success' | 'failure' | 'neutral'): void {+ if (outcome === 'neutral') return;+ if (outcome === 'success') {+ state.delete(deviceId);+ return;+ }+ const failures = (state.get(deviceId)?.failures ?? 0) + 1;+ const delay = Math.min(baseMs * 2 ** (failures - 1), maxMs);+ // 抖动后再 clamp:maxMs 是硬封顶(review:+15% 抖动曾把封顶档放大到 138s),+ // 负值防御性归零。+ const jittered = Math.min(Math.max(0, jitter(delay)), maxMs);+ state.set(deviceId, { failures, nextEligibleAt: now() + jittered });+ },+ /** 只保留仍合格的设备,防止退避账本随设备增删无界增长。 */+ retainOnly(deviceIds: ReadonlySet<string>): void {+ for (const deviceId of state.keys()) {+ if (!deviceIds.has(deviceId)) state.delete(deviceId);+ }+ },+ };+}++export type ReconcileBackoff = ReturnType<typeof createReconcileBackoff>;+/*** 启动 listing tier 的低频有界对账。setInterval 只负责触发;每设备的并发合并与乱序保护- * 继续由 refreshRemoteDeviceSessions 负责。返回清理函数,避免窗口卸载后残留 timer。+ * 继续由 refreshRemoteDeviceSessions 负责;连续失败的设备按 createReconcileBackoff 放慢+ * (refresh resolve 出的 RefreshResult 用于记账:'gave-up' = 失败,'ok' = 成功,其余中性;+ * reject 一律计失败)。返回清理函数,避免窗口卸载后残留 timer。*/export function startRemoteSessionsReconciler(getEligibleDevices: () => Iterable<readonly [string, string]>,refresh: RemoteSessionsRefresh = refreshRemoteDeviceSessions,intervalMs = RECONCILE_INTERVAL_MS,+ backoff: ReconcileBackoff = createReconcileBackoff({ baseMs: intervalMs }),): () => void {+ // 单次刷新可能横跨多个 tick(弱网下超时链 >10s);weak coalescing 会让后续 tick 拿到+ // 同一个在途 Promise,若每个 tick 都挂 then,一次 gave-up 会被重复记账、退避直接跳档+ // (review P2)。per-device 在途标记保证一次合并请求只记一次。+ const inFlight = new Set<string>();const timer = setInterval(() => {+ const seen = new Set<string>();for (const [deviceId, name] of getEligibleDevices()) {- void refresh(deviceId, name).catch((err) => {- log.debug(`periodic sessions reconcile failed for ${deviceId.slice(0, 8)}`, err);- });+ seen.add(deviceId);+ if (inFlight.has(deviceId) || !backoff.shouldAttempt(deviceId)) continue;+ inFlight.add(deviceId);+ void refresh(deviceId, name)+ .then((result) => {+ backoff.report(+ deviceId,+ result === 'gave-up' ? 'failure' : result === 'ok' ? 'success' : 'neutral',+ );+ })+ .catch((err) => {+ backoff.report(deviceId, 'failure');+ log.debug(`periodic sessions reconcile failed for ${deviceId.slice(0, 8)}`, err);+ })+ .finally(() => {+ inFlight.delete(deviceId);+ });}+ backoff.retainOnly(seen);}, intervalMs);return () => clearInterval(timer);}@@ -368,15 +447,40 @@ export function useDeviceLinkRemoteProjects(): void {coalescingMode: 'weak',});if (result === 'revoked' && !disposed) handleRevoked(deviceId);+ // 回传结果供 reconciler 的失败退避记账('gave-up' 加深退避,'ok' 复位)。+ return result;},);+ // 目标设备「无响应」熔断翻转(main 权威):镜像给 UI;恢复时重跑 subscribe+bootstrap+ // ——熔断 open 期间的订阅 / 首拉都被快速失败挡掉了,恢复必须主动补,不能等用户手点。+ // push 一旦到达即权威,但只对**它自己那台设备**权威:迟到的 getState 快照按设备合并,+ // 未被 push 覆盖的设备仍取快照值 —— 整份丢弃会让「A 设备先来一条 push」掩盖掉+ // 快照里 B 设备的 unresponsive 初值,B 在下一次熔断翻转前一直假装 connected(review P1)。+ const responsivenessPushedDeviceIds = new Set<string>();+ const offResponsiveness = window.electronAPI.deviceLink.onResponsivenessChanged((p) => {+ if (disposed) return;+ responsivenessPushedDeviceIds.add(p.deviceId);+ unresponsiveDevicesStore.apply(p.deviceId, p.unresponsive);+ if (!p.unresponsive) {+ const name = eligible.get(p.deviceId);+ if (name) void subscribeAndBootstrap(p.deviceId, name);+ }+ });+void window.electronAPI.deviceLink.getState().then((state) => {if (disposed) return;if (!linkStatusPushSeen) linkOnline = state.linkStatus === 'online';disabledControlDeviceIds = new Set(state.disabledControlDeviceIds ?? []);+ // 「无响应」熔断镜像的初值:按设备合并,已被 push 覆盖的设备以 push 为准+ // (store 初始为空,快照只需补写 unresponsive 的未覆盖设备)。+ for (const deviceId of state.unresponsiveDeviceIds ?? []) {+ if (!responsivenessPushedDeviceIds.has(deviceId)) {+ unresponsiveDevicesStore.apply(deviceId, true);+ }+ }reseed();}).catch((err) => {@@ -497,6 +601,8 @@ export function useDeviceLinkRemoteProjects(): void {offControlTarget();offRename();offShardChange();+ offResponsiveness();+ unresponsiveDevicesStore.clearAll();// best-effort 取消所有订阅(被控端 presence-offline 也会兜底清僵尸订阅)+ 驱逐远端快照缓存。for (const deviceId of eligible.keys()) {window.electronAPI.deviceLink.unsubscribe(deviceId, ['sessions']).catch(() => {});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 48d534ee0e..cb09c9c562 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6115,6 +6115,7 @@"remoteSession": {"reconnecting": "Connection to the controlled device was lost — reconnecting…","hostOffline": "The controlled device is offline; can't sync right now",+ "degraded": "Connection to the controlled device is unstable — retrying automatically…","actionsUnavailable": "The controlled device is unavailable. Reconnect it before changing this session.","resync": "Resync","loading": "Loading session from the remote device…",@@ -6248,9 +6249,8 @@"localMachine": "This device","connecting": "Connecting…","tasksLoading": "Loading sessions from {{device}}…",- "tasksLoadFailed": "Couldn't load sessions from {{device}}. Check the connection and try again.",- "tasksPartiallyFailed": "Sessions from {{device}} couldn't be loaded. Showing only content that loaded successfully.",- "retryTasks": "Reload sessions",+ "tasksLoadFailed": "Can't reach sessions on {{device}} right now — retrying automatically…",+ "tasksPartiallyFailed": "Can't reach sessions on {{device}} right now — retrying automatically; showing what's already loaded","devicesLoading": "Loading remote devices…","devicesLoadFailed": "Couldn't load the remote device list. Check the connection and try again.","devicesPartiallyFailed": "The remote device list couldn't be refreshed. Showing only content that loaded successfully.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c76756c3b4..5f5e82aecd 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6104,6 +6104,7 @@"remoteSession": {"reconnecting": "被制御デバイスとの接続が切れました。再接続中…","hostOffline": "被制御デバイスがオフラインのため、現在は同期できません",+ "degraded": "被制御デバイスとの接続が不安定です。自動的に再試行中…","actionsUnavailable": "被制御デバイスを利用できません。再接続してからこのセッションを変更してください。","resync": "再同期","loading": "リモートデバイスからセッションを読み込み中…",@@ -6237,9 +6238,8 @@"localMachine": "このデバイス","connecting": "接続中…","tasksLoading": "{{device}} のセッションを読み込み中…",- "tasksLoadFailed": "{{device}} のセッションを読み込めませんでした。接続を確認して再試行してください。",- "tasksPartiallyFailed": "{{device}} のセッションを読み込めませんでした。読み込み済みの内容のみ表示しています。",- "retryTasks": "セッションを再読み込み",+ "tasksLoadFailed": "現在 {{device}} のセッションを読み込めません。自動的に再試行中…",+ "tasksPartiallyFailed": "現在 {{device}} のセッションを読み込めません。自動的に再試行中のため、読み込み済みの内容のみ表示しています","devicesLoading": "リモートデバイスを読み込み中…","devicesLoadFailed": "リモートデバイスの一覧を読み込めませんでした。接続を確認して再試行してください。","devicesPartiallyFailed": "リモートデバイスの一覧を更新できませんでした。読み込み済みの内容のみ表示しています。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 41a0d80b44..0bc3c3507d 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6104,6 +6104,7 @@"remoteSession": {"reconnecting": "제어 대상 기기와 연결이 끊겼습니다. 다시 연결 중…","hostOffline": "제어 대상 기기가 오프라인이라 지금은 동기화할 수 없습니다",+ "degraded": "제어 대상 기기와 연결이 불안정합니다. 자동으로 다시 시도 중…","actionsUnavailable": "제어 대상 기기를 사용할 수 없습니다. 다시 연결한 뒤 이 세션을 변경하세요.","resync": "다시 동기화","loading": "원격 기기에서 세션을 불러오는 중…",@@ -6237,9 +6238,8 @@"localMachine": "이 기기","connecting": "연결 중…","tasksLoading": "{{device}}에서 세션을 불러오는 중…",- "tasksLoadFailed": "{{device}}의 세션을 불러오지 못했습니다. 연결을 확인한 후 다시 시도하세요.",- "tasksPartiallyFailed": "{{device}}의 세션을 불러오지 못했습니다. 불러온 내용만 표시합니다.",- "retryTasks": "세션 다시 불러오기",+ "tasksLoadFailed": "지금은 {{device}}의 세션을 불러올 수 없습니다. 자동으로 다시 시도 중…",+ "tasksPartiallyFailed": "지금은 {{device}}의 세션을 불러올 수 없습니다. 자동으로 다시 시도 중이며 불러온 내용만 표시합니다","devicesLoading": "원격 기기를 불러오는 중…","devicesLoadFailed": "원격 기기 목록을 불러오지 못했습니다. 연결을 확인한 후 다시 시도하세요.","devicesPartiallyFailed": "원격 기기 목록을 새로 고치지 못했습니다. 불러온 내용만 표시합니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex ea950d5d6d..f2650997d0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6104,6 +6104,7 @@"remoteSession": {"reconnecting": "与被控设备的连接中断,正在重连…","hostOffline": "被控设备已离线,暂时无法同步",+ "degraded": "与被控设备的连接不稳定,正在自动重试…","actionsUnavailable": "被控设备暂不可用,恢复连接后才能修改该任务","resync": "重新同步","loading": "正在从被控设备加载任务…",@@ -6237,9 +6238,8 @@"localMachine": "本机","connecting": "连接中…","tasksLoading": "正在从 {{device}} 读取任务…",- "tasksLoadFailed": "无法读取 {{device}} 上的任务。请检查连接后重试。",- "tasksPartiallyFailed": "未能读取 {{device}} 上的任务,当前仅显示已加载的内容。",- "retryTasks": "重新读取任务",+ "tasksLoadFailed": "暂时读取不到 {{device}} 上的任务,正在自动重试…",+ "tasksPartiallyFailed": "暂时读取不到 {{device}} 上的任务,正在自动重试;先显示已加载的内容","devicesLoading": "正在读取远程设备…","devicesLoadFailed": "无法读取远程设备列表。请检查连接后重试。","devicesPartiallyFailed": "无法刷新远程设备列表,当前仅显示已加载的内容。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex fe4230422e..37002293d2 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3062,6 +3062,7 @@ interface ElectronAPI {controlledBy: Array<{ deviceId: string; name: string }>;revokedControllers: string[];disabledControlDeviceIds: string[];+ unresponsiveDeviceIds: string[];}>;setEnabled: (enabled: boolean) => Promise<{ remoteControlEnabled: boolean }>;setKeepAwake: (enabled: boolean) => Promise<{ keepAwake: boolean }>;@@ -3117,6 +3118,10 @@ interface ElectronAPI {) => () => void;/** 「保持电脑唤醒」在其它共享 userData 实例被翻转后推送 */onKeepAwakeChanged: (cb: (payload: { keepAwake: boolean }) => void) => () => void;+ /** 控制端:目标设备「无响应」熔断状态翻转(弱网 / 对端卡死;presence 可能仍在线) */+ onResponsivenessChanged: (+ cb: (payload: { deviceId: string; unresponsive: boolean }) => void,+ ) => () => void;/*** 控制端:远程会话镜像的本地冷缓存(main 落 userData,见* main/device-link/mirrorCacheStore.ts)。只做首屏加速、非权威 —— 缓存里没有 live 态,diff --git a/apps/desktop/src/shared/deviceLinkIpc.ts b/apps/desktop/src/shared/deviceLinkIpc.tsindex 5ab2104397..2f78b27ddc 100644--- a/apps/desktop/src/shared/deviceLinkIpc.ts+++ b/apps/desktop/src/shared/deviceLinkIpc.ts@@ -94,6 +94,12 @@ export const DEVICE_LINK_PUSH = {* payload: { keepAwake: boolean } —— renderer 据此同步开关显示状态。*/KEEP_AWAKE_CHANGED: 'device-link:keep-awake-changed',+ /**+ * 控制端:某目标设备的「无响应」熔断状态翻转(连续 invoke 超时判定,弱网 / 对端+ * 卡死;presence 可能仍显示在线)。payload: { deviceId, unresponsive: boolean }。+ * renderer 据此显示「通路不稳定」降级态,恢复(探测拿到真实回包)时自动清除。+ */+ RESPONSIVENESS_CHANGED: 'device-link:responsiveness-changed',} as const;/** 控制本机的控制端信息(同 main/device-link/dispatch.ts ActiveController) */@@ -145,6 +151,11 @@ export interface DeviceLinkState {revokedControllers: string[];/** 本机主动关闭控制的目标设备 deviceId 列表(控制端本地偏好)。 */disabledControlDeviceIds: string[];+ /**+ * 「无响应」熔断中的目标设备(控制端本地判定;初值,后续变化走 RESPONSIVENESS_CHANGED+ * push)。presence 在线但连续 invoke 超时的弱网 / 对端卡死态。+ */+ unresponsiveDeviceIds: string[];}/** LIST_DEVICES 返回的设备视图(同 server REST DeviceView) */diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 8518b3d052..af8c055a25 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -92,6 +92,7 @@ export type IpcErrorCode =| 'DEVICE_LINK_ACCESS_REVOKED' // 目标设备已撤销本机的访问权限(逐设备黑名单)| 'DEVICE_LINK_CONTROL_DISABLED' // 本机已关闭对该目标设备的控制(控制端本地偏好)| 'DEVICE_LINK_TIMEOUT' // 等待远端响应超时+ | 'DEVICE_LINK_DEVICE_UNRESPONSIVE' // 目标设备连续超时被熔断判定无响应(弱网 / 对端卡死),快速失败中| 'DEVICE_LINK_VERSION_MISMATCH' // 两端协议/版本不匹配| 'DEVICE_LINK_MEDIA_TRANSFER_FAILED' // 远程媒体经 OSS 中转失败(出方向附件上传 / 入方向取媒体)| 'REMOTE_WORKDIR_INVALID' // 被控端工作目录路径非法@@ -222,6 +223,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['DEVICE_LINK_ACCESS_REVOKED','DEVICE_LINK_CONTROL_DISABLED','DEVICE_LINK_TIMEOUT',+ 'DEVICE_LINK_DEVICE_UNRESPONSIVE','DEVICE_LINK_VERSION_MISMATCH','DEVICE_LINK_MEDIA_TRANSFER_FAILED','REMOTE_WORKDIR_INVALID',diff --git a/apps/mobile/src/device-link/unresponsiveDevicesStore.ts b/apps/mobile/src/device-link/unresponsiveDevicesStore.tsindex b4424b49da..0e4b51d3b3 100644--- a/apps/mobile/src/device-link/unresponsiveDevicesStore.ts+++ b/apps/mobile/src/device-link/unresponsiveDevicesStore.ts@@ -3,8 +3,9 @@* ---------------------------------------------------------------------------* 结构照 revokedDevicesStore 模板:module 级 Set + subscribe/getSnapshot +* useSyncExternalStore hook,供 UI(首页设备行 failed 态、ConnectionBanner)订阅。- * 状态机本体在 deviceResponsivenessBreaker.ts(纯逻辑,可单测);本文件持有- * module 级单例并暴露 DeviceLinkContext 发送路径用的门禁 / 收尾 helper。+ * 状态机本体在 @cindy/maker-shared/device-responsiveness(纯逻辑,可单测,+ * desktop / mobile 控制端共享);本文件持有 module 级单例并暴露 DeviceLinkContext+ * 发送路径用的门禁 / 收尾 helper。*/import { useSyncExternalStore } from 'react';import { DeviceLinkError, type DeviceLinkErrorCode } from '@cindy/device-link';@@ -13,7 +14,7 @@ import {createDeviceResponsivenessBreaker,type BreakerSendSlot,type BreakerSettleOutcome,-} from '@/device-link/deviceResponsivenessBreaker';+} from '@cindy/maker-shared/device-responsiveness';const unresponsive = new Set<string>();let snapshot: ReadonlySet<string> = new Set();diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex b65a67ead7..f16c216bd6 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -3218,6 +3218,40 @@ describe('DeviceLinkClient', () => {h.client.stop();});+ it('连续 2 次握手超时后窗口翻倍(2×),hello-ack 上线后复位', async () => {+ const warns: string[] = [];+ const h = makeHarness({+ logger: {+ debug: () => {},+ info: () => {},+ warn: (...args: unknown[]) => warns.push(args.map(String).join(' ')),+ error: () => {},+ },+ timing: { handshakeTimeoutMs: 15, reconnectBaseMs: 5, reconnectMaxMs: 10 },+ });+ const handshakeWarns = () => warns.filter((w) => w.includes('handshake not completed'));+ h.client.start();+ // 等满 3 次握手超时:前两次窗口 15ms,第三次(streak≥2)翻倍到 30ms+ for (let i = 0; i < 200 && handshakeWarns().length < 3; i++) await tick(5);+ const seen = handshakeWarns();+ expect(seen.length).toBeGreaterThanOrEqual(3);+ expect(seen[0]).toContain('within 15ms');+ expect(seen[1]).toContain('within 15ms');+ expect(seen[2]).toContain('within 30ms');+ // 上线复位(负载下 ack 可能打在过期 socket 上,按既有模式有界重试)+ for (let i = 0; i < 20 && h.client.getStatus() !== 'online'; i++) {+ h.current().ack();+ await tick();+ }+ expect(h.client.getStatus()).toBe('online');+ // 掉线后下一次握手超时窗口回到基础值+ const before = handshakeWarns().length;+ h.current().emit('close', 1006);+ for (let i = 0; i < 200 && handshakeWarns().length <= before; i++) await tick(5);+ expect(handshakeWarns()[before]).toContain('within 15ms');+ h.client.stop();+ });+it('心跳僵死时无 terminate 实现(RN WebSocket)→ fallback close 回收 socket', async () => {const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });h.client.start();@@ -3226,12 +3260,46 @@ describe('DeviceLinkClient', () => {// 模拟 RN 适配层没有 terminate 的历史形态:删掉后必须退回 close,不能裸遗留(first as { terminate?: () => void }).terminate = undefined;first.ack();- await tick(40);+ // 有界轮询替代固定窗口:CI 负载下(Windows 实测)真实计时器漂移会让 8ms×2 tick+ // 的判死晚于固定 40ms 断言点,语义不变,只是等到事件发生。+ for (let i = 0; i < 100 && first.closed === null; i++) await tick(10);expect(first.closed).not.toBeNull();expect(h.client.getStatus()).toBe('connecting');h.client.stop();});+ it('restartConnection:online(可能半开假活)也强制重建并复位 link 状态;stopped 不拉起', async () => {+ const h = makeHarness({ timing: { reconnectBaseMs: 5, reconnectMaxMs: 10 } });+ h.client.start();+ await tick();+ h.current().ack();+ await tick();+ expect(h.client.getStatus()).toBe('online');+ // 建一条 reliable link:重建后它的 linkReady 必须被复位,host 才会重新 openLink+ await establishInboundReliableLink(h, 'resume-stream', 1, 'ctrl-resume');++ const before = h.sockets.length;+ h.client.restartConnection('system-resume');+ await tick();+ expect(h.sockets.length).toBe(before + 1); // 丢弃旧 socket,新建连接+ h.current().ack();+ await tick();+ expect(h.client.getStatus()).toBe('online');+ // linkReady 已复位:relay 在线 + link 未就绪 → invoke-result 走 legacy 裸帧+ // (若 linkReady 残留 true,这里会被包进 transport wrapper 走旧 stream)+ h.client.sendInvokeResult('ctrl-resume', 'req-after-resume', { ok: true, result: 1 });+ const resent = h.current().sent.filter((e) => e.kind === 'invoke-result');+ expect(resent).toHaveLength(1);+ expect(resent[0]!.payload).toMatchObject({ ok: true, result: 1 });++ h.client.stop();+ const count = h.sockets.length;+ h.client.restartConnection('after-stop');+ await tick(20);+ expect(h.sockets.length).toBe(count); // 生命周期仍归 start/stop 管+ expect(h.client.getStatus()).toBe('stopped');+ });+it('stop 后不再重连', async () => {const h = makeHarness();h.client.start();@@ -3439,4 +3507,102 @@ describe('DeviceLinkClient', () => {h.client.stop();});});++ describe('可靠传输死锁自愈(2026-08-03 线上实锤:被控端回程队列冻结)', () => {+ /** 建 reliable link 后经历一次 relay 断线重连:peer.reliable=true 而 linkReady=false。 */+ async function makeLinkDownPeer(h: Harness, src = 'ctrl-1'): Promise<void> {+ await tick();+ h.current().ack();+ await tick();+ await establishInboundReliableLink(h, `stream-${src}`, 1, src);+ h.current().emit('close', 1006);+ await tick(20); // 退避后重连+ h.current().ack();+ await tick();+ expect(h.client.getStatus()).toBe('online');+ }++ it('B:link 未就绪且 relay 在线时,invoke-result 降级 legacy 裸帧直发', async () => {+ const h = makeHarness({ timing: { reconnectBaseMs: 5, reconnectMaxMs: 10 } });+ h.client.start();+ await makeLinkDownPeer(h);++ h.client.sendInvokeResult('ctrl-1', 'req-legacy', { ok: true, result: 42 });+ const sent = h.current().sent.filter((e) => e.kind === 'invoke-result');+ expect(sent).toHaveLength(1);+ expect(sent[0]!.id).toBe('req-legacy');+ // 裸帧:payload 就是业务 payload,没有 transport wrapper+ expect(sent[0]!.payload).toMatchObject({ ok: true, result: 42 });+ h.client.stop();+ });++ it('A:link 断开状态下 pending 滞留超阈值 → 新帧入队前整队放弃,不再 BACKPRESSURE', async () => {+ const proto = DeviceLinkClient.prototype as unknown as { monotonicNow(): number };+ let nowMs = 1_000_000;+ const clock = vi.spyOn(proto, 'monotonicNow').mockImplementation(() => nowMs);+ try {+ const h = makeHarness({+ timing: { reconnectBaseMs: 5, reconnectMaxMs: 10, stalledLinkPendingMaxAgeMs: 50 },+ });+ h.client.start();+ await makeLinkDownPeer(h);++ // link down:push 只入队不发送,填满 pending(64 条)+ for (let i = 0; i < MAX_TRANSPORT_PENDING_MESSAGES; i++) {+ h.client.sendPush('ctrl-1', 'sessions', { i });+ }+ // 第 65 条:队头未过滞留阈值 → 仍是 BACKPRESSURE(原有语义不变)+ expect(() => h.client.sendPush('ctrl-1', 'sessions', { overflow: true })).toThrow(+ /reliable transport buffer is full/,+ );+ // 滞留超阈值后:入队前整队放弃,新帧不再被顶回+ nowMs += 51;+ expect(() => h.client.sendPush('ctrl-1', 'sessions', { after: true })).not.toThrow();+ h.client.stop();+ } finally {+ clock.mockRestore();+ }+ });++ it('C:link 未就绪收到可靠帧 → 通知 host(同 peer 节流,上线后重置无关)', async () => {+ const proto = DeviceLinkClient.prototype as unknown as { monotonicNow(): number };+ let nowMs = 2_000_000;+ const clock = vi.spyOn(proto, 'monotonicNow').mockImplementation(() => nowMs);+ try {+ const h = makeHarness({ timing: { reconnectBaseMs: 5, reconnectMaxMs: 10 } });+ const notified: string[] = [];+ h.client.onReliableFrameBeforeLink((deviceId) => notified.push(deviceId));+ h.client.start();+ await makeLinkDownPeer(h, 'dev-b');++ const frame = encodeReliableFrames(+ {+ v: PROTOCOL_VERSION,+ kind: 'push',+ src: 'dev-b',+ dst: 'dev-self',+ payload: { channel: 'sessions', payload: {} },+ },+ 'stream-dev-b',+ 1,+ 1,+ )[0]!;+ h.current().push({ ...frame, src: 'dev-b' });+ await tick();+ expect(notified).toEqual(['dev-b']);+ // 节流窗口内的第二帧不重复通知+ h.current().push({ ...frame, src: 'dev-b' });+ await tick();+ expect(notified).toEqual(['dev-b']);+ // 越过节流窗口再来一帧 → 再次通知+ nowMs += 30_001;+ h.current().push({ ...frame, src: 'dev-b' });+ await tick();+ expect(notified).toEqual(['dev-b', 'dev-b']);+ h.client.stop();+ } finally {+ clock.mockRestore();+ }+ });+ });});diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 80bfa81317..62e5df4422 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -531,12 +531,20 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([]);/**- * 逐 channel 的 invoke 隧道超时覆盖(ms)。+ * 逐 channel 的 invoke 隧道超时覆盖(ms),双向使用:*- * client 默认 requestTimeoutMs(30s)对「被控端自身持有同量级执行预算」的 channel- * 会产生对撞:desktop-cmd:run 在被控端有 30s 命令超时 + 5s SIGKILL 宽限,隧道 30s- * 必然先放弃 —— 命令在被控端继续跑完但输出被丢弃,控制端永远看不到 timedOut:true+ * **放宽**:client 默认 requestTimeoutMs(30s)对「被控端自身持有同量级执行预算」的+ * channel 会产生对撞:desktop-cmd:run 在被控端有 30s 命令超时 + 5s SIGKILL 宽限,隧道+ * 30s 必然先放弃 —— 命令在被控端继续跑完但输出被丢弃,控制端永远看不到 timedOut:true* 的正确语义。此表给这类 channel「执行预算 + 回程余量」的覆盖值。+ *+ * **收紧**:listing tier 的轻量 DB 读(sessions:list / sessions:get)在被控端是毫秒级+ * 查询,等满默认 30s 只可能是链路不通。它们又是控制端周期对账的高频 channel,弱网下+ * 每个 30s 超时都占着重试与并发预算(2026-08 实测:单日 2253 次 sessions:list 等满+ * 30s 超时)。给短超时让失败尽快暴露,把「设备无响应」判定交给控制端熔断器。+ * 注意:被控端 dispatch 的 REMOTE_INVOKE_MAX_CLIENT_WAIT_MS 取 max(30s, ...本表),+ * 收紧条目不影响被控端的等待窗口。+ ** client-agnostic:mobile/web 控制端应使用同一映射(与 allowlist 同为协议契约)。*/export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {@@ -547,6 +555,11 @@ export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {'worktree:create': 60_000,// 可能先等待同 sessionId 的晚到 create 释放互斥锁,再执行 git worktree remove。'worktree:discard-precreated': 60_000,+ // listing tier 轻量 DB 读:毫秒级查询,12s 仍等不到只能是链路问题,快速失败喂给熔断器。+ // 12s 同时覆盖被控端冷启动 DB 迁移的常见时长(那类失败是快速返回的 DbClient not ready,+ // 不吃满超时),不会误伤首拉重试。+ 'local-db:sessions:list': 12_000,+ 'local-db:sessions:get': 12_000,};/**diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 7a39e27bab..027d5d71ec 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -42,6 +42,10 @@ import {} from './transport.js';const DUPLICATE_CONNECTION_CLOSE_CODE = 4409;+/** 连续握手超时达到该次数后,握手窗口翻倍(见 armHandshakeTimeout)。 */+const HANDSHAKE_TIMEOUT_WIDEN_AFTER = 2;+/** 「link 未就绪收到可靠帧」通知的 per-peer 节流(见 onReliableFrameBeforeLink)。 */+const STALE_LINK_NOTIFY_THROTTLE_MS = 30_000;const SLOW_REQUEST_WARN_MS = 1_000;const MAX_LEGACY_INBOUND_FRAMES = 128;const MAX_LEGACY_INBOUND_BYTES = 16 * 1024 * 1024;@@ -161,6 +165,15 @@ export interface DeviceLinkTiming {transportMaxRetryAttempts: number;/** presence fire-and-forget 帧命中 WebSocket 背压后的合并重试间隔。 */presenceRetryIntervalMs: number;+ /**+ * link 断开状态下可靠 pending 的最长滞留时间;超过即整队放弃。+ * 防死锁兜底:link-accept/link-open 丢失时,冻结的满队列会把之后所有+ * invoke-result 顶成 BACKPRESSURE(2026-08-03 线上实锤:被控端队列冻结+ * 30+ 分钟,每个执行成功的结果都进 outbox 等 120s 过期丢弃)。滞留超过+ * 该阈值说明这不是「短断线等重放」而是链路重建失败,pending 里的 push+ * 由重连 resync 补偿,invoke-result 的原请求方早已超时,整队放弃无损。+ */+ stalledLinkPendingMaxAgeMs: number;}const DEFAULT_TIMING: DeviceLinkTiming = {@@ -175,6 +188,7 @@ const DEFAULT_TIMING: DeviceLinkTiming = {transportRetryIntervalMs: TRANSPORT_RETRY_INTERVAL_MS,transportMaxRetryAttempts: TRANSPORT_MAX_RETRY_ATTEMPTS,presenceRetryIntervalMs: 500,+ stalledLinkPendingMaxAgeMs: 60_000,};export type DeviceLinkStatus = 'stopped' | 'connecting' | 'online';@@ -344,6 +358,8 @@ export class DeviceLinkClient {private reconnectTimer: ReturnType<typeof setTimeout> | null = null;private reconnectStableTimer: ReturnType<typeof setTimeout> | null = null;private handshakeTimer: ReturnType<typeof setTimeout> | null = null;+ /** 连续握手超时次数;任一次 hello-ack 上线即复位(驱动握手窗口自适应放宽)。 */+ private handshakeTimeoutStreak = 0;private pingTimer: ReturnType<typeof setInterval> | null = null;private pongMisses = 0;/** 当前连接的代号,用于丢弃过期 socket 的事件回调 */@@ -380,6 +396,9 @@ export class DeviceLinkClient {// —— host 订阅 ——private statusHandlers = new Set<(s: DeviceLinkStatus) => void>();+ /** 收到「link 未就绪」可靠帧的通知(30s/peer 节流);host 据此主动重建控制链路。 */+ private staleLinkHandlers = new Set<(deviceId: string) => void>();+ private staleLinkNotifiedAt = new Map<string, number>();private presenceHandlers = new Set<(snap: PresenceSnapshot) => void>();private frameHandlers = new Set<InboundFrameHandler>();private issueHandlers = new Set<(issue: DeviceLinkConnectionIssue | null) => void>();@@ -422,6 +441,29 @@ export class DeviceLinkClient {void this.connect(reason);}+ /**+ * 强制重建连接:与 connectNow 的区别是 **online 也重建**。+ *+ * 供「当前 socket 大概率已经半开假活」的场景(系统睡眠唤醒)使用:睡眠期间+ * TCP 对端早已消失,但本端没收到 close/error、心跳也未累计到判死,状态机仍是+ * online —— connectNow 会直接返回,唤醒后的请求继续写进失效 socket 黑洞约一个+ * 判死周期(~45s)。这里无条件走 connect():它自带丢弃旧 socket、fail 掉+ * in-flight 请求、epoch 递增的完整语义;真在线时代价只是一次 1-2s 的重连抖动,+ * 对刚唤醒的空闲会话可接受。stopped 时不拉起(生命周期仍归 start/stop 管)。+ */+ restartConnection(reason = 'restart-connection'): void {+ if (this.stopped) return;+ this.reconnectAttempt = 0;+ if (this.reconnectTimer) {+ clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ }+ // 主动重建必须复用被动断线的链路层复位:半开期间 linkReady 仍是 true,+ // 不复位会让 host 侧跳过 openLink、旧 stream 帧在新 socket 上被对端丢弃。+ this.resetLinkStateForReconnect();+ void this.connect(reason);+ }+/*** 有界等待连接就绪。online 立即 resolve;否则订阅状态变化,在 timeoutMs 内* 等到 online 就 resolve,超时 / stopped 则 reject(NOT_CONNECTED)。@@ -470,9 +512,11 @@ export class DeviceLinkClient {if (this.stopped) return;this.stopped = true;this.clearTimers();+ this.handshakeTimeoutStreak = 0;this.failAllPending(new DeviceLinkError('NOT_CONNECTED', 'client stopped'));this.clearPeerTransport();this.pendingInboundLinkOffers.clear();+ this.staleLinkNotifiedAt.clear();this.resetLegacyInboundQueue();this.clearPendingPresence();const ws = this.ws;@@ -525,6 +569,31 @@ export class DeviceLinkClient {return () => this.frameHandlers.delete(cb);}+ /**+ * 订阅「收到某设备的可靠帧但本端 link 未就绪」通知(同一设备 30s 节流)。+ * 控制端 host 据此主动重建控制链路(openLink),打破「发送端等 ACK、+ * 接收端等 link」的相互死锁;被控端 host 忽略即可(link 重建由控制端发起)。+ */+ onReliableFrameBeforeLink(cb: (deviceId: string) => void): () => void {+ this.staleLinkHandlers.add(cb);+ return () => this.staleLinkHandlers.delete(cb);+ }++ private notifyReliableFrameBeforeLink(deviceId: string): void {+ if (this.staleLinkHandlers.size === 0) return;+ const now = this.monotonicNow();+ const last = this.staleLinkNotifiedAt.get(deviceId);+ if (last !== undefined && now - last < STALE_LINK_NOTIFY_THROTTLE_MS) return;+ this.staleLinkNotifiedAt.set(deviceId, now);+ for (const cb of this.staleLinkHandlers) {+ try {+ cb(deviceId);+ } catch (err) {+ this.log.error('reliable-frame-before-link handler threw', err);+ }+ }+ }+// ─── 出站 API ───────────────────────────────────────────────────────────────/** 部分更新本机 presence(开关 / busy);离线时静默忽略(重连时 hello 会带全量) */@@ -661,11 +730,23 @@ export class DeviceLinkClient {/** 被控端:回 invoke-result(对应入站 invoke 的 id) */sendInvokeResult(dst: string, requestId: string, payload: InvokeResultPayload): void {const peer = this.peerTransport.get(dst);+ const env: Envelope = { v: PROTOCOL_VERSION, kind: 'invoke-result', id: requestId, dst, payload };+ // 死锁绕行:relay 在线但控制链路未就绪时,result 不进可靠队列等一个可能永远+ // 不来的 link-accept(2026-08-03 线上实锤:队列冻结 30+ 分钟,每个执行成功的+ // 结果都等 120s 过期丢弃),改为 legacy 裸帧即时直发 —— 控制端按 id 配对+ // 不依赖可靠层。送达失败(对端恰好离线)时对端本来就会超时,不比旧行为差。+ // 超过单帧上限的大 result 只能靠可靠层分片,回落入队等 link 重建。+ if (peer?.reliable && !peer.linkReady && this.status === 'online') {+ try {+ this.sendEnvelope(env);+ peer.unlinkedLegacyResponseIds.delete(requestId);+ return;+ } catch (err) {+ if (!(err instanceof DeviceLinkError && err.code === 'PAYLOAD_TOO_LARGE')) throw err;+ }+ }const allowClosedLegacyResponse = peer?.unlinkedLegacyResponseIds.has(requestId) === true;- this.sendPeerEnvelope(- { v: PROTOCOL_VERSION, kind: 'invoke-result', id: requestId, dst, payload },- allowClosedLegacyResponse,- );+ this.sendPeerEnvelope(env, allowClosedLegacyResponse);if (allowClosedLegacyResponse) peer?.unlinkedLegacyResponseIds.delete(requestId);}@@ -994,9 +1075,14 @@ export class DeviceLinkClient {});}- private handleDisconnect(code?: number, reason?: string): void {- this.clearTimers();- this.ws = null;+ /**+ * 连接世代切换时的链路层复位:link 状态、可靠重试计时器、入站 offer、legacy 队列+ * 与跨世代 presence patch。可靠 pending **保留**(等 link 重建后按原 seq 重放)。+ * handleDisconnect(被动断线)与 restartConnection(主动重建)共用 —— 主动重建+ * 若跳过这段,旧 linkReady=true 会让 host 侧误以为 link 仍在、跳过 openLink,+ * 随后用旧 stream 在新 socket 上发帧被对端当未建链帧丢弃(review P2)。+ */+ private resetLinkStateForReconnect(): void {// hello 会从 host 读取完整最新状态;旧连接上尚未发出的覆盖型 patch 不跨世代重放。this.clearPendingPresence();for (const peer of this.peerTransport.values()) {@@ -1008,6 +1094,12 @@ export class DeviceLinkClient {}this.pendingInboundLinkOffers.clear();this.resetLegacyInboundQueue();+ }++ private handleDisconnect(code?: number, reason?: string): void {+ this.clearTimers();+ this.ws = null;+ this.resetLinkStateForReconnect();this.failNonReliablePending(new DeviceLinkError('NOT_CONNECTED', 'relay connection lost'));if (this.stopped) return;if (code === DUPLICATE_CONNECTION_CLOSE_CODE) {@@ -1030,22 +1122,37 @@ export class DeviceLinkClient {}/**- * 握手 watchdog:socket 创建后若在 handshakeTimeoutMs 内没等到 hello-ack(online),+ * 握手 watchdog:socket 创建后若在握手窗口内没等到 hello-ack(online),* 强制关掉这条连接走退避重连。覆盖两类弱网挂起:TCP/TLS 升级挂死(open 不来)、* upgrade 成功但 hello-ack 丢失。+ *+ * 窗口自适应:连续 HANDSHAKE_TIMEOUT_WIDEN_AFTER 次握手超时后窗口翻倍(封顶 2×)。+ * 高 RTT 链路(实测网络响应性可达 ~10s)上 DNS + TCP + TLS + upgrade + hello 可能+ * 恰好超过默认窗口,固定窗口会把「慢但能通」判成永远连不上;翻倍只在连续失败后+ * 生效,一次成功上线即复位,不拖慢正常网络下对真死链的判定。*/private armHandshakeTimeout(epoch: number): void {if (this.handshakeTimer) clearTimeout(this.handshakeTimer);+ const timeoutMs = this.effectiveHandshakeTimeoutMs();this.handshakeTimer = setTimeout(() => {this.handshakeTimer = null;if (this.stopped || epoch !== this.connEpoch || this.status === 'online') return;- this.log.warn(`handshake not completed within ${this.timing.handshakeTimeoutMs}ms, forcing reconnect`);+ this.handshakeTimeoutStreak++;+ this.log.warn(+ `handshake not completed within ${timeoutMs}ms, forcing reconnect (streak=${this.handshakeTimeoutStreak})`,+ );const ws = this.ws;this.ws = null;this.connEpoch++;closeOrTerminate(ws);this.handleDisconnect(1006, 'handshake timeout');- }, this.timing.handshakeTimeoutMs);+ }, timeoutMs);+ }++ private effectiveHandshakeTimeoutMs(): number {+ return this.handshakeTimeoutStreak >= HANDSHAKE_TIMEOUT_WIDEN_AFTER+ ? this.timing.handshakeTimeoutMs * 2+ : this.timing.handshakeTimeoutMs;}private scheduleReconnect(): void {@@ -1299,6 +1406,7 @@ export class DeviceLinkClient {clearTimeout(this.handshakeTimer);this.handshakeTimer = null;}+ this.handshakeTimeoutStreak = 0;const wasOnline = this.status === 'online';this.setStatus('online');this.armReconnectStableReset();@@ -1528,6 +1636,10 @@ export class DeviceLinkClient {// pub/sub 帧可能被投到同 deviceId 的新进程;提前执行会绕过新基线并重复副作用。// 不回 ACK,让仍存活的发送端在链路重新建立后按同 seq 重放。this.log.debug(`dropping reliable payload before link is ready from ${env.src.slice(0, 8)}`);+ // 但发送端还在按可靠流发帧 = 它认为链路该通而本端没有 link ——+ // 光靠沉默丢弃两边会互等(死锁的另一半)。节流通知 host,由控制端+ // 决定是否主动重新 link-open 让双方 stream 重新对齐。+ this.notifyReliableFrameBeforeLink(env.src);return { handled: true };}if (peer.remoteStreamId && peer.remoteStreamId !== parsed.meta.streamId) {@@ -1829,6 +1941,23 @@ export class DeviceLinkClient {return false;}+ // 死锁兜底:link 断开状态下 pending 冻结(不重试、不清理,只等 link 重建),+ // 若 link-accept/link-open 丢失则永远等不到,满队列把所有新帧顶成 BACKPRESSURE。+ // 队头滞留超过阈值即整队放弃 —— push 由重连 resync 补偿,invoke-result 的+ // 原请求方早已超时;放弃后 baseSeq 前移,对端按新基线跳过这些 seq。+ if (!peer.linkReady && peer.pending.size > 0) {+ const oldest = peer.pending.values().next().value as PendingReliableMessage | undefined;+ if (+ oldest+ && this.monotonicNow() - oldest.enqueuedAt > this.timing.stalledLinkPendingMaxAgeMs+ ) {+ this.log.warn(+ `abandoning ${peer.pending.size} stalled reliable frame(s) for peer ${env.dst.slice(0, 8)} (link down > ${this.timing.stalledLinkPendingMaxAgeMs}ms)`,+ );+ this.abandonReliablePending(env.dst, 'reliable link stalled; pending abandoned');+ }+ }+const seq = peer.nextSeq;let frames: Envelope[];let reservedBytes: number;diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex 77130b5f49..e8b0dab385 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -19,6 +19,7 @@"./composer-palette": "./src/composerPalette.ts","./device-list": "./src/deviceList.ts","./device-link-contract": "./src/deviceLinkContract.ts",+ "./device-responsiveness": "./src/deviceResponsiveness.ts","./error-redaction": "./src/errorRedaction.ts","./expanded-block-memory": "./src/expandedBlockMemory.ts","./file-browser": "./src/fileBrowser.ts",diff --git a/apps/mobile/src/__tests__/deviceResponsivenessBreaker.test.ts b/packages/maker-shared/src/__tests__/deviceResponsiveness.test.tssimilarity index 99%rename from apps/mobile/src/__tests__/deviceResponsivenessBreaker.test.tsrename to packages/maker-shared/src/__tests__/deviceResponsiveness.test.tsindex 6f032dc6a7..2954744a7b 100644--- a/apps/mobile/src/__tests__/deviceResponsivenessBreaker.test.ts+++ b/packages/maker-shared/src/__tests__/deviceResponsiveness.test.ts@@ -5,7 +5,7 @@ import {BREAKER_PROBE_BACKOFF_MAX_MS,createDeviceResponsivenessBreaker,type BreakerSendSlot,-} from '@/device-link/deviceResponsivenessBreaker';+} from '../deviceResponsiveness';const DEV = 'dev-1';diff --git a/apps/mobile/src/device-link/deviceResponsivenessBreaker.ts b/packages/maker-shared/src/deviceResponsiveness.tssimilarity index 96%rename from apps/mobile/src/device-link/deviceResponsivenessBreaker.tsrename to packages/maker-shared/src/deviceResponsiveness.tsindex 06be951469..fa23e64a04 100644--- a/apps/mobile/src/device-link/deviceResponsivenessBreaker.ts+++ b/packages/maker-shared/src/deviceResponsiveness.ts@@ -1,9 +1,13 @@/**- * deviceResponsivenessBreaker.ts — per-device「目标设备无响应」熔断器(纯逻辑,node 可单测)。+ * deviceResponsiveness.ts — per-device「目标设备无响应」熔断器(纯逻辑,node 可单测)。* ---------------------------------------------------------------------------+ * desktop / mobile 控制端共享(原 apps/mobile/src/device-link/deviceResponsivenessBreaker.ts,+ * 2026-08 提炼到 maker-shared 供桌面控制端复用;两端各自持有 UI 镜像 store 与接线)。+ ** 事故链背景(2026-07 生产):桌面端进程活着(relay 心跳 / presence 全正常)但内部* 卡死(DB gate 失败),invoke 永不回包。手机端每个请求都等满超时,重试链 + 多触发源* 重放把请求堆成风暴,JS 线程停摆(实测最长 114s),期间连超时 timer 都被冻结。+ * 弱网场景同理:请求到不了对端或响应回不来,同样表现为连续 INVOKE_TIMEOUT。* 本熔断器把「对同一台无响应设备的持续请求」收敛为周期性单飞探测:** - 失败信号:**仅** INVOKE_TIMEOUT(等满超时无回包)计入连续失败;