Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-desktop): 协调后台节流并移除常驻服务探测
Dash32bdfa8c728a
diff --git a/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts b/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.tsindex 5790301942..f9cda3b69d 100644--- a/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts+++ b/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts@@ -56,7 +56,8 @@ describe('主 BrowserWindow 后台节流', () => {it('active turn 期间通过 webContents 运行态切换后台节流', () => {expect(source).toContain('function setMainWindowBackgroundThrottlingForActiveTurn(hasRunningTurn: boolean): void');expect(source).toContain('const nextAllowed = !hasRunningTurn;');- expect(source).toContain('win.webContents.setBackgroundThrottling(mainWindowBackgroundThrottlingAllowed);');+ expect(source).toContain('mainWindowBackgroundThrottlingAllowed && !isRemoteDesktopVideoActive(),');+ expect(source).toContain('registerRemoteDesktopIpc(applyMainWindowBackgroundThrottling);');expect(source).toContain('onAnySessionTurnKeepaliveChange: (isRunning) => {');expect(source).toContain('setMainWindowBackgroundThrottlingForActiveTurn(isRunning);');expect(source).toContain('notifyUpdateAutoRelaunchBusyStateChanged();');diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex c639ec6d73..1f6b93cce0 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -461,7 +461,7 @@ import { sanitizeGhostNoticeText } from './cindy-brain/notifySlot.js';import { isIpcError } from '../shared/ipc-errors';import { readFileBytesForPreview } from './fileReadBytes.js';import { initHeartbeatService } from './heartbeatService';-import { registerRemoteDesktopIpc } from './remote-desktop';+import { isRemoteDesktopVideoActive, registerRemoteDesktopIpc } from './remote-desktop';import { initAnalyticsSettingsService, noteAuthColdStartState } from './analyticsSettingsService';import { initLogUploadService, scheduleStartupBackfill } from './log-upload';import { WindowManualDragController } from './windowManualDrag';@@ -3380,7 +3380,10 @@ if (process.platform === 'darwin') {function applyMainWindowBackgroundThrottling(): void {const win = mainWindowRef;if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return;- win.webContents.setBackgroundThrottling(mainWindowBackgroundThrottlingAllowed);+ // A finishing turn or video must not throttle the other active workload.+ win.webContents.setBackgroundThrottling(+ mainWindowBackgroundThrottlingAllowed && !isRemoteDesktopVideoActive(),+ );}function setMainWindowBackgroundThrottlingForActiveTurn(hasRunningTurn: boolean): void {@@ -8826,7 +8829,7 @@ app.on('ready', async () => {// owning modules above; future collections/actions do not add tunnel channels.registerRemoteResourcesIpc();registerDeviceLinkIpc();- registerRemoteDesktopIpc();+ registerRemoteDesktopIpc(applyMainWindowBackgroundThrottling);void startupPurgeDrain.then(({ purged, pending }) => {if (purged > 0 || pending > 0) {diff --git a/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.tsnew file mode 100644index 0000000000..90dec5e901--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts@@ -0,0 +1,121 @@+import { readFileSync } from 'node:fs';+import { ScriptTarget, transpileModule } from 'typescript';+import { describe, expect, it, vi } from 'vitest';++const source = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');+const bootstrap = readFileSync(new URL('../../bootstrap-electron.ts', import.meta.url), 'utf8');+function between(text: string, start: string, end: string): string {+ const from = text.indexOf(start);+ const to = text.indexOf(end, from);+ if (from < 0 || to < 0) throw new Error(`Missing source boundary: ${start}`);+ return text.slice(from, to);+}+function compile(text: string, deps: Record<string, unknown>) {+ const js = transpileModule(text, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;+ return new Function(...Object.keys(deps), js)(...Object.values(deps));+}++describe('remote video shares the existing main-window throttle policy', () => {+ function harness() {+ const setBackgroundThrottling = vi.fn();+ const window = {+ isDestroyed: () => false,+ webContents: { isDestroyed: () => false, setBackgroundThrottling },+ };+ // Execute the production policy and lease setter, without booting Electron.+ const runtime = compile(+ `+ let mainWindowRef = window;+ let mainWindowBackgroundThrottlingAllowed = true;+ ${between(source, 'let videoLease:', 'let offerGeneration').replace('export ', '')}+ ${between(bootstrap, 'function applyMainWindowBackgroundThrottling', 'function focusMainWindow')}+ onVideoActivityChanged = applyMainWindowBackgroundThrottling;+ return { turn: setMainWindowBackgroundThrottlingForActiveTurn, video: setVideoLease,+ apply: applyMainWindowBackgroundThrottling, replace: (win) => { mainWindowRef = win; applyMainWindowBackgroundThrottling(); } };+ `,+ { window },+ );+ return { ...runtime, window, setBackgroundThrottling };+ }++ it.each(['turn', 'video'])(+ 'keeps the other workload unthrottled when %s finishes first',+ (first) => {+ const h = harness();+ h.apply();+ expect(h.setBackgroundThrottling).toHaveBeenLastCalledWith(true);+ h.turn(true);+ h.video('lease');+ expect(h.setBackgroundThrottling).toHaveBeenLastCalledWith(false);+ if (first === 'turn') h.turn(false);+ else h.video(null);+ expect(h.setBackgroundThrottling).toHaveBeenLastCalledWith(false);+ if (first === 'turn') h.video(null);+ else h.turn(false);+ expect(h.setBackgroundThrottling).toHaveBeenLastCalledWith(true);+ },+ );++ it('reapplies active video to a replacement window and ignores destroyed windows', () => {+ const h = harness();+ h.video('lease');+ h.replace(null);+ h.turn(true);+ h.turn(false);+ const apply = vi.fn();+ h.replace({+ ...h.window,+ webContents: { ...h.window.webContents, setBackgroundThrottling: apply },+ });+ expect(apply).toHaveBeenLastCalledWith(false);+ h.replace({ ...h.window, isDestroyed: () => true });+ h.video(null);+ expect(apply).toHaveBeenCalledTimes(1);+ });++ it('notifies through every lease change instead of independently setting Electron throttling', () => {+ expect(source.match(/videoLease = /g)).toHaveLength(1);+ expect(source).not.toContain('.setBackgroundThrottling(');+ expect(between(source, 'function stopVideo()', 'async function sources')).toContain(+ 'setVideoLease(null);',+ );+ expect(between(source, 'async function offer(', 'export const remoteDesktop')).toContain(+ 'setVideoLease(lease.lease);',+ );+ });+});++describe('remote desktop state polling', () => {+ it('does not probe Windows for routine polls, but checks fresh status on explicit requests', async () => {+ const readWindowsDesktopSupport = vi.fn(async () => 'ready');+ const assertTrustedAppRendererEvent = vi.fn();+ let handler: (event: unknown, check?: unknown) => Promise<Record<string, unknown>>;+ compile(between(source, ' ipcMain.handle(DESKTOP_LOCAL.STATE', ' let windowsSetupBusy'), {+ ipcMain: {+ handle: (_name: string, callback: typeof handler) => {+ handler = callback;+ },+ },+ DESKTOP_LOCAL: { STATE: 'state' },+ assertTrustedAppRendererEvent,+ readDeviceLinkSettings: () => ({ remoteDesktopEnabled: false }),+ remoteDesktop: { state: null },+ permissions: { guideOpen: false },+ readWindowsDesktopSupport,+ throwIpcError: (code: string) => {+ throw new Error(code);+ },+ });+ for (let poll = 0; poll < 60; poll++) {+ expect(await handler!({}, poll % 2 ? false : undefined)).not.toHaveProperty('windowsSupport');+ }+ expect(readWindowsDesktopSupport).not.toHaveBeenCalled();+ expect(await handler!({}, true)).toHaveProperty('windowsSupport', 'ready');+ readWindowsDesktopSupport.mockResolvedValue('missing');+ expect(await handler!({}, true)).toHaveProperty('windowsSupport', 'missing');+ expect(readWindowsDesktopSupport).toHaveBeenCalledTimes(2);+ await expect(handler!({}, 'true')).rejects.toThrow('INVALID_PARAMS');+ expect(readWindowsDesktopSupport).toHaveBeenCalledTimes(2);+ expect(assertTrustedAppRendererEvent).toHaveBeenCalledTimes(63);+ });+});diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.tsindex 5cbba16629..e285b465e9 100644--- a/apps/desktop/src/main/remote-desktop/index.ts+++ b/apps/desktop/src/main/remote-desktop/index.ts@@ -89,6 +89,14 @@ const supportsSystemAudio =return major > 14 || (major === 14 && minor >= 2);})());let videoLease: string | null = null;+let onVideoActivityChanged = () => {};+export function isRemoteDesktopVideoActive(): boolean {+ return videoLease !== null;+}+function setVideoLease(lease: string | null): void {+ videoLease = lease;+ onVideoActivityChanged();+}let offerGeneration = 0;let nativeOverlay = false;let nativeSettings: RemoteDesktopVideoSettings | undefined;@@ -107,9 +115,8 @@ function stopVideo(): void {nativeCapture.stop();nativeDisplay = null;captureGrant = null;- videoLease = null;+ setVideoLease(null);if (host && !host.isDestroyed()) {- host.setBackgroundThrottling(true);if (isTrustedAppRendererWindow(BrowserWindow.fromWebContents(host)))host.send(DESKTOP_LOCAL.COMMAND, {id: randomUUID(),@@ -151,7 +158,7 @@ async function offer(const generation = ++offerGeneration;nativeCapture.stop();nativeDisplay = null;- videoLease = null;+ setVideoLease(null);captureGrant = null;const currentHost = host;let source: DesktopCapturerSource | null = null;@@ -197,8 +204,7 @@ async function offer(nativeDisplay = nativeAvailable ? lease.display.id : null;nativeOverlay = cursorOverlay === true && process.platform === 'darwin';nativeSettings = settings;- videoLease = lease.lease;- currentHost.setBackgroundThrottling(false);+ setVideoLease(lease.lease);return new Promise<string>((resolve, reject) => {const id = randomUUID();const timer = setTimeout(() => {@@ -293,7 +299,9 @@ export const remoteDesktop = new RemoteDesktopController({},});-export function registerRemoteDesktopIpc(): void {+export function registerRemoteDesktopIpc(refreshBackgroundThrottling: () => void): void {+ onVideoActivityChanged = refreshBackgroundThrottling;+ onVideoActivityChanged();const timer = setInterval(() => remoteDesktop.tick(), 1000);timer.unref();app.on('before-quit', () => {@@ -354,13 +362,17 @@ export function registerRemoteDesktopIpc(): void {throwIpcError('PERMISSION_DENIED', 'Invalid desktop viewer heartbeat');remoteDesktop.viewHeartbeat(lease);});- ipcMain.handle(DESKTOP_LOCAL.STATE, async (event) => {+ ipcMain.handle(DESKTOP_LOCAL.STATE, async (event, checkWindowsSupport: unknown) => {assertTrustedAppRendererEvent(event);+ if (checkWindowsSupport !== undefined && typeof checkWindowsSupport !== 'boolean')+ throwIpcError('INVALID_PARAMS', 'Invalid Windows support status request');return {enabled: readDeviceLinkSettings().remoteDesktopEnabled,active: remoteDesktop.state,permissionGuide: permissions.guideOpen,- windowsSupport: await readWindowsDesktopSupport(),+ ...(checkWindowsSupport === true+ ? { windowsSupport: await readWindowsDesktopSupport() }+ : {}),};});let windowsSetupBusy = false;diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 13f6e5a5f4..9746bcf2ca 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4178,7 +4178,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// 同账号设备经 server relay 互联;此处只暴露开关 + 设备列表管理面,// 隧道(远程会话控制)在 M3 接入。remoteDesktop: {- state: () => ipcRenderer.invoke(DESKTOP_LOCAL.STATE),+ state: (checkWindowsSupport) => ipcRenderer.invoke(DESKTOP_LOCAL.STATE, checkWindowsSupport),permissions: () => ipcRenderer.invoke(DESKTOP_LOCAL.PERMISSIONS),openPermission: (permission) => ipcRenderer.invoke(DESKTOP_LOCAL.OPEN_PERMISSION, permission),dismissPermissionGuide: () => ipcRenderer.invoke(DESKTOP_LOCAL.DISMISS_GUIDE),diff --git a/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx b/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsxindex 6b97455d0d..e5404cc65b 100644--- a/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx+++ b/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx@@ -24,7 +24,7 @@ export function RemoteDesktopSetting() {reading = true;const current = revision.current;void api- .state()+ .state(true).then((state) => {if (active && current === revision.current) {setEnabled(state.enabled);@@ -109,7 +109,7 @@ export function RemoteDesktopSetting() {setServiceError(false);void window.electronAPI.remoteDesktop.windowsSupport(windowsSupport !== 'ready')- .then(() => window.electronAPI.remoteDesktop.state())+ .then(() => window.electronAPI.remoteDesktop.state(true)).then((state) => setWindowsSupport(state.windowsSupport)).catch(() => setServiceError(true)).finally(() => {diff --git a/apps/desktop/src/renderer/components/settings/__tests__/remoteDesktopSetting.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/remoteDesktopSetting.test.tsxnew file mode 100644index 0000000000..16e5612320--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/remoteDesktopSetting.test.tsx@@ -0,0 +1,66 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import { RemoteDesktopSetting } from '../RemoteDesktopSetting';+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('../RemoteDesktopPermissions', () => ({ RemoteDesktopPermissions: () => null }));+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++it('probes service status only while settings are mounted and after setup', async () => {+ vi.useFakeTimers();+ let support = 'missing';+ const state = vi.fn(async (probe?: boolean) => ({+ enabled: true,+ active: null,+ ...(probe ? { windowsSupport: support } : {}),+ }));+ const windowsSupport = vi.fn(async () => {+ support = 'ready';+ });+ Object.assign(window, { electronAPI: { remoteDesktop: { state, windowsSupport } } });+ const view = render(<RemoteDesktopSetting />);+ await act(async () => {});+ expect(state).toHaveBeenCalledExactlyOnceWith(true);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(6000);+ });+ expect(state.mock.calls.slice(1)).toEqual([[true], [true], [true]]);+ fireEvent.click(screen.getByRole('button', { name: 'remoteDesktop.windowsEnable' }));+ await act(async () => {});+ expect(windowsSupport).toHaveBeenCalledExactlyOnceWith(true);+ expect(state).toHaveBeenLastCalledWith(true);+ expect(screen.getByRole('button', { name: 'remoteDesktop.windowsDisable' })).toBeTruthy();+ view.unmount();+ const calls = state.mock.calls.length;+ await vi.advanceTimersByTimeAsync(4000);+ expect(state).toHaveBeenCalledTimes(calls);+});++it('recovers a slow initial probe discarded by an intervening enable action', async () => {+ vi.useFakeTimers();+ let complete!: (value: { enabled: boolean; active: null; windowsSupport: string }) => void;+ const state = vi+ .fn(async () => ({ enabled: true, active: null, windowsSupport: 'missing' }))+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ complete = resolve;+ }),+ );+ const enable = vi.fn(async () => {});+ Object.assign(window, { electronAPI: { remoteDesktop: { state, enable } } });+ render(<RemoteDesktopSetting />);+ fireEvent.click(screen.getByRole('switch'));+ await act(async () => {});+ await act(async () => {+ complete({ enabled: false, active: null, windowsSupport: 'missing' });+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(state).toHaveBeenLastCalledWith(true);+ expect(screen.getByRole('button', { name: 'remoteDesktop.windowsEnable' })).toBeTruthy();+});diff --git a/apps/desktop/src/shared/remoteDesktop.ts b/apps/desktop/src/shared/remoteDesktop.tsindex bd7d1b0867..fa5ef32d08 100644--- a/apps/desktop/src/shared/remoteDesktop.ts+++ b/apps/desktop/src/shared/remoteDesktop.ts@@ -38,7 +38,7 @@ export interface DesktopLocalState {}export type WindowsDesktopSupport = 'ready' | 'missing' | 'installRequired' | 'unavailable';export interface RemoteDesktopApi {- state(): Promise<DesktopLocalState>;+ state(checkWindowsSupport?: boolean): Promise<DesktopLocalState>;enable(enabled: boolean): Promise<void>;windowsSupport(enabled: boolean): Promise<void>;stop(): Promise<void>;