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): 将桌面捕获隔离到专用沙箱窗口
Dashd05a257545a1
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 104f834d64..d119943946 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1727,6 +1727,11 @@ const config: ForgeConfig = {config: 'vite.preload.config.ts',target: 'preload',},+ {+ entry: 'src/preload/desktopCapturePreload.ts',+ config: 'vite.preload.config.ts',+ target: 'preload',+ },{// 资源用量独立窗不加载主应用的通用 bridge 与模块级同步初始化。entry: 'src/preload/resourceUsagePreload.ts',@@ -1763,6 +1768,7 @@ const config: ForgeConfig = {},],renderer: [+ { name: 'desktop_capture', config: 'vite.capture.config.ts' },{name: 'main_window',config: 'vite.renderer.config.ts',diff --git a/apps/desktop/native/remote-desktop/README.md b/apps/desktop/native/remote-desktop/README.mdindex 223882193c..dc6c24ea88 100644--- a/apps/desktop/native/remote-desktop/README.md+++ b/apps/desktop/native/remote-desktop/README.md@@ -32,3 +32,38 @@ development flags, stale audit tokens, and signed-resource helper replacement.The resource fixture is ad-hoc signed: it verifies resource sealing, **not** theproduction Apple/team acceptance path. A signed application launch and TCC flowmust still be checked during release validation.++# Desktop capture process boundary++Main creates one hidden, sandboxed capture renderer per media offer. It uses a+separate in-memory session, dedicated preload and separate build entry. Packaged+assets are served only by `cindy-desktop-capture://capture/`; the page cannot load+chat/Markdown, navigate, open windows or use arbitrary HTTP/WebSocket requests.+WebRTC remains the media transport. The main application preload exposes only+remote-desktop settings/status/stop, never source IDs or raw frame reads.++The owner lifecycle is `absent → starting → active → destroyed`. All capture IPC+requires the exact Main-created webContents, its top-level frame and document URL.+Main owns the single-use display grant and existing lease/offer generation. Stop,+revocation, replacement and offer failure clear authority before destroying the+window; late ready, source enumeration or replies cannot revive the old owner.+Unexpected capture process failure ends only its desktop lease. ICE retries keep+the existing process; there is no process restart loop or shared relay reset.+This surface deliberately does not follow reusable UI-window hide semantics:+destroying the renderer is necessary to end independently created media streams.++The app session rejects both `getDisplayMedia` and legacy desktop capture. In+Electron 41 those requests use `media` with an empty `mediaTypes` list; physical+microphone/camera requests remain allowed. The capture session admits that empty+media request only from its own exact main frame, then the display handler checks+the lease and consumes its grant. Native fallback reads are gated by the same+owner, lease and generation and remain in Main/native helpers.++Validation covers cancellation during readiness/enumeration, foreign and child+frame IPC, offer versus ICE timeout, forced destruction, and stale-owner events.+Electron 41.10.3 was also exercised with the production capture bundle/preload and+custom scheme: synthetic WebFrameMain video/audio → WebRTC answer/received track,+main-page capture rejection, fake microphone capture, and webContents destruction.+Mixed microphone/legacy-desktop requests were rejected by Chromium's bad-IPC+validation before our permission callback. These synthetic tests do not replace+real system audio, Windows lock/UAC or mobile cross-NAT release validation.diff --git a/apps/desktop/src/capture-renderer/entry.ts b/apps/desktop/src/capture-renderer/entry.tsnew file mode 100644index 0000000000..12cf5d5ac8--- /dev/null+++ b/apps/desktop/src/capture-renderer/entry.ts@@ -0,0 +1,10 @@+import type { DesktopCaptureApi } from '../shared/remoteDesktop';+import { startDesktopCaptureHost } from '../renderer/features/remote-desktop/captureHost';++declare global {+ interface Window {+ desktopCapture: DesktopCaptureApi;+ }+}+const dispose = startDesktopCaptureHost(window.desktopCapture);+window.addEventListener('unload', dispose, { once: true });diff --git a/apps/desktop/src/capture-renderer/index.html b/apps/desktop/src/capture-renderer/index.htmlnew file mode 100644index 0000000000..4c85e1fbfe--- /dev/null+++ b/apps/desktop/src/capture-renderer/index.html@@ -0,0 +1,10 @@+<!doctype html>+<html>+ <head>+ <meta charset="UTF-8" />+ <title>Desktop capture</title>+ </head>+ <body>+ <script type="module" src="./entry.ts"></script>+ </body>+</html>diff --git a/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts b/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.tsindex f9cda3b69d..bd424a9dcc 100644--- a/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts+++ b/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts@@ -56,8 +56,9 @@ describe('主 BrowserWindow 后台节流', () => {it('active turn 期间通过 webContents 运行态切换后台节流', () => {expect(source).toContain('function setMainWindowBackgroundThrottlingForActiveTurn(hasRunningTurn: boolean): void');expect(source).toContain('const nextAllowed = !hasRunningTurn;');- expect(source).toContain('mainWindowBackgroundThrottlingAllowed && !isRemoteDesktopVideoActive(),');- expect(source).toContain('registerRemoteDesktopIpc(applyMainWindowBackgroundThrottling);');+ expect(source).toMatch(/setBackgroundThrottling\(\s*mainWindowBackgroundThrottlingAllowed,?\s*\)/);+ expect(source).not.toContain('isRemoteDesktopVideoActive');+ expect(source).toContain('registerRemoteDesktopIpc();');expect(source).toContain('onAnySessionTurnKeepaliveChange: (isRunning) => {');expect(source).toContain('setMainWindowBackgroundThrottlingForActiveTurn(isRunning);');expect(source).toContain('notifyUpdateAutoRelaunchBusyStateChanged();');@@ -180,6 +181,10 @@ describe('窗口可见性广播(装饰动画闸门的兜底信号)', () => {* 豁免必须显式登记并写明理由——目的是逼一次判断,而不是让人默默跳过。*/const BROADCAST_EXEMPT = new Map<string, string>([+ [+ 'remote-desktop/captureWindow.ts',+ '独立捕获页不加载聊天 Renderer 或装饰动画;只在媒体连接期间存在,停止时销毁',+ ],['computer-permission-guide/window.ts',// 这两个窗口(guide / backdrop)确实也加载 index.html?view=、也装了闸门,但其视图diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 1f6b93cce0..82452d28b5 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 { isRemoteDesktopVideoActive, registerRemoteDesktopIpc } from './remote-desktop';+import { registerRemoteDesktopIpc } from './remote-desktop';import { initAnalyticsSettingsService, noteAuthColdStartState } from './analyticsSettingsService';import { initLogUploadService, scheduleStartupBackfill } from './log-upload';import { WindowManualDragController } from './windowManualDrag';@@ -2445,6 +2445,10 @@ authManager.setStableOwnerPostCommitTask(async ({ reason, scopeKey, dataOwnerId// cindy-media: 媒体总仓字节仓取件窗口(内容寻址 blob;新写入媒体的// 统一协议,历史 xdt-* 协议只读兼容)protocol.registerSchemesAsPrivileged([+ {+ scheme: 'cindy-desktop-capture',+ privileges: { standard: true, secure: true, supportFetchAPI: true },+ },imageSchemePrivilege,videoSchemePrivilege,localFileSchemePrivilege,@@ -3380,9 +3384,8 @@ if (process.platform === 'darwin') {function applyMainWindowBackgroundThrottling(): void {const win = mainWindowRef;if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return;- // A finishing turn or video must not throttle the other active workload.win.webContents.setBackgroundThrottling(- mainWindowBackgroundThrottlingAllowed && !isRemoteDesktopVideoActive(),+ mainWindowBackgroundThrottlingAllowed,);}@@ -8829,7 +8832,7 @@ app.on('ready', async () => {// owning modules above; future collections/actions do not add tunnel channels.registerRemoteResourcesIpc();registerDeviceLinkIpc();- registerRemoteDesktopIpc(applyMainWindowBackgroundThrottling);+ registerRemoteDesktopIpc();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.tsindex 90dec5e901..8dc1bb1696 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts@@ -15,73 +15,17 @@ function compile(text: string, deps: Record<string, unknown>) {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('capture background activity is isolated from the chat window', () => {+ it('keeps capture unthrottled without changing the main-window workload policy', () => {+ const capture = readFileSync(new URL('../captureWindow.ts', import.meta.url), 'utf8');+ expect(capture).toContain('backgroundThrottling: false');+ expect(+ between(+ bootstrap,+ 'function applyMainWindowBackgroundThrottling',+ 'function focusMainWindow',+ ),+ ).not.toContain('isRemoteDesktopVideoActive');});});diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.tsnew file mode 100644index 0000000000..b91af993cc--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts@@ -0,0 +1,241 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { DESKTOP_LOCAL } from '../../../shared/remoteDesktop';++const h = vi.hoisted(() => ({+ handlers: new Map<string, any>(),+ windows: [] as any[],+ deps: null as any,+ lease: 'lease',+ ready: false,+ source: null as null | Promise<any[]>,+ owner: null as any,+ dispose: vi.fn(),+ stop: vi.fn(),+ nativeStop: vi.fn(),+}));+vi.mock('electron', () => ({+ app: { on: vi.fn() },+ powerMonitor: { on: vi.fn() },+ shell: {},+ nativeImage: {},+ screen: { on: vi.fn(), getAllDisplays: () => [{ id: 1 }] },+ systemPreferences: { getMediaAccessStatus: () => 'granted' },+ desktopCapturer: {+ getSources: () => h.source ?? Promise.resolve([{ id: 'screen:1', display_id: '1' }]),+ },+ ipcMain: { handle: (key: string, value: any) => h.handlers.set(key, value) },+ powerSaveBlocker: { start: () => 1, stop: vi.fn() },+ session: { defaultSession: {} },+}));+vi.mock('../capturePermissions', () => ({ denyAppDesktopCapture: vi.fn() }));+vi.mock('../captureWindow', () => ({+ DesktopCaptureWindow: class {+ get contents() {+ return h.owner;+ }+ assertSender(e: any) {+ if (!h.owner || e.sender !== h.owner || e.senderFrame !== h.owner.mainFrame)+ throw new Error('PERMISSION_DENIED');+ }+ registered(e: any) {+ this.assertSender(e);+ h.owner.ready();+ }+ start() {+ const win = {+ mainFrame: {},+ isDestroyed: () => win.dead,+ dead: false,+ send: vi.fn(),+ session: { setDisplayMediaRequestHandler: vi.fn() },+ ready: () => {},+ cancel: () => {},+ };+ h.windows.push(win);+ h.owner = win;+ return new Promise<void>((resolve, reject) => {+ win.ready = resolve;+ win.cancel = () => reject(new Error('DESKTOP_VIDEO_STOPPED'));+ });+ }+ dispose() {+ h.dispose();+ const owner = h.owner;+ h.owner = null;+ if (owner) {+ owner.dead = true;+ owner.cancel();+ }+ }+ },+}));+vi.mock('../controller', () => ({+ RemoteDesktopController: class {+ constructor(deps: any) {+ h.deps = deps;+ }+ state = null;+ hasLease(value: string) {+ return value === h.lease;+ }+ stop() {+ h.stop();+ h.deps.stopVideo();+ }+ stopByUser() {+ this.stop();+ }+ tick() {}+ input = vi.fn();+ viewHeartbeat = vi.fn();+ },+}));+vi.mock('../nativeCapture', () => ({+ NativeDesktopCapture: class {+ stop = h.nativeStop;+ frame = vi.fn(async () => 'frame');+ },+}));+vi.mock('../inputHost', () => ({+ DesktopInputHost: class {+ stop = vi.fn();+ input = vi.fn();+ },+ readDesktopDisplayModes: vi.fn(),+ setDesktopDisplayMode: vi.fn(),+ readDesktopInputPermission: vi.fn(),+ requestDesktopInputPermission: vi.fn(),+}));+vi.mock('../permissions', () => ({+ RemoteDesktopPermissionsService: class {+ dismiss() {}+ },+}));+vi.mock('../windowsHost', () => ({+ readWindowsDesktopSupport: vi.fn(async () => 'ready'),+ configureWindowsDesktopSupport: vi.fn(),+}));+vi.mock('../clipboard', () => ({+ transferDesktopClipboard: vi.fn(),+ transferDesktopClipboardContent: vi.fn(),+}));+vi.mock('../../device-link/settings-store', () => ({+ readDeviceLinkSettings: () => ({}),+ writeDeviceLinkSetting: vi.fn(),+}));+vi.mock('../../security/trustedAppRenderer', () => ({ assertTrustedAppRendererEvent: vi.fn() }));+vi.mock('../../deepLink', () => ({ getDeepLinkMainWindow: vi.fn() }));+vi.mock('../../computer-permission-guide/request', () => ({+ MAC_ACCESSIBILITY_SETTINGS_URL: '',+ MAC_SCREEN_RECORDING_SETTINGS_URL: '',+}));+vi.mock('../../utils/ipcValidate', () => ({+ throwIpcError: () => {+ throw new Error('PERMISSION_DENIED');+ },+}));+import { registerRemoteDesktopIpc } from '../index';+const event = (owner = h.owner) => ({ sender: owner, senderFrame: owner.mainFrame });+const flush = async () => {+ for (let i = 0; i < 12; i++) await Promise.resolve();+};+const offer = () =>+ h.deps.offer({ lease: h.lease, display: { id: '1' } }, 'sdp', undefined, false, 'attempt');+beforeEach(() => {+ vi.useFakeTimers();+ h.handlers.clear();+ h.windows.length = 0;+ h.source = null;+ h.lease = 'lease';+ h.dispose.mockClear();+ h.stop.mockClear();+ h.nativeStop.mockClear();+ registerRemoteDesktopIpc();+});+afterEach(() => {+ h.deps.stopVideo();+ vi.clearAllTimers();+ vi.useRealTimers();+});++it.each(['ready', 'sources'])(+ 'revocation during %s prevents late capture from reviving the old offer',+ async (phase) => {+ let finish!: (sources: any[]) => void;+ if (phase === 'sources')+ h.source = new Promise((resolve) => {+ finish = resolve;+ });+ const pending = offer();+ const rejected = expect(pending).rejects.toThrow(/DESKTOP_(VIDEO_STOPPED|LEASE_EXPIRED)/);+ const old = h.owner;+ if (phase === 'sources') {+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());+ await flush();+ }+ h.lease = 'replacement';+ h.deps.stopVideo();+ if (finish) finish([{ id: 'screen:1', display_id: '1' }]);+ old.ready();+ await rejected;+ expect(old.dead).toBe(true);+ expect(old.send).not.toHaveBeenCalled();+ expect(h.owner).toBeNull();+ },+);++it('denies main/child-frame capture IPC and forces disposal on offer timeout', async () => {+ const pending = offer();+ const rejected = expect(pending).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');+ const owner = h.owner;+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());+ await flush();+ for (const key of [+ DESKTOP_LOCAL.REGISTER,+ DESKTOP_LOCAL.REPLY,+ DESKTOP_LOCAL.INPUT,+ DESKTOP_LOCAL.VIEW_HEARTBEAT,+ DESKTOP_LOCAL.CAPTURE_STOP,+ ]) {+ for (const caller of [event({ mainFrame: {} }), { sender: owner, senderFrame: {} }])+ expect(() => h.handlers.get(key)(caller, 'lease')).toThrow('PERMISSION_DENIED');+ }+ await expect(+ h.handlers.get(DESKTOP_LOCAL.NATIVE_FRAME)(event({ mainFrame: {} }), 'lease'),+ ).rejects.toThrow('PERMISSION_DENIED');+ expect(owner.send).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(18_000);+ await rejected;+ expect(owner.dead).toBe(true);+ expect(h.nativeStop).toHaveBeenCalled();+});++it('retains the capture owner on ICE timeout and rejects old-owner replies after replacement', async () => {+ const pending = offer();+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());+ await flush();+ const old = h.owner;+ const id = old.send.mock.calls[0][1].id;+ h.handlers.get(DESKTOP_LOCAL.REPLY)(event(), id, 'answer');+ await expect(pending).resolves.toBe('answer');+ const ice = h.deps.ice({+ op: 'ice',+ lease: 'lease',+ attemptId: 'attempt',+ after: 0,+ candidates: [],+ });+ const rejected = expect(ice).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');+ await vi.advanceTimersByTimeAsync(4000);+ await rejected;+ expect(old.dead).toBe(false);+ const next = offer();+ const nextRejected = expect(next).rejects.toThrow('DESKTOP_VIDEO_STOPPED');+ expect(old.dead).toBe(true);+ expect(() => h.handlers.get(DESKTOP_LOCAL.REPLY)(event(old), id, 'late answer')).toThrow(+ 'PERMISSION_DENIED',+ );+ expect(h.owner.dead).toBe(false);+ h.deps.stopVideo();+ await nextRejected;+});diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.tsnew file mode 100644index 0000000000..d79e89356b--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts@@ -0,0 +1,193 @@+import { EventEmitter } from 'node:events';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { DesktopCaptureWindow } from '../captureWindow';+import { denyAppDesktopCapture } from '../capturePermissions';+import { buildContentSecurityPolicy } from '../../security/csp';++const fake = vi.hoisted(() => ({+ windows: [] as any[],+ sessions: [] as any[],+ loadFailure: false,+}));+vi.mock('electron', () => ({+ session: {+ fromPartition: vi.fn(() => {+ const ses = Object.assign(new EventEmitter(), {+ webRequest: { onHeadersReceived: vi.fn() },+ protocol: { handle: vi.fn() },+ setDisplayMediaRequestHandler: vi.fn(),+ setPermissionCheckHandler: vi.fn(),+ setPermissionRequestHandler: vi.fn(),+ });+ fake.sessions.push(ses);+ return ses;+ }),+ },+ BrowserWindow: class {+ destroyed = false;+ webContents = Object.assign(new EventEmitter(), {+ mainFrame: { url: '', parent: null },+ isDestroyed: () => this.destroyed,+ setWindowOpenHandler: vi.fn(),+ });+ constructor(public options: any) {+ fake.windows.push(this);+ }+ loadURL = vi.fn(async (url: string) => {+ this.webContents.mainFrame.url = url;+ if (fake.loadFailure) throw new Error('load failed');+ });+ isDestroyed() {+ return this.destroyed;+ }+ destroy() {+ this.destroyed = true;+ this.webContents.emit('destroyed');+ }+ },+}));+vi.mock('../../utils/ipcValidate', () => ({+ throwIpcError: () => {+ throw new Error('PERMISSION_DENIED');+ },+}));+const event = (window: any) =>+ ({ sender: window.webContents, senderFrame: window.webContents.mainFrame }) as any;+beforeEach(() => {+ fake.windows.length = fake.sessions.length = 0;+ fake.loadFailure = false;+ vi.stubGlobal('DESKTOP_CAPTURE_VITE_DEV_SERVER_URL', 'http://localhost:9988/');+ vi.stubGlobal('DESKTOP_CAPTURE_VITE_NAME', 'desktop_capture');+});+afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++it('only admits the registered top frame and kills the whole process on stop', async () => {+ const failed = vi.fn(),+ owner = new DesktopCaptureWindow(failed);+ const ready = owner.start();+ const win = fake.windows[0];+ const valid = event(win);+ expect(() => owner.registered({ ...valid, sender: {} })).toThrow('PERMISSION_DENIED');+ expect(() =>+ owner.registered({+ ...valid,+ senderFrame: { ...valid.senderFrame, parent: valid.senderFrame },+ }),+ ).toThrow('PERMISSION_DENIED');+ win.webContents.mainFrame.url = 'https://attacker.invalid/';+ expect(() => owner.registered(valid)).toThrow('PERMISSION_DENIED');+ win.webContents.mainFrame.url = 'http://localhost:9988/index.html';+ owner.registered(valid);+ await ready;+ expect(win.options).toMatchObject({+ show: false,+ focusable: false,+ webPreferences: {+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ webSecurity: true,+ webviewTag: false,+ backgroundThrottling: false,+ },+ });+ expect(win.webContents.setWindowOpenHandler.mock.calls[0][0]()).toEqual({ action: 'deny' });+ owner.dispose();+ expect(win.destroyed).toBe(true);+ expect(owner.contents).toBeNull();+ expect(() => owner.assertSender(valid)).toThrow('PERMISSION_DENIED');+ expect(failed).not.toHaveBeenCalled();+});++it('cancels pending readiness and rejects late old events without touching the replacement', async () => {+ const failed = vi.fn(),+ owner = new DesktopCaptureWindow(failed);+ const first = owner.start();+ const rejection = expect(first).rejects.toThrow('DESKTOP_VIDEO_STOPPED');+ const old = fake.windows[0];+ const second = owner.start();+ await rejection;+ const next = fake.windows[1];+ expect(() => owner.registered(event(old))).toThrow('PERMISSION_DENIED');+ old.webContents.emit('render-process-gone');+ old.webContents.emit('destroyed');+ expect(next.destroyed).toBe(false);+ expect(failed).not.toHaveBeenCalled();+ owner.registered(event(next));+ await second;+ expect(fake.sessions).toHaveLength(1); // bounded in-memory session, never persistent profiles+ owner.dispose();+});++it.each(['render-process-gone', 'will-navigate', 'will-redirect', 'destroyed'])(+ 'closes the lease on unexpected %s, once',+ async (name) => {+ const failed = vi.fn(),+ owner = new DesktopCaptureWindow(failed);+ const ready = owner.start();+ const win = fake.windows[0];+ owner.registered(event(win));+ await ready;+ const preventDefault = vi.fn();+ win.webContents.emit(name, { preventDefault });+ expect(win.destroyed).toBe(true);+ expect(failed).toHaveBeenCalledTimes(1);+ if (name.startsWith('will-')) expect(preventDefault).toHaveBeenCalled();+ },+);++it.each(['timeout', 'load'])('bounds %s failure without recreating a process', async (kind) => {+ vi.useFakeTimers();+ fake.loadFailure = kind === 'load';+ const failed = vi.fn(),+ owner = new DesktopCaptureWindow(failed);+ const ready = owner.start();+ const rejected = expect(ready).rejects.toThrow('DESKTOP_VIDEO_STOPPED');+ await vi.advanceTimersByTimeAsync(10_000);+ await rejected;+ expect(fake.windows).toHaveLength(1);+ expect(fake.windows[0].destroyed).toBe(true);+ expect(failed).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+});++it('denies app display/legacy capture while preserving physical microphone and camera', () => {+ const ses = {+ setDisplayMediaRequestHandler: vi.fn(),+ setPermissionCheckHandler: vi.fn(),+ setPermissionRequestHandler: vi.fn(),+ };+ denyAppDesktopCapture(ses as any);+ const check = ses.setPermissionCheckHandler.mock.calls[0][0];+ const request = ses.setPermissionRequestHandler.mock.calls[0][0];+ for (const mediaType of ['unknown', undefined])+ expect(check(null, 'media', '', { mediaType })).toBe(false);+ for (const mediaType of ['audio', 'video'])+ expect(check(null, 'media', '', { mediaType })).toBe(true);+ for (const types of [[], undefined, ['unknown']]) {+ const reply = vi.fn();+ request(null, 'media', reply, { mediaTypes: types });+ expect(reply).toHaveBeenCalledWith(false);+ }+ const reply = vi.fn();+ request(null, 'media', reply, { mediaTypes: ['audio'] });+ expect(reply).toHaveBeenLastCalledWith(true);+ request(null, 'display-capture', reply, {});+ expect(reply).toHaveBeenLastCalledWith(false);+ ses.setDisplayMediaRequestHandler.mock.calls[0][0]({}, reply);+ expect(reply).toHaveBeenLastCalledWith({});+});++it('capture CSP forbids arbitrary network, application frames and inline/eval scripts', () => {+ const csp = buildContentSecurityPolicy({+ isDev: false,+ devServerOrigin: null,+ desktopCapture: true,+ });+ expect(csp).toContain("connect-src 'none'");+ expect(csp).toContain("frame-src 'none'");+ expect(csp).not.toMatch(/https:|wss:|unsafe-inline|unsafe-eval/);+});diff --git a/apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.tsindex 62ddae11ed..4c8cbc7af7 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/hostCommands.test.ts@@ -21,7 +21,7 @@ function harness(sourceText = source) {parseDesktopIceReply,setTimeout,clearTimeout,- assertTrustedAppRendererEvent() {},+ captureWindow: { assertSender() {} },throwIpcError: () => {throw new Error('PERMISSION_DENIED');},diff --git a/apps/desktop/src/main/remote-desktop/capturePermissions.ts b/apps/desktop/src/main/remote-desktop/capturePermissions.tsnew file mode 100644index 0000000000..cc54ecced9--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/capturePermissions.ts@@ -0,0 +1,23 @@+import type { Session } from 'electron';++/** Remove desktop capture from the app session, including Chromium's legacy+ * chromeMediaSource path (reported as media with no physical mediaTypes).+ * Keep microphone/camera requests working; do not change unrelated permissions. */+export function denyAppDesktopCapture(ses: Session): void {+ ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));+ ses.setPermissionCheckHandler((_owner, permission, _origin, details) => {+ if (permission === 'media')+ return details.mediaType === 'audio' || details.mediaType === 'video';+ return true;+ });+ ses.setPermissionRequestHandler((_owner, permission, callback, details) => {+ if (permission === 'display-capture') return callback(false);+ if (permission === 'media') {+ const types = 'mediaTypes' in details ? details.mediaTypes : undefined;+ return callback(+ Boolean(types?.length && types.every((type) => type === 'audio' || type === 'video')),+ );+ }+ callback(true);+ });+}diff --git a/apps/desktop/src/main/remote-desktop/captureWindow.ts b/apps/desktop/src/main/remote-desktop/captureWindow.tsnew file mode 100644index 0000000000..4a829fdd4c--- /dev/null+++ b/apps/desktop/src/main/remote-desktop/captureWindow.ts@@ -0,0 +1,181 @@+import { BrowserWindow, session, type IpcMainInvokeEvent, type Session } from 'electron';+import path from 'node:path';+import { readFile } from 'node:fs/promises';+import { installContentSecurityPolicy, parseOrigin } from '../security/csp';+import { throwIpcError } from '../utils/ipcValidate';++declare const DESKTOP_CAPTURE_VITE_DEV_SERVER_URL: string | undefined;+declare const DESKTOP_CAPTURE_VITE_NAME: string;+const CAPTURE_URL = 'cindy-desktop-capture://capture/index.html';++/** Main owns one ephemeral capture process. Unlike a reusable UI tool window,+ * hiding is NOT a stop boundary: disposal must kill every media stream, including+ * ones that never registered a cooperative JS cleanup. No automatic restart. */+export class DesktopCaptureWindow {+ private window: BrowserWindow | null = null;+ private ready: {+ resolve(): void;+ reject(error: Error): void;+ timer: ReturnType<typeof setTimeout>;+ } | null = null;+ private captureSession: Session | null = null;+ private get url(): string {+ return DESKTOP_CAPTURE_VITE_DEV_SERVER_URL+ ? new URL('index.html', DESKTOP_CAPTURE_VITE_DEV_SERVER_URL).href+ : CAPTURE_URL;+ }++ constructor(private readonly failed: () => void) {}++ get contents() {+ return this.window?.webContents ?? null;+ }++ assertSender(event: IpcMainInvokeEvent): void {+ const owner = this.contents;+ if (+ !owner ||+ owner.isDestroyed() ||+ event.sender !== owner ||+ event.senderFrame !== owner.mainFrame ||+ event.senderFrame?.parent !== null ||+ event.senderFrame.url !== this.url+ )+ throwIpcError('PERMISSION_DENIED', 'Invalid desktop capture process');+ }++ registered(event: IpcMainInvokeEvent): void {+ this.assertSender(event);+ const pending = this.ready;+ this.ready = null;+ if (pending) {+ clearTimeout(pending.timer);+ pending.resolve();+ }+ }++ private getSession(): Session {+ if (this.captureSession) return this.captureSession;+ const ses = session.fromPartition('cindy-desktop-capture', { cache: false });+ this.captureSession = ses;+ installContentSecurityPolicy(ses, {+ isDev: Boolean(DESKTOP_CAPTURE_VITE_DEV_SERVER_URL),+ devServerOrigin: parseOrigin(DESKTOP_CAPTURE_VITE_DEV_SERVER_URL),+ desktopCapture: true,+ });+ const origin = `${new URL(this.url).protocol}//${new URL(this.url).host}`;+ ses.setPermissionCheckHandler(+ (owner, permission, requestingOrigin) =>+ owner === this.contents &&+ owner?.mainFrame.url === this.url &&+ (requestingOrigin === origin || requestingOrigin === `${origin}/`) &&+ permission === 'media',+ );+ ses.setPermissionRequestHandler((owner, permission, callback, details) => {+ callback(+ owner === this.contents &&+ owner?.mainFrame.url === this.url &&+ details.isMainFrame === true &&+ details.requestingUrl === this.url &&+ permission === 'media' &&+ 'mediaTypes' in details &&+ details.mediaTypes?.length === 0,+ );+ });+ ses.on('will-download', (event) => event.preventDefault());+ if (!DESKTOP_CAPTURE_VITE_DEV_SERVER_URL) {+ // Only packaged HTML/JS assets in this build's separate output directory.+ // No main app pages, user files, remote URL proxy or percent-decoded paths.+ ses.protocol.handle('cindy-desktop-capture', async (request) => {+ const url = new URL(request.url);+ if (+ request.method !== 'GET' ||+ url.host !== 'capture' ||+ url.search ||+ !/^\/(?:index\.html|assets\/[A-Za-z0-9_-]+\.js)$/.test(url.pathname)+ )+ return new Response(null, { status: 403 });+ try {+ const file = path.join(+ __dirname,+ '../renderer',+ DESKTOP_CAPTURE_VITE_NAME,+ url.pathname.slice(1),+ );+ const bytes = await readFile(file);+ return new Response(new Uint8Array(bytes), {+ headers: {+ 'Content-Type': url.pathname.endsWith('.html') ? 'text/html' : 'text/javascript',+ },+ });+ } catch {+ return new Response(null, { status: 404 });+ }+ });+ }+ return ses;+ }++ async start(): Promise<void> {+ this.dispose();+ const win = new BrowserWindow({+ show: false,+ focusable: false,+ skipTaskbar: true,+ width: 1,+ height: 1,+ webPreferences: {+ session: this.getSession(),+ preload: path.join(__dirname, 'desktopCapturePreload.js'),+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ nodeIntegrationInSubFrames: false,+ nodeIntegrationInWorker: false,+ webSecurity: true,+ allowRunningInsecureContent: false,+ experimentalFeatures: false,+ plugins: false,+ navigateOnDragDrop: false,+ webviewTag: false,+ backgroundThrottling: false,+ spellcheck: false,+ },+ });+ this.window = win;+ const failed = () => {+ if (this.window !== win) return;+ this.dispose();+ this.failed();+ };+ win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));+ win.webContents.on('will-attach-webview', (event) => event.preventDefault());+ win.webContents.on('will-navigate', (event) => {+ event.preventDefault();+ failed();+ });+ win.webContents.on('will-redirect', (event) => {+ event.preventDefault();+ failed();+ });+ win.webContents.on('render-process-gone', failed);+ win.webContents.on('destroyed', failed);+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(failed, 10_000);+ this.ready = { resolve, reject, timer };+ void win.loadURL(this.url).catch(failed);+ });+ }++ dispose(): void {+ const win = this.window;+ this.window = null; // Detach before destruction callbacks; never stop a replacement owner.+ const pending = this.ready;+ this.ready = null;+ if (pending) {+ clearTimeout(pending.timer);+ pending.reject(new Error('DESKTOP_VIDEO_STOPPED'));+ }+ if (win && !win.isDestroyed()) win.destroy();+ }+}diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.tsindex 196c98b62d..810bb23e7c 100644--- a/apps/desktop/src/main/remote-desktop/index.ts+++ b/apps/desktop/src/main/remote-desktop/index.ts@@ -1,12 +1,12 @@import {app,- BrowserWindow,desktopCapturer,ipcMain,nativeImage,powerMonitor,powerSaveBlocker,screen,+ session,shell,systemPreferences,type WebContents,@@ -26,10 +26,9 @@ import {type DesktopHostCommand,type DesktopHostReply,} from '../../shared/remoteDesktop';-import {- assertTrustedAppRendererEvent,- isTrustedAppRendererWindow,-} from '../security/trustedAppRenderer';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';+import { DesktopCaptureWindow } from './captureWindow';+import { denyAppDesktopCapture } from './capturePermissions';import { readDeviceLinkSettings, writeDeviceLinkSetting } from '../device-link/settings-store';import { throwIpcError } from '../utils/ipcValidate';import { RemoteDesktopController } from './controller';@@ -84,6 +83,7 @@ const permissions = new RemoteDesktopPermissionsService({});let host: WebContents | null = null;+const captureWindow = new DesktopCaptureWindow(() => remoteDesktop.stop());const nativeCapture = new NativeDesktopCapture();let displayAwake: number | null = null;let nativeDisplay: string | null = null;@@ -91,19 +91,15 @@ let windowsAvailable = false;let captureGrant: { source: DesktopCapturerSource; lease: string; audio: boolean } | null = null;const supportsSystemAudio =process.platform === 'win32' ||- (process.platform === 'darwin' && typeof process.getSystemVersion === 'function' &&+ (process.platform === 'darwin' &&+ typeof process.getSystemVersion === 'function' &&(() => {const [major, minor] = process.getSystemVersion().split('.').map(Number);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;@@ -127,13 +123,9 @@ function stopVideo(): void {nativeDisplay = null;captureGrant = null;setVideoLease(null);- if (host && !host.isDestroyed()) {- if (isTrustedAppRendererWindow(BrowserWindow.fromWebContents(host)))- host.send(DESKTOP_LOCAL.COMMAND, {- id: randomUUID(),- op: 'stop',- } satisfies DesktopHostCommand);- }+ host = null;+ preparingOffer = false;+ captureWindow.dispose();if (pending) {clearTimeout(pending.timer);pending.reject(new Error('DESKTOP_VIDEO_STOPPED'));@@ -146,11 +138,15 @@ async function sources(thumbnail = false, timeoutMs = 5000) {systemPreferences.getMediaAccessStatus('screen') !== 'granted')throw new Error('DESKTOP_SCREEN_PERMISSION_REQUIRED');- return enumerateDesktopSources(() => desktopCapturer.getSources({- types: ['screen'],- thumbnailSize: thumbnail ? { width: 1280, height: 1280 } : { width: 0, height: 0 },- fetchWindowIcons: false,- }), timeoutMs);+ return enumerateDesktopSources(+ () =>+ desktopCapturer.getSources({+ types: ['screen'],+ thumbnailSize: thumbnail ? { width: 1280, height: 1280 } : { width: 0, height: 0 },+ fetchWindowIcons: false,+ }),+ timeoutMs,+ );}async function offer(lease: RemoteDesktopLease,@@ -159,72 +155,74 @@ async function offer(cursorOverlay?: boolean,attemptId?: string,): Promise<string> {- if (- !host ||- host.isDestroyed() ||- !isTrustedAppRendererWindow(BrowserWindow.fromWebContents(host))- )- throw new Error('DESKTOP_VIDEO_UNAVAILABLE');if (pending || preparingOffer) throw new Error('DESKTOP_VIDEO_BUSY');+ stopVideo();preparingOffer = true;- const generation = ++offerGeneration;- nativeCapture.stop();- nativeDisplay = null;- setVideoLease(null);- captureGrant = null;- const currentHost = host;- let source: DesktopCapturerSource | null = null;- let nativeAvailable = process.platform === 'darwin';+ const generation = offerGeneration;+ const current = () => generation === offerGeneration && remoteDesktop.hasLease(lease.lease);try {- nativeAvailable ||=- process.platform === 'win32' && (await readWindowsDesktopSupport()) === 'ready';- try {- const available = await sources(false, nativeAvailable ? 2000 : 5000);- source = desktopCaptureSource(available, lease.display.id, screen.getAllDisplays());- } catch (error) {- // A locked macOS session can reject Chromium's source enumeration even- // though the user has granted capture. Only the native adapter may recover.- if (- !nativeAvailable ||- (process.platform === 'darwin' &&- systemPreferences.getMediaAccessStatus('screen') !== 'granted')- )- throw error;+ const ready = captureWindow.start();+ host = captureWindow.contents;+ const currentHost = host;+ await ready;+ if (!current() || host !== currentHost || !currentHost || currentHost.isDestroyed())+ throw new Error('DESKTOP_LEASE_EXPIRED');+ let source: DesktopCapturerSource | null = null;+ let nativeAvailable = process.platform === 'darwin';+ {+ nativeAvailable ||=+ process.platform === 'win32' && (await readWindowsDesktopSupport()) === 'ready';+ try {+ const available = await sources(false, nativeAvailable ? 2000 : 5000);+ source = desktopCaptureSource(available, lease.display.id, screen.getAllDisplays());+ } catch (error) {+ // A locked macOS session can reject Chromium's source enumeration even+ // though the user has granted capture. Only the native adapter may recover.+ if (+ !nativeAvailable ||+ (process.platform === 'darwin' &&+ systemPreferences.getMediaAccessStatus('screen') !== 'granted')+ )+ throw error;+ }}+ if (!source && !nativeAvailable) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ if (+ generation !== offerGeneration ||+ !remoteDesktop.hasLease(lease.lease) ||+ host !== currentHost ||+ currentHost.isDestroyed()+ )+ throw new Error('DESKTOP_LEASE_EXPIRED');+ if (settings?.audio && !supportsSystemAudio) throw new Error('DESKTOP_AUDIO_UNAVAILABLE');+ captureGrant = source ? { source, lease: lease.lease, audio: settings?.audio === true } : null;+ nativeDisplay = nativeAvailable ? lease.display.id : null;+ nativeOverlay = cursorOverlay === true && process.platform === 'darwin';+ nativeSettings = settings;+ setVideoLease(lease.lease);+ videoAttempt = attemptId;+ const result = await requestHost(+ {+ id: randomUUID(),+ op: 'offer',+ sourceId: source?.id,+ nativeCapture: nativeAvailable,+ cursorOverlay: nativeOverlay,+ lease: lease.lease,+ sdp,+ settings,+ attemptId,+ },+ 18_000,+ );+ if (typeof result !== 'string') throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ return result;+ } catch (error) {+ if (generation === offerGeneration) stopVideo();+ throw error;} finally {- preparingOffer = false;+ if (generation === offerGeneration) preparingOffer = false;}- if (!source && !nativeAvailable) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');- if (- generation !== offerGeneration ||- !remoteDesktop.hasLease(lease.lease) ||- host !== currentHost ||- currentHost.isDestroyed()- )- throw new Error('DESKTOP_LEASE_EXPIRED');- if (settings?.audio && !supportsSystemAudio) throw new Error('DESKTOP_AUDIO_UNAVAILABLE');- captureGrant = source ? { source, lease: lease.lease, audio: settings?.audio === true } : null;- nativeDisplay = nativeAvailable ? lease.display.id : null;- nativeOverlay = cursorOverlay === true && process.platform === 'darwin';- nativeSettings = settings;- setVideoLease(lease.lease);- videoAttempt = attemptId;- const result = await requestHost(- {- id: randomUUID(),- op: 'offer',- sourceId: source?.id,- nativeCapture: nativeAvailable,- cursorOverlay: nativeOverlay,- lease: lease.lease,- sdp,- settings,- attemptId,- },- 18_000,- );- if (typeof result !== 'string') throw new Error('DESKTOP_VIDEO_UNAVAILABLE');- return result;}/** One bounded command to the existing capture owner; never reset the shared device link. */@@ -318,7 +316,11 @@ export const remoteDesktop = new RemoteDesktopController({// Compatibility viewers must also wake/capture without waiting for// Chromium's thumbnail enumeration, which may hang on a sleeping display.if (process.platform === 'darwin' || windowsAvailable) {- const frame = await nativeCapture.frame(displayId, cursorOverlay === true && process.platform === 'darwin', nativeSettings);+ const frame = await nativeCapture.frame(+ displayId,+ cursorOverlay === true && process.platform === 'darwin',+ nativeSettings,+ );return encodeNativeRelayFrame(frame, (jpeg) => nativeImage.createFromBuffer(jpeg));}const source = desktopCaptureSource(await sources(true), displayId, screen.getAllDisplays());@@ -348,9 +350,8 @@ export const remoteDesktop = new RemoteDesktopController({},});-export function registerRemoteDesktopIpc(refreshBackgroundThrottling: () => void): void {- onVideoActivityChanged = refreshBackgroundThrottling;- onVideoActivityChanged();+export function registerRemoteDesktopIpc(): void {+ denyAppDesktopCapture(session.defaultSession);const timer = setInterval(() => remoteDesktop.tick(), 1000);timer.unref();app.on('before-quit', () => {@@ -391,7 +392,7 @@ export function registerRemoteDesktopIpc(refreshBackgroundThrottling: () => voidpowerMonitor.on('lock-screen', sessionChanged);powerMonitor.on('unlock-screen', sessionChanged);ipcMain.handle(DESKTOP_LOCAL.NATIVE_FRAME, async (event, lease: unknown) => {- assertTrustedAppRendererEvent(event);+ captureWindow.assertSender(event);if (event.sender !== host ||typeof lease !== 'string' ||@@ -401,12 +402,14 @@ export function registerRemoteDesktopIpc(refreshBackgroundThrottling: () => void)throwIpcError('PERMISSION_DENIED', 'Invalid desktop capture lease');const generation = offerGeneration;- const jpeg = await nativeCapture.frame(nativeDisplay, nativeOverlay, nativeSettings).catch(() => null);+ const jpeg = await nativeCapture+ .frame(nativeDisplay, nativeOverlay, nativeSettings)+ .catch(() => null);if (generation !== offerGeneration || !remoteDesktop.hasLease(lease)) return null;return jpeg;});ipcMain.handle(DESKTOP_LOCAL.VIEW_HEARTBEAT, (event, lease: unknown) => {- assertTrustedAppRendererEvent(event);+ captureWindow.assertSender(event);if (event.sender !== host || typeof lease !== 'string' || lease !== videoLease)throwIpcError('PERMISSION_DENIED', 'Invalid desktop viewer heartbeat');remoteDesktop.viewHeartbeat(lease);@@ -472,46 +475,35 @@ export function registerRemoteDesktopIpc(refreshBackgroundThrottling: () => voidremoteDesktop.stopByUser();});ipcMain.handle(DESKTOP_LOCAL.REGISTER, (event) => {- assertTrustedAppRendererEvent(event);- if (getDeepLinkMainWindow()?.webContents !== event.sender)- throwIpcError('PERMISSION_DENIED', 'Only the main window can host desktop capture');- if (host && !host.isDestroyed() && host !== event.sender)- throwIpcError('PERMISSION_DENIED', 'Desktop host already registered');- if (host === event.sender) return;- host = event.sender;- const owner = host;+ captureWindow.registered(event);+ const owner = event.sender;owner.session.setDisplayMediaRequestHandler((request, callback) => {const grant = captureGrant;if (!grant ||host !== owner ||request.frame !== owner.mainFrame ||- !isTrustedAppRendererWindow(BrowserWindow.fromWebContents(owner)) ||!remoteDesktop.hasLease(grant.lease) ||!pending ||+ pending.op !== 'offer' ||!request.videoRequested) {callback({});return;}- captureGrant = null; // single-use and bound to the exact active offer+ captureGrant = null;callback({video: grant.source,...(grant.audio && request.audioRequested ? { audio: 'loopback' as const } : {}),});});- const stop = () => {- if (host === owner) {- remoteDesktop.stop();- host = null;- }- };- owner.once('destroyed', stop);- owner.on('render-process-gone', stop);- owner.on('will-navigate', stop);+ });+ ipcMain.handle(DESKTOP_LOCAL.CAPTURE_STOP, (event) => {+ captureWindow.assertSender(event);+ remoteDesktop.stop();});ipcMain.handle(DESKTOP_LOCAL.REPLY, (event, id: unknown, sdp: unknown) => {- assertTrustedAppRendererEvent(event);+ captureWindow.assertSender(event);if (event.sender !== host || !pending || id !== pending.id)throwIpcError('PERMISSION_DENIED', 'Invalid desktop host reply');const request = pending;@@ -545,7 +537,7 @@ export function registerRemoteDesktopIpc(refreshBackgroundThrottling: () => voidipcMain.handle(DESKTOP_LOCAL.INPUT,(event, lease: unknown, sequence: unknown, events: unknown) => {- assertTrustedAppRendererEvent(event);+ captureWindow.assertSender(event);if (event.sender !== host ||lease !== videoLease ||diff --git a/apps/desktop/src/main/security/csp.ts b/apps/desktop/src/main/security/csp.tsindex 8a24258746..93dad421a4 100644--- a/apps/desktop/src/main/security/csp.ts+++ b/apps/desktop/src/main/security/csp.ts@@ -64,6 +64,8 @@ const CUSTOM_MEDIA_SCHEMES = [/** Inputs that shape the emitted policy. All origins are already normalized. */export interface CspContext {+ /** Isolated capture document: no arbitrary network, subframes or application UI. */+ desktopCapture?: boolean;/** True when the renderer is served by the Vite dev server (needs eval + ws). */isDev: boolean;/** Vite dev-server origin (dev only); added to connect-src. `null` in prod. */@@ -94,6 +96,9 @@ export function parseOrigin(url: string | null | undefined): string | null {*/export function buildContentSecurityPolicy(ctx: CspContext): string {const { isDev, devServerOrigin } = ctx;+ if (ctx.desktopCapture) {+ return "default-src 'none'; script-src 'self'; connect-src 'none'; img-src blob: data:; media-src blob:; object-src 'none'; frame-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'";+ }// script-src is the crown jewel. The XSS→preload escalation path is an// attacker getting THEIR script to run — via an injected inline <script>@@ -195,7 +200,9 @@ export function installContentSecurityPolicy(session: Session, ctx: CspContext):if (cspInstalledSessions.has(session)) {// Re-installing would silently replace our own listener — and hint that// some caller may be racing onHeadersReceived. Skip + warn instead.- cspLog.warn('installContentSecurityPolicy called twice on the same session — ignoring the second call');+ cspLog.warn(+ 'installContentSecurityPolicy called twice on the same session — ignoring the second call',+ );return;}cspInstalledSessions.add(session);@@ -216,6 +223,7 @@ export function installContentSecurityPolicy(session: Session, ctx: CspContext):// Exact-origin match (not startsWith) so e.g. http://localhost:51730// cannot piggyback on a http://localhost:5173 dev origin.const isAppDocument =+ (ctx.desktopCapture === true && url === 'cindy-desktop-capture://capture/index.html') ||url.startsWith('file://') ||(ctx.devServerOrigin !== null && parseOrigin(url) === ctx.devServerOrigin);if (!isAppDocument) {@@ -229,10 +237,7 @@ export function installContentSecurityPolicy(session: Session, ctx: CspContext):// intersect two policies and silently over-tighten.for (const key of Object.keys(responseHeaders)) {const lower = key.toLowerCase();- if (- lower === 'content-security-policy' ||- lower === 'content-security-policy-report-only'- ) {+ if (lower === 'content-security-policy' || lower === 'content-security-policy-report-only') {delete responseHeaders[key];}}diff --git a/apps/desktop/src/preload/desktopCapturePreload.ts b/apps/desktop/src/preload/desktopCapturePreload.tsnew file mode 100644index 0000000000..a5f9f1134a--- /dev/null+++ b/apps/desktop/src/preload/desktopCapturePreload.ts@@ -0,0 +1,26 @@+import { contextBridge, ipcRenderer } from 'electron';+import {+ DESKTOP_LOCAL,+ type DesktopCaptureApi,+ type DesktopHostCommand,+} from '../shared/remoteDesktop';++/** No settings, filesystem, chat, credentials or general IPC in the capture process. */+const api: DesktopCaptureApi = {+ registerHost: () => ipcRenderer.invoke(DESKTOP_LOCAL.REGISTER),+ stop: () => ipcRenderer.invoke(DESKTOP_LOCAL.CAPTURE_STOP),+ onCommand: (listener) => {+ const wrapped = (_event: Electron.IpcRendererEvent, command: DesktopHostCommand) =>+ listener(command);+ ipcRenderer.on(DESKTOP_LOCAL.COMMAND, wrapped);+ return () => {+ ipcRenderer.removeListener(DESKTOP_LOCAL.COMMAND, wrapped);+ };+ },+ reply: (id, result) => ipcRenderer.invoke(DESKTOP_LOCAL.REPLY, id, result),+ input: (lease, sequence, events) =>+ ipcRenderer.invoke(DESKTOP_LOCAL.INPUT, lease, sequence, events),+ viewHeartbeat: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.VIEW_HEARTBEAT, lease),+ nativeFrame: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.NATIVE_FRAME, lease),+};+contextBridge.exposeInMainWorld('desktopCapture', api);diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 1eb20e4586..ff0e0d84b6 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1,5 +1,5 @@import { contextBridge, ipcRenderer, webUtils } from 'electron';-import { DESKTOP_LOCAL, type RemoteDesktopApi, type DesktopHostCommand } from '../shared/remoteDesktop';+import { DESKTOP_LOCAL, type RemoteDesktopApi } from '../shared/remoteDesktop';import { DEVICE_LINK_PUSH } from '../shared/deviceLinkIpc';import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';import type { AppearanceSettings } from '../shared/appearanceSettings';@@ -1150,8 +1150,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// 意识仓库 (shared/ghost.ts)。listSync 走 sendSync:意识面板要与内置// 面板同帧注册进布局引擎(规则 7 无跳变);目录扫描极小,同步读不卡启动。ghosts: {- recommendationsSync: (): import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot =>- ipcRenderer.sendSync('ghosts:recommendations'),+ recommendationsSync:+ (): import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot =>+ ipcRenderer.sendSync('ghosts:recommendations'),listSync: (): { ghosts: unknown[] } => ipcRenderer.sendSync('ghosts:list'),recentUsageSync: (): { ids: string[] } => {try {@@ -4187,16 +4188,6 @@ contextBridge.exposeInMainWorld('electronAPI', {enable: (enabled) => ipcRenderer.invoke(DESKTOP_LOCAL.ENABLE, enabled),windowsSupport: (enabled) => ipcRenderer.invoke(DESKTOP_LOCAL.WINDOWS_SUPPORT, enabled),stop: () => ipcRenderer.invoke(DESKTOP_LOCAL.STOP),- registerHost: () => ipcRenderer.invoke(DESKTOP_LOCAL.REGISTER),- onCommand: (listener) => {- const wrapped = (_event: Electron.IpcRendererEvent, command: DesktopHostCommand) => listener(command);- ipcRenderer.on(DESKTOP_LOCAL.COMMAND, wrapped);- return () => { ipcRenderer.removeListener(DESKTOP_LOCAL.COMMAND, wrapped); };- },- reply: (id, sdp) => ipcRenderer.invoke(DESKTOP_LOCAL.REPLY, id, sdp),- input: (lease, sequence, events) => ipcRenderer.invoke(DESKTOP_LOCAL.INPUT, lease, sequence, events),- viewHeartbeat: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.VIEW_HEARTBEAT, lease),- nativeFrame: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.NATIVE_FRAME, lease),} satisfies RemoteDesktopApi,deviceLink: {getState: (): Promise<{diff --git a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsxindex b8add113da..753c589dca 100644--- a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx+++ b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx@@ -1,20 +1,10 @@import { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import {- isDesktopInput,- parseDesktopIceCandidates,- REMOTE_DESKTOP_ICE_SERVERS,- REMOTE_DESKTOP_NETWORK,- type RemoteDesktopIceCandidate,- type DesktopInput,- type RemoteDesktopCursor,-} from '@cindy/device-link';import type { DesktopLocalState } from '../../../shared/remoteDesktop';import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { RemoteDesktopPermissions } from '@/components/settings/RemoteDesktopPermissions';-import { nativeCaptureStream } from './nativeCaptureStream';-/** Lives only in the existing trusted main renderer; no remote document gets this bridge. */+/** Main-window status and permission UI; it has no capture or media bridge. */export function RemoteDesktopHost() {const { t } = useTranslation();const [state, setState] = useState<DesktopLocalState | null>(null);@@ -23,376 +13,7 @@ export function RemoteDesktopHost() {useEffect(() => {const api = window.electronAPI?.remoteDesktop;if (!api) return;- let peer: RTCPeerConnection | null = null;- let stream: MediaStream | null = null;- let generation = 0;let disposed = false;- let heartbeat: ReturnType<typeof setInterval> | null = null;- let latestCursor: RemoteDesktopCursor | null | undefined;- let cursorTimer: ReturnType<typeof setInterval> | null = null;- let native: Awaited<ReturnType<typeof nativeCaptureStream>> | null = null;- let recoverCapture: (() => void) | null = null;- let activeLease: string | null = null;- let attemptId: string | undefined;- let localCandidates: RemoteDesktopIceCandidate[] = [];- let remoteCandidates = new Set<string>();- let disconnectedTimer: ReturnType<typeof setTimeout> | undefined;- let gatheringTimer: ReturnType<typeof setTimeout> | undefined;- let finishGathering: (() => void) | undefined;- let exchanging = false;- const stop = () => {- generation++;- exchanging = false;- clearTimeout(disconnectedTimer);- clearTimeout(gatheringTimer);- finishGathering?.();- finishGathering = undefined;- disconnectedTimer = gatheringTimer = undefined;- attemptId = undefined;- localCandidates = [];- remoteCandidates = new Set();- latestCursor = undefined;- if (cursorTimer) clearInterval(cursorTimer);- cursorTimer = null;- native?.stop();- native = null;- recoverCapture = null;- activeLease = null;- if (heartbeat) clearInterval(heartbeat);- heartbeat = null;- peer?.close();- peer = null;- stream?.getTracks().forEach((track) => track.stop());- stream = null;- };- const unsubscribe = api.onCommand((command) => {- if (command.op === 'ice') {- const rtc = peer,- current = generation;- if (exchanging) {- void api.reply(command.id, { error: 'DESKTOP_VIDEO_STOPPED' }).catch(() => {});- return;- }- exchanging = true;- const seen = remoteCandidates;- void (async () => {- if (- !rtc ||- command.lease !== activeLease ||- !attemptId ||- command.attemptId !== attemptId ||- !Number.isSafeInteger(command.after) ||- command.after! < 0 ||- command.after! > localCandidates.length- )- throw new Error('DESKTOP_VIDEO_STOPPED');- for (const candidate of parseDesktopIceCandidates(command.candidates)) {- if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');- const key = JSON.stringify(candidate);- if (seen.has(key)) continue;- if (seen.size >= REMOTE_DESKTOP_NETWORK.maxCandidates)- throw new Error('DESKTOP_VIDEO_UNAVAILABLE');- await rtc.addIceCandidate(candidate);- seen.add(key);- }- if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');- const candidates = localCandidates.slice(- command.after,- command.after! + REMOTE_DESKTOP_NETWORK.batchSize,- );- await api.reply(command.id, {- attemptId,- candidates,- next: command.after! + candidates.length,- complete:- rtc.iceGatheringState === 'complete' &&- command.after! + candidates.length === localCandidates.length,- });- })()- .catch(() => api.reply(command.id, { error: 'DESKTOP_VIDEO_STOPPED' }).catch(() => {}))- .finally(() => {- if (current === generation) exchanging = false;- });- return;- }- if (command.op === 'capture-reset') {- if (command.lease === activeLease) {- native?.clear();- recoverCapture?.();- }- return;- }- stop();- if (- command.op !== 'offer' ||- !command.lease ||- !command.sdp ||- (!command.sourceId && !command.nativeCapture)- )- return;- const current = generation;- const lease = command.lease;- activeLease = lease;- attemptId = command.attemptId;- void (async () => {- try {- const capture = async () =>- command.settings?.audio- ? await navigator.mediaDevices.getDisplayMedia({- audio: true,- video: { frameRate: { ideal: command.settings.fps, max: command.settings.fps } },- })- : await navigator.mediaDevices.getUserMedia({- audio: false,- video: {- mandatory: {- chromeMediaSource: 'desktop',- chromeMediaSourceId: command.sourceId,- maxFrameRate: command.settings?.fps ?? 30,- ...(!command.settings ? { maxWidth: 1920, maxHeight: 1920 } : {}),- },- } as MediaTrackConstraints,- });- const boundedCapture = async () => {- if (!command.sourceId) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');- let abandoned = false;- let timeout: ReturnType<typeof setTimeout> | undefined;- try {- return await Promise.race([- capture().then((value) => {- if (abandoned || current !== generation) {- value.getTracks().forEach((track) => track.stop());- throw new Error('DESKTOP_VIDEO_STOPPED');- }- return value;- }),- new Promise<never>((_, reject) => {- timeout = setTimeout(() => {- abandoned = true;- reject(new Error('DESKTOP_VIDEO_TIMEOUT'));- }, command.nativeCapture ? 2000 : 10000);- }),- ]);- } finally {- if (timeout) clearTimeout(timeout);- }- };- const nativeStream = async () => {- const result = await nativeCaptureStream(- () => api.nativeFrame(lease),- () => current === generation,- () => stop(),- (value) => { if (current === generation) latestCursor = value; },- command.cursorOverlay ? (command.settings?.fps ?? 30) : 15,- );- if (current !== generation) {- result.stop();- throw new Error('DESKTOP_VIDEO_STOPPED');- }- native = result;- return result.stream;- };- let captured: MediaStream;- if (command.cursorOverlay) {- // Chromium in our runtime exposes no cursor constraint. Use the- // cursor-free native video while retaining the normal audio track.- let audioSource: MediaStream | null = null;- try {- if (command.settings?.audio && command.sourceId) {- try {- audioSource = await boundedCapture();- } catch (error) {- if (current !== generation) throw error;- // Validate the final track set below, including native video.- }- }- captured = await nativeStream();- if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');- for (const track of audioSource?.getAudioTracks() ?? []) captured.addTrack(track);- audioSource?.getVideoTracks().forEach((track) => track.stop());- } catch (error) {- audioSource?.getTracks().forEach((track) => track.stop());- throw error;- }- } else try {- captured = await boundedCapture();- } catch (error) {- if (!command.nativeCapture || current !== generation) throw error;- captured = await nativeStream();- }- if (current !== generation) {- captured.getTracks().forEach((track) => track.stop());- return;- }- if (command.settings?.audio && !captured.getAudioTracks().length) {- captured.getTracks().forEach((track) => track.stop());- throw new Error('DESKTOP_AUDIO_UNAVAILABLE');- }- stream = captured;- const rtc = new RTCPeerConnection({- iceServers: REMOTE_DESKTOP_ICE_SERVERS,- });- peer = rtc;- rtc.onicecandidate = ({ candidate }) => {- if (!command.attemptId || current !== generation || !candidate?.candidate) return;- if (localCandidates.length >= REMOTE_DESKTOP_NETWORK.maxCandidates) {- stop();- return;- }- localCandidates.push({- candidate: candidate.candidate,- sdpMid: candidate.sdpMid,- sdpMLineIndex: candidate.sdpMLineIndex,- ...(candidate.usernameFragment- ? { usernameFragment: candidate.usernameFragment }- : {}),- });- };- let recovering = false;- recoverCapture = () => {- if (!command.nativeCapture || native || recovering || current !== generation) return;- recovering = true;- void (async () => {- const replacement = await nativeStream();- const sender = rtc.getSenders().find((item) => item.track?.kind === 'video');- if (!sender || current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');- await sender.replaceTrack(replacement.getVideoTracks()[0]);- captured.getVideoTracks().forEach((track) => {- track.onended = null;- track.onmute = null;- track.stop();- });- })().catch(() => {- if (current === generation) stop();- });- };- captured.getVideoTracks().forEach((track) => {- track.onended = () => recoverCapture?.();- track.onmute = () => recoverCapture?.();- });- rtc.onconnectionstatechange = () => {- if (current !== generation) return;- if (['failed', 'closed'].includes(rtc.connectionState)) {- stop();- return;- }- if (rtc.connectionState === 'disconnected') {- if (!disconnectedTimer)- disconnectedTimer = setTimeout(() => {- if (current === generation && rtc.connectionState === 'disconnected') stop();- }, REMOTE_DESKTOP_NETWORK.disconnectedMs);- } else {- clearTimeout(disconnectedTimer);- disconnectedTimer = undefined;- }- };- rtc.ondatachannel = ({ channel }) => {- if (channel.label !== 'input-v1') {- channel.close();- return;- }- if (command.cursorOverlay) {- let lastCursor = '';- cursorTimer = setInterval(() => {- if (latestCursor === undefined || channel.readyState !== 'open' ||- current !== generation || channel.bufferedAmount > 65536) return;- const data = JSON.stringify({ type: 'cursor', cursor: latestCursor });- if (data !== lastCursor) { channel.send(data); lastCursor = data; }- }, 50);- }- let pending = 0;- let challenge = '';- heartbeat = setInterval(() => {- if (channel.readyState !== 'open' || current !== generation) return;- challenge = crypto.randomUUID();- channel.send(JSON.stringify({ type: 'viewPing', challenge }));- }, 2000);- channel.onmessage = ({ data }) => {- if (current !== generation) return;- if (typeof data === 'string' && challenge && data === challenge) {- challenge = '';- void api.viewHeartbeat(lease).catch(() => {});- return;- }- if (typeof data !== 'string' || data.length > 32_768 || pending >= 8) {- stop();- void api.stop().catch(() => {});- return;- }- try {- const message = JSON.parse(data) as { sequence: number; events: DesktopInput[] };- if (- !Number.isSafeInteger(message.sequence) ||- !Array.isArray(message.events) ||- message.events.length > 64 ||- !message.events.every(isDesktopInput)- ) {- stop();- void api.stop().catch(() => {});- return;- }- pending++;- void api- .input(lease, message.sequence, message.events)- .catch(() => channel.close())- .finally(() => {- pending--;- });- } catch {- stop();- void api.stop().catch(() => {});- }- };- };- stream.getTracks().forEach((track) => rtc.addTrack(track, captured));- await rtc.setRemoteDescription({ type: 'offer', sdp: command.sdp });- await rtc.setLocalDescription(await rtc.createAnswer());- for (const sender of rtc.getSenders()) {- if (sender.track?.kind !== 'video' || !command.settings) continue;- const parameters = sender.getParameters();- if (!parameters.encodings?.length) continue;- for (const encoding of parameters.encodings) {- encoding.maxFramerate = command.settings.fps;- if (command.settings.bitrate) encoding.maxBitrate = command.settings.bitrate;- }- await sender.setParameters(parameters);- }- if (!command.attemptId)- await new Promise<void>((resolve) => {- finishGathering = resolve;- if (rtc.iceGatheringState === 'complete') {- resolve();- return;- }- gatheringTimer = setTimeout(resolve, REMOTE_DESKTOP_NETWORK.legacyGatherMs);- rtc.onicegatheringstatechange = () => {- if (rtc.iceGatheringState === 'complete') {- clearTimeout(gatheringTimer);- resolve();- }- };- });- if (current === generation)- await api.reply(command.id, rtc.localDescription?.sdp ?? null);- } catch (error) {- if (current === generation) {- stop();- const code = error instanceof Error ? error.message : '';- await api- .reply(command.id, {- error:- code === 'DESKTOP_AUDIO_UNAVAILABLE'- ? code- : code === 'DESKTOP_VIDEO_TIMEOUT'- ? code- : 'DESKTOP_VIDEO_UNAVAILABLE',- })- .catch(() => {});- }- }- })();- });- void api.registerHost().catch(() => {});let readingState = false;const refresh = () => {if (readingState || dismissing.current) return;@@ -413,9 +34,6 @@ export function RemoteDesktopHost() {return () => {disposed = true;clearInterval(timer);- unsubscribe();- stop();- void api.stop().catch(() => {});};}, []);if (!state) return null;diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/RemoteDesktopHost.test.tsx b/apps/desktop/src/renderer/features/remote-desktop/__tests__/RemoteDesktopHost.test.tsxindex dafeafac8a..955d501c74 100644--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/RemoteDesktopHost.test.tsx+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/RemoteDesktopHost.test.tsx@@ -1,14 +1,18 @@// @vitest-environment jsdomimport { act, cleanup, render } from '@testing-library/react';import { afterEach, expect, it, vi } from 'vitest';-import { RemoteDesktopHost } from '../RemoteDesktopHost';+import { startDesktopCaptureHost } from '../captureHost';+const disposers: Array<() => void> = [];import { nativeCaptureStream } from '../nativeCaptureStream';vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('@/components/ui/confirm-dialog', () => ({ ConfirmDialog: () => null }));-vi.mock('@/components/settings/RemoteDesktopPermissions', () => ({ RemoteDesktopPermissions: () => null }));+vi.mock('@/components/settings/RemoteDesktopPermissions', () => ({+ RemoteDesktopPermissions: () => null,+}));vi.mock('../nativeCaptureStream', () => ({ nativeCaptureStream: vi.fn() }));afterEach(() => {+ disposers.splice(0).forEach((dispose) => dispose());cleanup();vi.unstubAllGlobals();vi.useRealTimers();@@ -50,7 +54,7 @@ it.each(['rejected', 'missing'] as const)(},},});- render(<RemoteDesktopHost />);+ disposers.push(startDesktopCaptureHost(window.electronAPI.remoteDesktop as any));await act(async () => {command({op: 'offer',@@ -100,7 +104,7 @@ it('exchanges replayable candidates without recapturing, tolerates transient disconst track = { stop: vi.fn() },stream = { getTracks: () => [track], getVideoTracks: () => [track] };const capture = vi.fn().mockResolvedValue(stream);- vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: capture } });+ vi.stubGlobal('navigator', { mediaDevices: { getDisplayMedia: capture } });let command!: (value: any) => void;const reply = vi.fn().mockResolvedValue(undefined);Object.assign(window, {@@ -117,7 +121,7 @@ it('exchanges replayable candidates without recapturing, tolerates transient dis},},});- render(<RemoteDesktopHost />);+ disposers.push(startDesktopCaptureHost(window.electronAPI.remoteDesktop as any));const offer = {op: 'offer',id: 'offer',diff --git a/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts b/apps/desktop/src/renderer/features/remote-desktop/captureHost.tsnew file mode 100644index 0000000000..17b58087c1--- /dev/null+++ b/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts@@ -0,0 +1,390 @@+import {+ isDesktopInput,+ parseDesktopIceCandidates,+ REMOTE_DESKTOP_ICE_SERVERS,+ REMOTE_DESKTOP_NETWORK,+ type RemoteDesktopIceCandidate,+ type DesktopInput,+ type RemoteDesktopCursor,+} from '@cindy/device-link';+import type { DesktopCaptureApi } from '../../../shared/remoteDesktop';+import { nativeCaptureStream } from './nativeCaptureStream';++/** Runs exclusively in the isolated capture renderer; never import into the chat entry. */+export function startDesktopCaptureHost(api: DesktopCaptureApi): () => void {+ let peer: RTCPeerConnection | null = null;+ let stream: MediaStream | null = null;+ let generation = 0;+ let heartbeat: ReturnType<typeof setInterval> | null = null;+ let latestCursor: RemoteDesktopCursor | null | undefined;+ let cursorTimer: ReturnType<typeof setInterval> | null = null;+ let native: Awaited<ReturnType<typeof nativeCaptureStream>> | null = null;+ let recoverCapture: (() => void) | null = null;+ let activeLease: string | null = null;+ let attemptId: string | undefined;+ let localCandidates: RemoteDesktopIceCandidate[] = [];+ let remoteCandidates = new Set<string>();+ let disconnectedTimer: ReturnType<typeof setTimeout> | undefined;+ let gatheringTimer: ReturnType<typeof setTimeout> | undefined;+ let finishGathering: (() => void) | undefined;+ let exchanging = false;+ const stop = () => {+ generation++;+ exchanging = false;+ clearTimeout(disconnectedTimer);+ clearTimeout(gatheringTimer);+ finishGathering?.();+ finishGathering = undefined;+ disconnectedTimer = gatheringTimer = undefined;+ attemptId = undefined;+ localCandidates = [];+ remoteCandidates = new Set();+ latestCursor = undefined;+ if (cursorTimer) clearInterval(cursorTimer);+ cursorTimer = null;+ native?.stop();+ native = null;+ recoverCapture = null;+ activeLease = null;+ if (heartbeat) clearInterval(heartbeat);+ heartbeat = null;+ peer?.close();+ peer = null;+ stream?.getTracks().forEach((track) => track.stop());+ stream = null;+ };+ const unsubscribe = api.onCommand((command) => {+ if (command.op === 'ice') {+ const rtc = peer,+ current = generation;+ if (exchanging) {+ void api.reply(command.id, { error: 'DESKTOP_VIDEO_STOPPED' }).catch(() => {});+ return;+ }+ exchanging = true;+ const seen = remoteCandidates;+ void (async () => {+ if (+ !rtc ||+ command.lease !== activeLease ||+ !attemptId ||+ command.attemptId !== attemptId ||+ !Number.isSafeInteger(command.after) ||+ command.after! < 0 ||+ command.after! > localCandidates.length+ )+ throw new Error('DESKTOP_VIDEO_STOPPED');+ for (const candidate of parseDesktopIceCandidates(command.candidates)) {+ if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');+ const key = JSON.stringify(candidate);+ if (seen.has(key)) continue;+ if (seen.size >= REMOTE_DESKTOP_NETWORK.maxCandidates)+ throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ await rtc.addIceCandidate(candidate);+ seen.add(key);+ }+ if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');+ const candidates = localCandidates.slice(+ command.after,+ command.after! + REMOTE_DESKTOP_NETWORK.batchSize,+ );+ await api.reply(command.id, {+ attemptId,+ candidates,+ next: command.after! + candidates.length,+ complete:+ rtc.iceGatheringState === 'complete' &&+ command.after! + candidates.length === localCandidates.length,+ });+ })()+ .catch(() => api.reply(command.id, { error: 'DESKTOP_VIDEO_STOPPED' }).catch(() => {}))+ .finally(() => {+ if (current === generation) exchanging = false;+ });+ return;+ }+ if (command.op === 'capture-reset') {+ if (command.lease === activeLease) {+ native?.clear();+ recoverCapture?.();+ }+ return;+ }+ stop();+ if (+ command.op !== 'offer' ||+ !command.lease ||+ !command.sdp ||+ (!command.sourceId && !command.nativeCapture)+ )+ return;+ const current = generation;+ const lease = command.lease;+ activeLease = lease;+ attemptId = command.attemptId;+ void (async () => {+ try {+ const capture = () =>+ navigator.mediaDevices.getDisplayMedia({+ audio: command.settings?.audio === true,+ video: {+ frameRate: { ideal: command.settings?.fps ?? 30, max: command.settings?.fps ?? 30 },+ },+ });+ const boundedCapture = async () => {+ if (!command.sourceId) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ let abandoned = false;+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ capture().then((value) => {+ if (abandoned || current !== generation) {+ value.getTracks().forEach((track) => track.stop());+ throw new Error('DESKTOP_VIDEO_STOPPED');+ }+ return value;+ }),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(+ () => {+ abandoned = true;+ reject(new Error('DESKTOP_VIDEO_TIMEOUT'));+ },+ command.nativeCapture ? 2000 : 10000,+ );+ }),+ ]);+ } finally {+ if (timeout) clearTimeout(timeout);+ }+ };+ const nativeStream = async () => {+ const result = await nativeCaptureStream(+ () => api.nativeFrame(lease),+ () => current === generation,+ () => stop(),+ (value) => {+ if (current === generation) latestCursor = value;+ },+ command.cursorOverlay ? (command.settings?.fps ?? 30) : 15,+ );+ if (current !== generation) {+ result.stop();+ throw new Error('DESKTOP_VIDEO_STOPPED');+ }+ native = result;+ return result.stream;+ };+ let captured: MediaStream;+ if (command.cursorOverlay) {+ // Chromium in our runtime exposes no cursor constraint. Use the+ // cursor-free native video while retaining the normal audio track.+ let audioSource: MediaStream | null = null;+ try {+ if (command.settings?.audio && command.sourceId) {+ try {+ audioSource = await boundedCapture();+ } catch (error) {+ if (current !== generation) throw error;+ // Validate the final track set below, including native video.+ }+ }+ captured = await nativeStream();+ if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');+ for (const track of audioSource?.getAudioTracks() ?? []) captured.addTrack(track);+ audioSource?.getVideoTracks().forEach((track) => track.stop());+ } catch (error) {+ audioSource?.getTracks().forEach((track) => track.stop());+ throw error;+ }+ } else+ try {+ captured = await boundedCapture();+ } catch (error) {+ if (!command.nativeCapture || current !== generation) throw error;+ captured = await nativeStream();+ }+ if (current !== generation) {+ captured.getTracks().forEach((track) => track.stop());+ return;+ }+ if (command.settings?.audio && !captured.getAudioTracks().length) {+ captured.getTracks().forEach((track) => track.stop());+ throw new Error('DESKTOP_AUDIO_UNAVAILABLE');+ }+ stream = captured;+ const rtc = new RTCPeerConnection({+ iceServers: REMOTE_DESKTOP_ICE_SERVERS,+ });+ peer = rtc;+ rtc.onicecandidate = ({ candidate }) => {+ if (!command.attemptId || current !== generation || !candidate?.candidate) return;+ if (localCandidates.length >= REMOTE_DESKTOP_NETWORK.maxCandidates) {+ stop();+ return;+ }+ localCandidates.push({+ candidate: candidate.candidate,+ sdpMid: candidate.sdpMid,+ sdpMLineIndex: candidate.sdpMLineIndex,+ ...(candidate.usernameFragment ? { usernameFragment: candidate.usernameFragment } : {}),+ });+ };+ let recovering = false;+ recoverCapture = () => {+ if (!command.nativeCapture || native || recovering || current !== generation) return;+ recovering = true;+ void (async () => {+ const replacement = await nativeStream();+ const sender = rtc.getSenders().find((item) => item.track?.kind === 'video');+ if (!sender || current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');+ await sender.replaceTrack(replacement.getVideoTracks()[0]);+ captured.getVideoTracks().forEach((track) => {+ track.onended = null;+ track.onmute = null;+ track.stop();+ });+ })().catch(() => {+ if (current === generation) stop();+ });+ };+ captured.getVideoTracks().forEach((track) => {+ track.onended = () => recoverCapture?.();+ track.onmute = () => recoverCapture?.();+ });+ rtc.onconnectionstatechange = () => {+ if (current !== generation) return;+ if (['failed', 'closed'].includes(rtc.connectionState)) {+ stop();+ return;+ }+ if (rtc.connectionState === 'disconnected') {+ if (!disconnectedTimer)+ disconnectedTimer = setTimeout(() => {+ if (current === generation && rtc.connectionState === 'disconnected') stop();+ }, REMOTE_DESKTOP_NETWORK.disconnectedMs);+ } else {+ clearTimeout(disconnectedTimer);+ disconnectedTimer = undefined;+ }+ };+ rtc.ondatachannel = ({ channel }) => {+ if (channel.label !== 'input-v1') {+ channel.close();+ return;+ }+ if (command.cursorOverlay) {+ let lastCursor = '';+ cursorTimer = setInterval(() => {+ if (+ latestCursor === undefined ||+ channel.readyState !== 'open' ||+ current !== generation ||+ channel.bufferedAmount > 65536+ )+ return;+ const data = JSON.stringify({ type: 'cursor', cursor: latestCursor });+ if (data !== lastCursor) {+ channel.send(data);+ lastCursor = data;+ }+ }, 50);+ }+ let pending = 0;+ let challenge = '';+ heartbeat = setInterval(() => {+ if (channel.readyState !== 'open' || current !== generation) return;+ challenge = crypto.randomUUID();+ channel.send(JSON.stringify({ type: 'viewPing', challenge }));+ }, 2000);+ channel.onmessage = ({ data }) => {+ if (current !== generation) return;+ if (typeof data === 'string' && challenge && data === challenge) {+ challenge = '';+ void api.viewHeartbeat(lease).catch(() => {});+ return;+ }+ if (typeof data !== 'string' || data.length > 32_768 || pending >= 8) {+ stop();+ void api.stop().catch(() => {});+ return;+ }+ try {+ const message = JSON.parse(data) as { sequence: number; events: DesktopInput[] };+ if (+ !Number.isSafeInteger(message.sequence) ||+ !Array.isArray(message.events) ||+ message.events.length > 64 ||+ !message.events.every(isDesktopInput)+ ) {+ stop();+ void api.stop().catch(() => {});+ return;+ }+ pending++;+ void api+ .input(lease, message.sequence, message.events)+ .catch(() => channel.close())+ .finally(() => {+ pending--;+ });+ } catch {+ stop();+ void api.stop().catch(() => {});+ }+ };+ };+ stream.getTracks().forEach((track) => rtc.addTrack(track, captured));+ await rtc.setRemoteDescription({ type: 'offer', sdp: command.sdp });+ await rtc.setLocalDescription(await rtc.createAnswer());+ for (const sender of rtc.getSenders()) {+ if (sender.track?.kind !== 'video' || !command.settings) continue;+ const parameters = sender.getParameters();+ if (!parameters.encodings?.length) continue;+ for (const encoding of parameters.encodings) {+ encoding.maxFramerate = command.settings.fps;+ if (command.settings.bitrate) encoding.maxBitrate = command.settings.bitrate;+ }+ await sender.setParameters(parameters);+ }+ if (!command.attemptId)+ await new Promise<void>((resolve) => {+ finishGathering = resolve;+ if (rtc.iceGatheringState === 'complete') {+ resolve();+ return;+ }+ gatheringTimer = setTimeout(resolve, REMOTE_DESKTOP_NETWORK.legacyGatherMs);+ rtc.onicegatheringstatechange = () => {+ if (rtc.iceGatheringState === 'complete') {+ clearTimeout(gatheringTimer);+ resolve();+ }+ };+ });+ if (current === generation) await api.reply(command.id, rtc.localDescription?.sdp ?? null);+ } catch (error) {+ if (current === generation) {+ stop();+ const code = error instanceof Error ? error.message : '';+ await api+ .reply(command.id, {+ error:+ code === 'DESKTOP_AUDIO_UNAVAILABLE'+ ? code+ : code === 'DESKTOP_VIDEO_TIMEOUT'+ ? code+ : 'DESKTOP_VIDEO_UNAVAILABLE',+ })+ .catch(() => {});+ }+ }+ })();+ });+ void api.registerHost().catch(() => stop());++ return () => {+ unsubscribe();+ stop();+ };+}diff --git a/apps/desktop/src/shared/remoteDesktop.ts b/apps/desktop/src/shared/remoteDesktop.tsindex 245909f213..3d725ecc8f 100644--- a/apps/desktop/src/shared/remoteDesktop.ts+++ b/apps/desktop/src/shared/remoteDesktop.ts@@ -11,6 +11,7 @@ export const DESKTOP_LOCAL = {STATE: 'remote-desktop:state',ENABLE: 'remote-desktop:enable',STOP: 'remote-desktop:stop',+ CAPTURE_STOP: 'remote-desktop:capture-stop',REGISTER: 'remote-desktop:register-host',COMMAND: 'remote-desktop:host-command',REPLY: 'remote-desktop:host-reply',@@ -61,6 +62,10 @@ export interface RemoteDesktopApi {permissions(): Promise<RemoteDesktopPermissions>;openPermission(permission: DesktopPermission): Promise<void>;dismissPermissionGuide(): Promise<void>;+}+/** Narrow bridge exposed only to the dedicated capture surface. */+export interface DesktopCaptureApi {+ stop(): Promise<void>;registerHost(): Promise<void>;onCommand(listener: (command: DesktopHostCommand) => void): () => void;reply(id: string, result: DesktopHostReply): Promise<void>;diff --git a/apps/desktop/vite.capture.config.ts b/apps/desktop/vite.capture.config.tsnew file mode 100644index 0000000000..32f40c7eb2--- /dev/null+++ b/apps/desktop/vite.capture.config.ts@@ -0,0 +1,14 @@+import { defineConfig } from 'vite';+import path from 'node:path';++// Separate module graph: no App, Markdown, plugins, React providers or chat preload.+export default defineConfig({+ root: path.resolve(__dirname, 'src/capture-renderer'),+ base: './',+ server: { hmr: false },+ build: {+ emptyOutDir: true,+ outDir: path.resolve(__dirname, '.vite/renderer/desktop_capture'),+ rollupOptions: { output: { inlineDynamicImports: true } },+ },+});