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): invoke-result outbox 全量轮跳过 presence 显式离线的控制端 (#2189)
Dash91f1de4e2f2c
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.tsindex ad7033d00e..5202a51263 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts@@ -33,7 +33,12 @@ vi.mock('../settings-store', () => ({readDeviceLinkSettings: () => deviceLinkSettings.value,}));-import { __testing, flushRemoteInvokeResultOutboxOnReconnect } from '../dispatch';+import {+ __testing,+ flushRemoteInvokeResultOutboxOnReconnect,+ handleControllerOffline,+ setDispatchPresenceOfflineCheck,+} from '../dispatch';function mkClient(over: Partial<{@@ -237,6 +242,173 @@ describe('[2] outbox 离线不自旋,上线事件驱动投递', () => {});});+describe('[5] outbox flush 的 presence 显式离线门禁', () => {+ it('presence 明确离线的控制端本轮跳过(条目保留),在线控制端照常投递;设备回归后可投', () => {+ // 门禁要掐掉的是**同一连接代内**的稳态盲发:relay 在线时全量轮每 500ms 跑一次+ // (REMOTE_INVOKE_RESULT_OUTBOX_RETRY_MS),对 presence 已明说离线的控制端就是+ // 2 帧/秒的 DEVICE_OFFLINE 稳定输出,直到 TTL 出清——纯粹喂 relay 聚合背压。+ // 门禁按 src 隔离:一个离线控制端不影响其它控制端本轮的投递。+ const offline = new Set(['ctrl-offline']);+ setDispatchPresenceOfflineCheck((id) => offline.has(id));+ const sendInvokeResult = vi.fn().mockImplementation(() => {+ throw notConnected();+ });+ const client = mkClient({ sendInvokeResult });+ __testing.setActiveClient(client as never);++ // 两个控制端各一条 outbox 积压(首发失败入队)+ for (const src of ['ctrl-offline', 'ctrl-online']) {+ __testing.sendInvokeResultSafe(+ client as never,+ src,+ `req-${src}`,+ { ok: true, result: 1 },+ 'local-db:sessions:list',+ );+ }+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(2);++ // ws-online 全量 flush:离线者被门禁跳过(不 trySend),在线者投递成功+ sendInvokeResult.mockImplementation(() => {});+ const callsBefore = sendInvokeResult.mock.calls.length;+ flushRemoteInvokeResultOutboxOnReconnect();+ const flushed = sendInvokeResult.mock.calls.slice(callsBefore);+ expect(flushed.map((c) => c[0])).toEqual(['ctrl-online']);+ // 离线者的条目保留(TTL 照常),没有被丢弃+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);++ // 设备回归(presence 翻转):下一次 flush 正常投递+ offline.clear();+ flushRemoteInvokeResultOutboxOnReconnect();+ expect(sendInvokeResult).toHaveBeenLastCalledWith(+ 'ctrl-offline',+ 'req-ctrl-offline',+ expect.anything(),+ );+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(0);+ });++ it('定向 flush(link-open 触发)不受门禁约束:对端已主动建链是更强的在线证据', () => {+ // review P2:presence 短暂滞后/误报为 offline 时,不得把「对端刚 link-open」+ // 这条恢复事件一并拦死——定向轮(onlySrc)必须照常投递。+ setDispatchPresenceOfflineCheck(() => true); // 极端:判据说所有设备都离线+ const sendInvokeResult = vi.fn().mockImplementationOnce(() => {+ throw notConnected();+ });+ const client = mkClient({ sendInvokeResult });+ __testing.setActiveClient(client as never);+ __testing.sendInvokeResultSafe(+ client as never,+ 'ctrl-a',+ 'req-1',+ { ok: true, result: 1 },+ 'local-db:sessions:list',+ );+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);++ // 全量轮:被门禁挡住(条目保留)+ flushRemoteInvokeResultOutboxOnReconnect();+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);++ // 定向轮(link-open 路径):不看门禁,直接投递+ __testing.flushRemoteInvokeResultOutbox('ctrl-a');+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(0);+ });++ it('presence 滞后为 offline 但控制端已 link-open 回归:全量轮不再拦它(定向轮失败后的无参重试照样投递)', () => {+ // codex review 同族第 3 次指出的缺口:定向轮首发被 BACKPRESSURE 打回后,末尾排的+ // 重试是**无参全量轮**、丢掉 onlySrc 证据 —— 判据若只看 presence,这个已建链的+ // peer 会被持续跳过到 presence 更新或 TTL 丢结果。判据带上 accepted link 后 fail-open。+ setDispatchPresenceOfflineCheck(() => true); // presence 停留在陈旧的 offline+ const sendInvokeResult = vi.fn().mockImplementation(() => {+ throw backpressure();+ });+ const client = mkClient({ sendInvokeResult });+ __testing.setActiveClient(client as never);+ __testing.sendInvokeResultSafe(+ client as never,+ 'ctrl-a',+ 'req-1',+ { ok: true, result: 1 },+ 'local-db:sessions:list',+ );+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);++ // 还没有 accepted link:全量轮被门禁挡住(不 trySend)+ let calls = sendInvokeResult.mock.calls.length;+ flushRemoteInvokeResultOutboxOnReconnect();+ expect(sendInvokeResult.mock.calls.length).toBe(calls);++ // 控制端 link-open 回归 → accepted link 成立;它触发的定向轮仍被背压打回,+ // 条目保留、末尾排下无参全量重试。+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-1', undefined);+ expect(__testing.getActiveControllers().map((c) => c.deviceId)).toEqual(['ctrl-a']);+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);++ // 无参全量重试:presence 判据仍说离线,但 accepted link 是更新的可达证据 → 放行+ sendInvokeResult.mockImplementation(() => {});+ calls = sendInvokeResult.mock.calls.length;+ vi.advanceTimersByTime(500);+ expect(sendInvokeResult.mock.calls.length).toBeGreaterThan(calls);+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(0);+ });++ it('presence 宣告离线拆掉 accepted link 后:全量轮重新受门禁约束', () => {+ // 可达证据不得比链路活得更久 —— presence 说离线时 index.ts 会调+ // handleControllerOffline 拆掉该控制端的 accepted link 与订阅,此后必须回到+ // 「presence 说了算」,否则一次历史建链会永久豁免门禁。+ setDispatchPresenceOfflineCheck(() => true);+ const sendInvokeResult = vi.fn().mockImplementationOnce(() => {+ throw notConnected();+ });+ const client = mkClient({ sendInvokeResult });+ __testing.setActiveClient(client as never);+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-1', undefined);+ __testing.sendInvokeResultSafe(+ client as never,+ 'ctrl-a',+ 'req-1',+ { ok: true, result: 1 },+ 'local-db:sessions:list',+ );+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);++ // accepted link 在场:全量轮放行+ sendInvokeResult.mockImplementation(() => {+ throw notConnected();+ });+ let calls = sendInvokeResult.mock.calls.length;+ flushRemoteInvokeResultOutboxOnReconnect();+ expect(sendInvokeResult.mock.calls.length).toBeGreaterThan(calls);++ // presence 宣告离线 → 拆链:证据随链路一起消失,门禁重新生效+ handleControllerOffline('ctrl-a');+ calls = sendInvokeResult.mock.calls.length;+ flushRemoteInvokeResultOutboxOnReconnect();+ expect(sendInvokeResult.mock.calls.length).toBe(calls);+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);+ });++ it('presence 判据未接线(null)时 fail-open:行为与门禁不存在时一致', () => {+ // __testing.reset() 已把判据清空;不接线直接 flush,验证默认路径不受影响+ const sendInvokeResult = vi.fn().mockImplementationOnce(() => {+ throw notConnected();+ });+ const client = mkClient({ sendInvokeResult });+ __testing.setActiveClient(client as never);+ __testing.sendInvokeResultSafe(+ client as never,+ 'ctrl-a',+ 'req-1',+ { ok: true, result: 1 },+ 'local-db:sessions:list',+ );+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(1);+ flushRemoteInvokeResultOutboxOnReconnect();+ expect(__testing.remoteInvokeResultOutboxSize()).toBe(0);+ });+});+describe('[3] outbox 保留时长按 channel 收窄', () => {it('锁「预算 ×2、封顶 120s」联动:表内 channel 跟随共享表,缺省 30s→60s', () => {// 联动语义从共享表推导,不再硬编码结果值——此断言曾在 #1418/#1477 并行开发diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 3270a7de1d..629217f730 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -391,6 +391,48 @@ function projectInvokeResultForTunnel(/** 持有 client 的引用(转发 push 用);wireInboundDispatch 接入时设置。 */let activeClient: DeviceLinkClient | null = null;+/**+ * presence「显式离线」判据(index.ts 接线,那里持有权威 presence 视图):返回 true+ * 仅当**当代** presence 明确宣告该设备离线;未知一律返回 false —— fail-open,不把+ * 恢复窗口的首发拦死(判据刻意不跨连接代记忆,理由见 index.ts 的同名函数注释)。+ *+ * outbox **全量** flush 据此跳过注定 DEVICE_OFFLINE 的盲发:relay 在线时全量轮每+ * REMOTE_INVOKE_RESULT_OUTBOX_RETRY_MS(500ms)跑一次,对 presence 已明说离线的+ * 控制端就是 2 帧/秒的稳定无效出站,一直持续到 TTL 出清——只喂 relay 聚合背压+ * (2026-08-08 事故的第四层失效面,见 docs/dev-rules/remote-and-mobile-adaptation.md)。+ * 条目保留不丢,恢复由该控制端 link-open 触发的定向 flush+ * (flushRemoteInvokeResultOutbox(src),不受本门禁约束)与 presence 翻回 online 后的+ * 全量轮接棒。+ */+let presenceOfflineCheck: ((deviceId: string) => boolean) | null = null;++export function setDispatchPresenceOfflineCheck(+ check: ((deviceId: string) => boolean) | null,+): void {+ presenceOfflineCheck = check;+}++/**+ * 门禁的唯一不变量:**只在 relay 确定路由不到时抑制发送**;同代内任何比 presence+ * 更新的可达证据都必须让位给发送(fail-open),且该证据不得跨连接代存活。+ *+ * 这里的「更新的证据」就是 `acceptedLinkControllers`——它记录「link-accept 已成功、+ * 尚未显式 close」的控制端,而它的增删边正好覆盖两侧:link-accept 成功即加入+ * (那一刻 relay 确实路由到了它),link-close / 撤权 / presence 宣告离线+ * (handleControllerOffline)/ teardown 立刻移除。于是「有 accepted link」天然表示+ * 「已建链,且 presence 此后没有再说它离线」——不需要任何新状态或时间戳,证据由+ * 权威源自己回收。+ *+ * 它关掉的具体缺口(codex review,同族第 3 次):presence 在同一代内滞后停留在+ * false、控制端已 link-open 回归时,定向 flush 的首发若被 BACKPRESSURE 打回,末尾+ * 排的重试是**无参全量轮**、丢掉 onlySrc 证据,于是这个已建链的 peer 会被持续跳过+ * 到 presence 更新或 TTL 丢结果。判据里带上 accepted link 后,那一轮直接 fail-open。+ */+function isKnownUnroutable(deviceId: string): boolean {+ if (!presenceOfflineCheck?.(deviceId)) return false;+ return !acceptedLinkControllers.has(deviceId);+}+/** 订阅集合变化时一次性通知 host UI 控制态与更新重启安全态。 */type ControllersChangedListener = (controllers: ActiveController[],@@ -1681,6 +1723,15 @@ function flushRemoteInvokeResultOutbox(onlySrc?: string): void {// 离线轮只做上面的 TTL 出清:trySend 必然 NOT_CONNECTED,不空转、不刷日志。if (!relayOnline) continue;if (blockedPeers.has(queued.src)) continue;+ // presence 已明确宣告该控制端离线、且它当下也没有 accepted link:全量轮跳过盲发+ // (每 500ms 一帧必弹 DEVICE_OFFLINE,只喂 relay 聚合背压),条目保留、TTL 照常。+ // 判据与 fail-open 边界见 isKnownUnroutable。门禁只作用于全量轮(onlySrc 为空):+ // 定向轮由 link-open 触发,「对端刚主动建链」是比 presence 更强、更新的在线证据,+ // presence 短暂滞后/误报不得把这条恢复事件一并拦死(review P2)。+ if (!onlySrc && isKnownUnroutable(queued.src)) {+ blockedPeers.add(queued.src);+ continue;+ }const attempt = trySendInvokeResult(client,queued.src,@@ -2274,6 +2325,7 @@ export const __testing = {clearAllSessionActivityStages();cancelAllLinkAcceptRetries();setBroadcastTapListener(null);+ presenceOfflineCheck = null;},getActiveControllers,getUpdateRelaunchControllers,diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 19c8a86a08..bfa9e42880 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -67,6 +67,7 @@ import {forgetControllerInvokeState,handleControllerOffline,purgeRevokedController,+ setDispatchPresenceOfflineCheck,} from './dispatch';import {clearControllerPlatforms,@@ -245,6 +246,22 @@ const RESPONSIVENESS_PROBE_TICK_MS = 5_000;*/const presenceOnlineByDevice = new Map<string, boolean>();+/**+ * 发送门禁判据:**当代 presence 已明确宣告**该设备离线(供 dispatch 的+ * invoke-result outbox 全量轮跳过盲发,见 setDispatchPresenceOfflineCheck)。+ *+ * 刻意只读当代视图、不做任何跨连接代的记忆:+ * - presence-changed 是**只发给当时在线设备的增量广播,新连接没有全量重放**+ * (mobile 侧同一结论已固化在 presenceRecovery.resetPresenceAvailabilityForConnection+ * 的注释里)。断线期间恢复上线的设备,重连后不会有任何 presence 帧来纠正一条+ * 转存下来的 offline 结论——跨代保留会把它永久挡在门外,拿不到订阅与在途回包。+ * - 因此门禁的作用域被限定为「同一连接代内、presence 已明说离线」这一段:视图为空+ * (刚重连、尚无首帧 presence)一律 fail-open。它是减量优化,不是安全边界。+ */+function isPresenceExplicitlyOffline(deviceId: string): boolean {+ return presenceOnlineByDevice.get(deviceId) === false;+}+const presenceNameByDevice = new Map<string, string>();let unsubscribeDictionaryChanged: (() => void) | null = null;@@ -563,6 +580,8 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v// 被控端:接线入站隧道(link-open / invoke / link-close → 本机 handler dispatch)wireInboundDispatch(client);+ // outbox flush 的 presence 显式离线门禁(运行期接线,模块顶层会撞 import 环 TDZ)+ setDispatchPresenceOfflineCheck(isPresenceExplicitlyOffline);// busy presence:每 5s 探一次本机是否有 turn 在跑,变化才上报(dedupe by value)startBusyReporting();@@ -904,6 +923,15 @@ function replayActiveSubscriptions(reason: string, deviceId?: string): void {`device-link replay subscriptions (${reason}): devices=${refs.length} topics=${topicCount}`,);for (const { deviceId, topics } of refs) {+ // 这里**不套** presence 离线门禁(2026-08-08 review 的收敛结论,别再加回来):+ // - 唯一的广播型调用者是 ws-online,而它跑在「非 online 时清空视图」之后、+ // 本代首帧 presence 之前,当代 presence 必然为空 → 门禁在此恒不成立,是死码;+ // - 其余三个调用者都是定向的(link-reopen / responsiveness-recovered /+ // presence-online),各自的触发证据(收到 link-accept、探测 invoke 刚成功、+ // presence 刚翻成 online)都比 presence 视图更新更强,拿更旧的 presence 去+ // 拦它们只会把恢复事件拦死——与 dispatch 侧「定向 flush 不受门禁约束」同构。+ // 已知离线目标的无效 subscribe 由 replayDeviceSubscription 的重试前置门+ // (presenceAvailableByDevice !== true)在当代内收敛,首发放行一帧即可。replayDeviceSubscription(deviceId, topics, reason, 0);}}