Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 取消断线后排队刷新并补充设备互联来源统计 (#5097)
DavidShenXDfd92cc75ff75
diff --git a/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts b/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.tsnew file mode 100644index 0000000000..42268f5fa0--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts@@ -0,0 +1,189 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { DeviceLinkError } from '@cindy/device-link';+import type { DeviceLinkIpcDeps } from '../ipc';+import { createDeviceLinkIpcDiagnostics } from '../ipcDiagnostics';+import { createDeviceUnresponsiveError } from '../responsivenessTracker';++beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++function harness() {+ const emit = vi.fn();+ const diagnostics = createDeviceLinkIpcDiagnostics(emit);+ const invoke = vi.fn<DeviceLinkIpcDeps['invoke']>().mockResolvedValue({ ok: true, result: [] });+ const subscribe = vi+ .fn<DeviceLinkIpcDeps['subscribe']>()+ .mockResolvedValue({ ok: true, result: null });+ const unsubscribe = vi+ .fn<DeviceLinkIpcDeps['unsubscribe']>()+ .mockResolvedValue({ ok: true, result: null });+ const openLink = vi.fn<DeviceLinkIpcDeps['openLink']>();+ const deps = { invoke, subscribe, unsubscribe, openLink } as unknown as DeviceLinkIpcDeps;+ return {+ emit,+ diagnostics,+ invoke,+ subscribe,+ unsubscribe,+ openLink,+ deps,+ observed: diagnostics.forWindow(deps, 10),+ };+}++const CHANNEL = 'local-db:sessions:list';++describe('device-link IPC diagnostics', () => {+ it('aggregates a failure storm and successes without changing transport calls or errors', async () => {+ const h = harness();+ const error = new DeviceLinkError('BACKPRESSURE', 'private error');+ h.invoke.mockRejectedValue(error);+ for (let i = 0; i < 1000; i++) {+ await expect(h.observed.invoke('private-peer', CHANNEL, [])).rejects.toBe(error);+ }+ expect(h.emit).toHaveBeenCalledTimes(1);+ expect(h.emit).toHaveBeenCalledWith(+ 'transport first failure',+ expect.objectContaining({ code: 'BACKPRESSURE', completed: 1 }),+ );+ const result = { ok: true as const, result: ['private response'] };+ h.invoke.mockResolvedValue(result);+ await expect(h.observed.invoke('private-peer', CHANNEL, ['private argument'])).resolves.toBe(+ result,+ );+ expect(h.invoke).toHaveBeenCalledTimes(1001);+ await vi.advanceTimersByTimeAsync(30_000);+ expect(h.emit).toHaveBeenCalledTimes(3);+ expect(h.emit).toHaveBeenCalledWith(+ 'transport summary',+ expect.objectContaining({ code: 'BACKPRESSURE', completed: 1000, elapsedMs: 30_000 }),+ );+ expect(h.emit).toHaveBeenCalledWith(+ 'transport summary',+ expect.objectContaining({ code: 'OK', completed: 1 }),+ );+ expect(JSON.stringify(h.emit.mock.calls)).not.toContain('private');+ expect(vi.getTimerCount()).toBe(0);+ h.invoke.mockRejectedValue(error);+ await expect(h.observed.invoke('private-peer', CHANNEL, [])).rejects.toBe(error);+ expect(h.emit).toHaveBeenCalledTimes(4);+ h.diagnostics.flush();+ });++ it('distinguishes raw causes, peers, windows and subscription operations', async () => {+ const h = harness();+ for (const code of ['NOT_CONNECTED', 'LINK_NOT_OPEN', 'PEER_RESET', 'BACKPRESSURE'] as const) {+ h.invoke.mockRejectedValueOnce(new DeviceLinkError(code, 'private'));+ await expect(h.observed.invoke('peer-a', CHANNEL, [])).rejects.toMatchObject({ code });+ }+ h.subscribe.mockResolvedValue({+ ok: false,+ error: { code: 'DEVICE_OFFLINE', message: 'private' },+ });+ await h.observed.subscribe('peer-a', ['private-topic']);+ await h.diagnostics.forWindow(h.deps, 20).subscribe('peer-a', ['private-topic']);+ await h.observed.unsubscribe('peer-b', ['private-topic']);+ h.openLink.mockRejectedValue(new DeviceLinkError('REMOTE_DISABLED', 'private'));+ await expect(h.observed.openLink('peer-a')).rejects.toMatchObject({ code: 'REMOTE_DISABLED' });+ h.diagnostics.flush();+ const rows = h.emit.mock.calls+ .filter(([event]) => event === 'transport summary')+ .map(([, row]) => row);+ expect(rows).toHaveLength(8);+ expect(new Set(rows.map((row) => row.peer)).size).toBe(2);+ expect(rows.filter((row) => row.operation === 'subscribe').map((row) => row.windowId)).toEqual([+ 10, 20,+ ]);+ expect(rows.filter((row) => row.operation === 'invoke').map((row) => row.code)).toEqual([+ 'NOT_CONNECTED',+ 'LINK_NOT_OPEN',+ 'PEER_RESET',+ 'BACKPRESSURE',+ ]);+ expect(JSON.stringify(rows)).not.toMatch(/private|peer-a|peer-b/);+ });++ it.each(['invoke', 'subscribe'] as const)(+ 'records %s circuit-breaker rejection under its actual local code',+ async (operation) => {+ const h = harness();+ const error = createDeviceUnresponsiveError('private-peer');+ h[operation].mockRejectedValue(error);+ const run = () =>+ operation === 'invoke'+ ? h.observed.invoke('private-peer', CHANNEL, [])+ : h.observed.subscribe('private-peer', ['private-topic']);+ await expect(run()).rejects.toBe(error);+ await expect(run()).rejects.toBe(error);+ expect(h.emit).toHaveBeenCalledTimes(1);+ expect(h.emit).toHaveBeenCalledWith(+ 'transport first failure',+ expect.objectContaining({+ operation,+ code: 'DEVICE_UNRESPONSIVE',+ completed: 1,+ }),+ );+ h.diagnostics.flush();+ expect(h.emit).toHaveBeenCalledWith(+ 'transport summary',+ expect.objectContaining({+ operation,+ code: 'DEVICE_UNRESPONSIVE',+ completed: 2,+ }),+ );+ expect(JSON.stringify(h.emit.mock.calls)).not.toMatch(/private|circuit open|UNKNOWN/);+ },+ );++ it('preserves unknown failures while redacting unknown channels and codes', async () => {+ const h = harness();+ const unknown = Object.assign(new Error('private body'), { code: 'private-code' });+ h.invoke.mockRejectedValueOnce(unknown);+ await expect(h.observed.invoke('private-peer', 'private-channel', [])).rejects.toBe(unknown);+ expect(h.emit).toHaveBeenCalledWith(+ 'transport first failure',+ expect.objectContaining({ code: 'UNKNOWN', channel: 'UNKNOWN' }),+ );+ h.invoke.mockRejectedValueOnce(new Error('[DEVICE_LINK_NOT_CONNECTED] client not initialized'));+ await expect(h.observed.invoke('private-peer', CHANNEL, [])).rejects.toThrow(+ 'client not initialized',+ );+ expect(h.emit).toHaveBeenCalledWith(+ 'transport first failure',+ expect.objectContaining({ code: 'MAPPED_NOT_CONNECTED' }),+ );+ expect(JSON.stringify(h.emit.mock.calls)).not.toContain('private');+ h.diagnostics.flush();+ });++ it('bounds cardinality and reports overflow without flooding first-failure logs', async () => {+ const h = harness();+ h.invoke.mockRejectedValue(new DeviceLinkError('NOT_CONNECTED', 'private'));+ for (let i = 0; i < 1000; i++) {+ await expect(h.observed.invoke(`peer-${i}`, CHANNEL, [])).rejects.toMatchObject({+ code: 'NOT_CONNECTED',+ });+ }+ expect(h.emit).toHaveBeenCalledTimes(64);+ h.diagnostics.flush();+ expect(h.emit).toHaveBeenCalledTimes(129);+ expect(h.emit).toHaveBeenLastCalledWith(+ 'transport summary overflow',+ expect.objectContaining({ overflowCompleted: 936, overflowFailures: 936 }),+ );+ });++ it('does not let a logging failure alter the result or thrown error', async () => {+ const h = harness();+ h.emit.mockImplementation(() => {+ throw new Error('log unavailable');+ });+ const error = new DeviceLinkError('NOT_CONNECTED', 'original');+ h.invoke.mockRejectedValueOnce(error);+ await expect(h.observed.invoke('peer', CHANNEL, [])).rejects.toBe(error);+ await expect(h.observed.invoke('peer', CHANNEL, [])).resolves.toEqual({ ok: true, result: [] });+ expect(() => h.diagnostics.flush()).not.toThrow();+ });+});diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex 64ecbc48ed..28866f60c6 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -15,6 +15,8 @@ const h = vi.hoisted(() => ({handlers: new Map<string, (...args: unknown[]) => unknown>(),trusted: true,canUseDeviceLink: true,+ diagnosticsInfo: vi.fn(),+ quitHandlers: new Map<string, { fn: () => void; phase: string }>(),cache: {readMessages: vi.fn(async () => [] as Record<string, unknown>[]),readMessagesWithInvalidation: vi.fn(async () => ({@@ -42,7 +44,12 @@ vi.mock('electron', () => ({},}));vi.mock('../../logger', () => ({- createLogger: () => ({ warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }),+ createLogger: (scope: string) => ({ warn: vi.fn(), error: vi.fn(), info: scope === 'device-link:ipc-diagnostics' ? h.diagnosticsInfo : vi.fn(), debug: vi.fn() }),+}));+vi.mock('../../lifecycle', () => ({+ onQuit: (name: string, fn: () => void, phase: string) => {+ h.quitHandlers.set(name, { fn, phase });+ },}));// 读路径要比对 owner 作用域路径(账号边界复核),这里给个稳定值即可。vi.mock('../../appSessionState', () => ({@@ -88,6 +95,8 @@ vi.mock('../../clientEndpointsService.js', () => ({vi.mock('../index', () => ({getDeviceLinkStatus: () => 'online',getDeviceLinkConnectionIssue: () => null,+ isDeviceLinkStandby: () => false,+ getUnresponsiveDeviceIds: () => [],clearDeviceResponsiveness: vi.fn(),setRemoteControlEnabled: vi.fn(),setKeepAwakeEnabled: vi.fn(),@@ -148,17 +157,18 @@ vi.mock('../subscriptionRefcount', () => ({import { DEVICE_LINK_INVOKE } from '../../../shared/deviceLinkIpc';import { registerDeviceLinkIpc } from '../ipc';-import { REMOTE_INVOKE_ALLOWLIST } from '@cindy/device-link';+import { DeviceLinkError, REMOTE_INVOKE_ALLOWLIST } from '@cindy/device-link';import { DESKTOP_LOCAL } from '../../../shared/remoteDesktop';import {setRemoteControlEnabled,revokeController,restoreController,disconnectAllControllers,+ remoteInvoke,} from '../index';import { setDeviceControlEnabled } from '../settings-store';-const EVENT = {} as Electron.IpcMainInvokeEvent;+const EVENT = { sender: { id: 42 } } as Electron.IpcMainInvokeEvent;/** 五个 channel 与一份能过运行期校验的最小 payload。 */const MIRROR_CACHE_CALLS: Array<[string, unknown]> = [@@ -185,11 +195,57 @@ async function call(channel: string, payload: unknown): Promise<unknown> {beforeEach(() => {vi.clearAllMocks();h.handlers.clear();+ h.quitHandlers.clear();h.trusted = true;h.canUseDeviceLink = true;registerDeviceLinkIpc();});+it.each([1_000, 30_000])('flushes completed calls on quit after %i ms without duplicate summaries', async (elapsed) => {+ vi.useFakeTimers();+ try {+ const payload = { deviceId: 'private-peer', channel: 'local-db:sessions:list', args: [] };+ vi.mocked(remoteInvoke).mockResolvedValueOnce({ ok: true, result: [] });+ await call(DEVICE_LINK_INVOKE.INVOKE, payload);+ vi.mocked(remoteInvoke).mockRejectedValueOnce(new DeviceLinkError('NOT_CONNECTED', 'offline'));+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, payload)).rejects.toThrow('DEVICE_LINK_NOT_CONNECTED');+ await vi.advanceTimersByTimeAsync(elapsed);+ const quit = h.quitHandlers.get('device-link-ipc-diagnostics');+ expect(quit?.phase).toBe('sync');+ quit!.fn();+ const summaries = h.diagnosticsInfo.mock.calls.filter(([event]) => event === 'transport summary');+ expect(summaries).toHaveLength(2);+ expect(summaries.map(([, fields]) => [fields.code, fields.completed])).toEqual([+ ['OK', 1], ['NOT_CONNECTED', 1],+ ]);+ const count = h.diagnosticsInfo.mock.calls.length;+ quit!.fn();+ await vi.advanceTimersByTimeAsync(30_000);+ expect(h.diagnosticsInfo).toHaveBeenCalledTimes(count);+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ }+});++it('records the originating window and raw error before the IPC adapter maps it', async () => {+ vi.useFakeTimers();+ try {+ vi.mocked(remoteInvoke).mockRejectedValueOnce(new DeviceLinkError('BACKPRESSURE', 'private failure'));+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, {+ deviceId: 'private-peer', channel: 'local-db:sessions:list', args: ['private argument'],+ })).rejects.toThrow('DEVICE_LINK_NOT_CONNECTED');+ expect(h.diagnosticsInfo).toHaveBeenCalledWith('transport first failure', expect.objectContaining({+ windowId: 42, operation: 'invoke', channel: 'local-db:sessions:list', code: 'BACKPRESSURE', completed: 1,+ }));+ expect(JSON.stringify(h.diagnosticsInfo.mock.calls)).not.toContain('private');+ await vi.advanceTimersByTimeAsync(30_000);+ expect(h.diagnosticsInfo).toHaveBeenCalledWith('transport summary', expect.objectContaining({ code: 'BACKPRESSURE', completed: 1 }));+ } finally {+ vi.useRealTimers();+ }+});+describe('mirror-cache IPC 授权边界', () => {it('五个 channel 都已注册', () => {for (const [channel] of MIRROR_CACHE_CALLS) {diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex b2d3c76336..bc618a586f 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -97,6 +97,8 @@ import {resetAll as resetSubscriptionRefcount,} from './subscriptionRefcount';import { createLogger } from '../logger';+import { onQuit } from '../lifecycle';+import { createDeviceLinkIpcDiagnostics } from './ipcDiagnostics';import { getAppCapabilities } from '../appCapabilities.js';const log = createLogger('device-link:ipc');@@ -1293,6 +1295,13 @@ export async function retryUnsubscribeAfterWindowGone(// ─── 注册(Electron adapter)──────────────────────────────────────────────────export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()): void {+ const diagnosticsLog = createLogger('device-link:ipc-diagnostics');+ const diagnostics = createDeviceLinkIpcDiagnostics((event, fields) =>+ diagnosticsLog.info(event, fields),+ );+ // Submit the final partial interval at shutdown start, giving the async log+ // writer the subsequent cleanup phases to drain before app.exit().+ onQuit('device-link-ipc-diagnostics', diagnostics.flush, 'sync');const deviceCodes = new LocalDeviceCodeSessions();const deviceCodeScope = (event: import('electron').IpcMainInvokeEvent): string => {assertTrustedAppRendererEvent(event);@@ -1382,20 +1391,20 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):const p = (payload ?? {}) as { deviceId?: unknown };return handleDeleteDevice(deps, p.deviceId);});- ipcMain.handle(DEVICE_LINK_INVOKE.OPEN_LINK, (_e, payload: unknown) => {+ ipcMain.handle(DEVICE_LINK_INVOKE.OPEN_LINK, (e, payload: unknown) => {requireDeviceLinkCapability();const p = (payload ?? {}) as { deviceId?: unknown };- return handleOpenLink(deps, p.deviceId);+ return handleOpenLink(diagnostics.forWindow(deps, e.sender.id), p.deviceId);});ipcMain.handle(DEVICE_LINK_INVOKE.CLOSE_LINK, (_e, payload: unknown) => {requireDeviceLinkCapability();const p = (payload ?? {}) as { deviceId?: unknown };return handleCloseLink(deps, p.deviceId);});- ipcMain.handle(DEVICE_LINK_INVOKE.INVOKE, (_e, payload: unknown) => {+ ipcMain.handle(DEVICE_LINK_INVOKE.INVOKE, (e, payload: unknown) => {requireDeviceLinkCapability();const p = (payload ?? {}) as { deviceId?: unknown; channel?: unknown; args?: unknown };- return handleInvoke(deps, p.deviceId, p.channel, p.args);+ return handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args);});// 多窗口订阅引用计数:每个发起订阅的窗口(WebContents)挂一次 'destroyed' 清理,// 窗口关闭时释放它持有的全部引用,聚合出降零 topics 才向 relay 发 unsubscribe@@ -1410,8 +1419,13 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):for (const { deviceId, topics } of recordWindowGone(windowId)) {// 窗口已销毁、无 ref 可恢复 → 用有限退避主动重试,堵住 unsubscribe 一次失败后被控端// 对已无 UI 订阅的 topic 持续推送的泄漏(见 retryUnsubscribeAfterWindowGone)。- if (topics.length > 0)- void retryUnsubscribeAfterWindowGone(deps.unsubscribe, deviceId, topics);+ if (topics.length > 0) {+ void retryUnsubscribeAfterWindowGone(+ diagnostics.forWindow(deps, windowId).unsubscribe,+ deviceId,+ topics,+ );+ }}});};@@ -1419,12 +1433,14 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):requireDeviceLinkCapability();const p = (payload ?? {}) as { deviceId?: unknown; topics?: unknown };attachWindowCleanup(e.sender);- return handleSubscribe(deps, p.deviceId, p.topics, e.sender.id);+ return handleSubscribe(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.topics, e.sender.id);});ipcMain.handle(DEVICE_LINK_INVOKE.UNSUBSCRIBE, (e, payload: unknown) => {requireDeviceLinkCapability();const p = (payload ?? {}) as { deviceId?: unknown; topics?: unknown };- return handleUnsubscribe(deps, p.deviceId, p.topics, e.sender.id);+ return handleUnsubscribe(+ diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.topics, e.sender.id,+ );});ipcMain.handle(DEVICE_LINK_INVOKE.DISCONNECT_ALL, (e) => {assertTrustedAppRendererEvent(e);diff --git a/apps/desktop/src/main/device-link/ipcDiagnostics.ts b/apps/desktop/src/main/device-link/ipcDiagnostics.tsnew file mode 100644index 0000000000..4aa3503614--- /dev/null+++ b/apps/desktop/src/main/device-link/ipcDiagnostics.ts@@ -0,0 +1,166 @@+import { createHmac, randomBytes } from 'node:crypto';+import { REMOTE_INVOKE_ALLOWLIST, type DeviceLinkErrorCode } from '@cindy/device-link';+import type { DeviceLinkIpcDeps } from './ipc';++// Explicit vocabulary: never copy remote error messages/codes or IPC arguments+// into diagnostics. Unknown errors still propagate unchanged to the caller.+const ERROR_CODES = {+ DEVICE_OFFLINE: true,+ REMOTE_DISABLED: true,+ VERSION_MISMATCH: true,+ PAYLOAD_TOO_LARGE: true,+ RATE_LIMITED: true,+ BAD_REQUEST: true,+ INTERNAL: true,+ CHANNEL_NOT_ALLOWED: true,+ ACCESS_REVOKED: true,+ INVOKE_TIMEOUT: true,+ PEER_RESET: true,+ LINK_NOT_OPEN: true,+ NOT_CONNECTED: true,+ BACKPRESSURE: true,+ MEDIA_FETCH_FAILED: true,+ VOICE_TRANSCRIBE_FAILED: true,+ VOICE_CREDENTIAL_SYNC_FAILED: true,+ VOICE_CREDENTIAL_SYNC_REMOVED: true,+ VOICE_DICTIONARY_LEARNING_FAILED: true,+ VOICE_DICTIONARY_GET_FAILED: true,+ IPC_ERROR: true,+ // responsivenessTracker emits this Desktop-local code outside the wire union.+ DEVICE_UNRESPONSIVE: true,+} satisfies Record<DeviceLinkErrorCode | 'IPC_ERROR' | 'DEVICE_UNRESPONSIVE', true>;++function errorCode(error: unknown): string {+ const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;+ if (typeof code === 'string' && Object.hasOwn(ERROR_CODES, code)) return code;+ // The uninitialized main client already throws this mapped code. Do not+ // misreport it as a known raw NOT_CONNECTED / BACKPRESSURE cause.+ if (error instanceof Error && error.message.startsWith('[DEVICE_LINK_NOT_CONNECTED]')) {+ return 'MAPPED_NOT_CONNECTED';+ }+ return 'UNKNOWN';+}++type Operation = 'open-link' | 'invoke' | 'subscribe' | 'unsubscribe';+interface Bucket {+ windowId: number;+ peer: string;+ operation: Operation;+ channel: string;+ code: string;+ completed: number;+}++/** Local diagnostics for completed transport calls originating at renderer IPC.+ * Counts before IPC error remapping; not wire sends or all main background work.+ * First failure per bucket is immediate; 30s summaries include that first event+ * and successes for a baseline. Bounded cardinality and no payloads/peer IDs.+ */+export function createDeviceLinkIpcDiagnostics(+ emit: (event: string, fields: Record<string, unknown>) => void,+) {+ const salt = randomBytes(32);+ const buckets = new Map<string, Bucket>();+ const maxBuckets = 64;+ let overflowCompleted = 0;+ let overflowFailures = 0;+ let startedAt = 0;+ let timer: ReturnType<typeof setTimeout> | undefined;++ function safeEmit(event: string, fields: Record<string, unknown>): void {+ try {+ emit(event, fields);+ } catch {+ /* Diagnostics cannot change request behavior. */+ }+ }++ function flush(): void {+ if (timer) clearTimeout(timer);+ timer = undefined;+ const elapsedMs = Date.now() - startedAt;+ for (const bucket of buckets.values()) safeEmit('transport summary', { ...bucket, elapsedMs });+ if (overflowCompleted)+ safeEmit('transport summary overflow', { overflowCompleted, overflowFailures, elapsedMs });+ buckets.clear();+ overflowCompleted = 0;+ overflowFailures = 0;+ }++ function record(+ windowId: number,+ deviceId: string,+ operation: Operation,+ channel: string,+ code: string,+ ): void {+ if (!timer) {+ startedAt = Date.now();+ timer = setTimeout(flush, 30_000);+ timer.unref?.();+ }+ const peer = createHmac('sha256', salt).update(deviceId).digest('hex').slice(0, 16);+ const safeChannel =+ operation === 'invoke'+ ? REMOTE_INVOKE_ALLOWLIST.has(channel)+ ? channel+ : 'UNKNOWN'+ : operation;+ const key = JSON.stringify([windowId, peer, operation, safeChannel, code]);+ const existing = buckets.get(key);+ if (existing) {+ existing.completed++;+ return;+ }+ if (buckets.size >= maxBuckets) {+ overflowCompleted++;+ if (code !== 'OK') overflowFailures++;+ return;+ }+ const bucket: Bucket = { windowId, peer, operation, channel: safeChannel, code, completed: 1 };+ buckets.set(key, bucket);+ if (code !== 'OK') safeEmit('transport first failure', { ...bucket });+ }++ async function observe<T>(+ windowId: number,+ deviceId: string,+ operation: Operation,+ channel: string,+ call: () => Promise<T>,+ ): Promise<T> {+ let code = 'OK';+ try {+ const result = await call();+ if (result && typeof result === 'object' && 'ok' in result && result.ok === false) {+ code = errorCode('error' in result ? result.error : undefined);+ }+ return result;+ } catch (error) {+ code = errorCode(error);+ throw error;+ } finally {+ try {+ record(windowId, deviceId, operation, channel, code);+ } catch {+ /* Best effort. */+ }+ }+ }++ return {+ flush,+ forWindow(deps: DeviceLinkIpcDeps, windowId: number): DeviceLinkIpcDeps {+ return {+ ...deps,+ openLink: (peer) => observe(windowId, peer, 'open-link', '', () => deps.openLink(peer)),+ invoke: (peer, channel, args) =>+ observe(windowId, peer, 'invoke', channel, () => deps.invoke(peer, channel, args)),+ subscribe: (peer, topics) =>+ observe(windowId, peer, 'subscribe', '', () => deps.subscribe(peer, topics)),+ unsubscribe: (peer, topics) =>+ observe(windowId, peer, 'unsubscribe', '', () => deps.unsubscribe(peer, topics)),+ };+ },+ };+}diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex 95b8fede07..ea2058bc67 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -1034,6 +1034,49 @@ describe('refreshRemoteDeviceSessions retry', () => {});});+describe('queued refresh cancellation', () => {+ // Renderer-local coverage: one controller, two target devices. This is not+ // the shared-host topology. Transport isolation with two controllers sharing+ // one host (including a silent/non-ACKing controller) is covered separately+ // in packages/device-link/src/__tests__/client.test.ts.+ it.each(['disconnect', 'disconnect-all', 'remove', 'clear'] as const)(+ 'does not revive a queued refresh after %s; another target in the same controller still works',+ async (action) => {+ const device = did();+ const otherTarget = did();+ remoteProjectsStore.setDeviceSessions(device, 'Remote', [session('cached')]);+ const pending = deferred<Session[]>();+ invoke.mockReturnValueOnce(pending.promise).mockResolvedValue([]);+ const first = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });+ const queued = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });+ if (action === 'disconnect') remoteProjectsStore.markDeviceDisconnected(device);+ if (action === 'disconnect-all') remoteProjectsStore.markAllDisconnected();+ if (action === 'remove') remoteProjectsStore.removeDevice(device);+ if (action === 'clear') remoteProjectsStore.clear();+ await expect(refreshRemoteDeviceSessions(otherTarget)).resolves.toBe('ok');+ pending.resolve([session('stale')]);+ await expect(Promise.all([first, queued])).resolves.toEqual(['superseded', 'superseded']);+ expect(invoke.mock.calls.filter(([peer]) => peer === device)).toHaveLength(1);+ expect(remoteProjectsStore.getDeviceIds()).not.toContain(device);+ expect(remoteProjectsStore.getDeviceIds()).toContain(otherTarget);+ },+ );++ it('accepts a new refresh after reconnect while the stale read is still in flight', async () => {+ const device = did();+ const pending = deferred<Session[]>();+ invoke.mockReturnValueOnce(pending.promise).mockResolvedValue([session('fresh')]);+ const first = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });+ const queued = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });+ remoteProjectsStore.markDeviceDisconnected(device);+ const reconnected = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });+ pending.resolve([session('stale')]);+ await expect(Promise.all([first, queued, reconnected])).resolves.toEqual(['ok', 'ok', 'ok']);+ expect(invoke).toHaveBeenCalledTimes(2);+ expect(remoteProjectsStore.getDeviceSessions(device).map((s) => s.id)).toEqual(['fresh']);+ });+});+describe('remote schedule mirror', () => {const snapshot = (readAt?: number) => ({ runs: [{sessionId: 'schedule-session', runId: 'run', scheduleId: 'auto', scheduleName: 'auto',diff --git a/apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx b/apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsxindex c3ef7d114a..588969c786 100644--- a/apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx+++ b/apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx@@ -35,6 +35,62 @@ interface TopLevelErrorBoundaryState {error: NormalizedError | null;}+interface RenderEntryContext {+ entry: string;+ windowKind: string;+ appVersion?: string;+}++/**+ * Keep the crash record attributable when several renderer windows share the+ * same main log. Do not include the raw query string: boot session/device IDs+ * in it are user data and are not needed to identify the entry point.+ */+function getRenderEntryContext(): RenderEntryContext {+ try {+ const params = new URLSearchParams(window.location.search);+ const view = params.get('view');+ const ghostPanel = params.get('ghostPanelWindow');++ if (params.get('sidebarWindow') === '1') {+ return {+ entry: 'sidebar-window',+ windowKind: 'sidebar',+ appVersion: window.electronAPI?.appVersion,+ };+ }+ if (ghostPanel) {+ return {+ entry: 'ghost-panel',+ windowKind: 'ghost-panel',+ appVersion: window.electronAPI?.appVersion,+ };+ }+ if (params.get('secondaryWindow') === '1') {+ return {+ entry: 'secondary-window',+ windowKind: 'secondary',+ appVersion: window.electronAPI?.appVersion,+ };+ }+ if (view) {+ return {+ entry: `view:${view}`,+ windowKind: 'utility',+ appVersion: window.electronAPI?.appVersion,+ };+ }+ } catch {+ // A malformed/early window URL must not interfere with the crash fallback.+ }++ return {+ entry: 'main',+ windowKind: 'main',+ appVersion: window.electronAPI?.appVersion,+ };+}+export class TopLevelErrorBoundary extends Component<{ children: ReactNode },TopLevelErrorBoundaryState@@ -47,10 +103,12 @@ export class TopLevelErrorBoundary extends Component<componentDidCatch(error: unknown, info: ErrorInfo): void {const { message, stack } = normalizeError(error);+ const renderEntry = getRenderEntryContext();log.error('top-level render crashed (above RouterProvider)', {message,stack,componentStack: info.componentStack ?? undefined,+ ...renderEntry,});}diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex aed914a42d..afd1c895d3 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -145,6 +145,7 @@ export type RefreshResult = 'ok' | 'revoked' | 'superseded' | 'gave-up';interface RefreshTask {promise: Promise<RefreshResult>;rerun: boolean;+ rerunEpoch?: number;name?: string;opts: RefreshOptions;}@@ -219,7 +220,7 @@ export async function refreshRemoteDeviceSessions(coalescingMode: undefined,};// 先让当前 in-flight snapshot 失效,否则它可能在排队的补跑开始前覆盖 push 带来的新状态。- remoteProjectsStore.nextSnapshotEpoch(deviceId, status);+ existing.rerunEpoch = remoteProjectsStore.nextSnapshotEpoch(deviceId, status);return existing.promise;}@@ -243,6 +244,15 @@ async function drainRefreshTask(deviceId: string, task: RefreshTask): Promise<Reresult = await runRefreshRemoteDeviceSessions(deviceId, task.name, task.opts);// revoked 是被控端明确拒绝,不再补跑排队请求。if (result === 'revoked') return result;+ // Disconnect/remove/clear must cancel queued work as well as the in-flight+ // snapshot. A new reconnect refresh can explicitly queue a newer epoch.+ if (+ task.rerun &&+ task.rerunEpoch !== undefined &&+ !remoteProjectsStore.isLatestSnapshotEpoch(deviceId, task.rerunEpoch, task.opts.status ?? 'active')+ ) {+ return 'superseded';+ }} while (task.rerun);return result;}