Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(remote-desktop): add standalone desktop viewer and shared mobile runtime

MagicLizi3083b5e89b2e
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 4090e89fb7..e0ddd7bfd1 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -1804,6 +1804,7 @@ const config: ForgeConfig = {
config: 'vite.preload.config.ts',
target: 'preload',
},
+ { entry: 'src/preload/remoteDesktopViewerPreload.ts', config: 'vite.preload.config.ts', target: 'preload' },
{
// 右侧栏独立子窗口专用 preload:最小权限 bridge,不加载主 preload 完整桥。
entry: 'src/preload/sidebarWindowPreload.ts',
diff --git a/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs b/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs
new file mode 100644
index 0000000000..d06c77f360
--- /dev/null
+++ b/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs
@@ -0,0 +1,178 @@
+/** Real Chromium + production Desktop viewer, with a loopback synthetic host.
+ * Usage: node apps/desktop/scripts/remote-desktop-viewer-smoke.mjs <Vite origin> <Chrome path>
+ * No account, OS capture, credential, or remote input. Artifacts live in a unique OS temp dir.
+ */
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { chromium } from 'playwright-core';
+
+const origin = new URL(process.argv[2]);
+assert(['localhost', '127.0.0.1'].includes(origin.hostname));
+const artifacts = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-viewer-smoke-'));
+const browser = await chromium.launch({ executablePath: process.argv[3], headless: true });
+try {
+ const context = await browser.newContext({ viewport: { width: 1180, height: 780 } });
+ const host = await context.newPage(),
+ viewer = await context.newPage();
+ await host.goto(origin.origin);
+ await host.setContent('<canvas width="1280" height="720"></canvas>');
+ const errors = [];
+ viewer.on('pageerror', (e) => errors.push(e.message));
+ const requests = [];
+ await viewer.exposeFunction('viewerRequest', async (request) => {
+ requests.push(request.op);
+ switch (request.op) {
+ case 'capabilities':
+ return {
+ version: 1,
+ enabled: true,
+ canControl: true,
+ automaticReconnect: true,
+ videoSettings: true,
+ platform: 'win32',
+ displays: [{ id: 'one', name: 'Test display', width: 1280, height: 720 }],
+ };
+ case 'start':
+ return {
+ lease: 'test-lease',
+ controlling: false,
+ display: { id: 'one', width: 1280, height: 720 },
+ };
+ case 'control':
+ return { controlling: request.enabled };
+ case 'heartbeat':
+ return { controlling: true };
+ case 'frame':
+ return { jpeg: null };
+ case 'stop':
+ return { ok: true };
+ case 'offer':
+ return {
+ sdp: await host.evaluate(async (sdp) => {
+ window.peer?.close();
+ clearInterval(window.paint);
+ const canvas = document.querySelector('canvas'),
+ ctx = canvas.getContext('2d');
+ let tick = 0;
+ window.paint = setInterval(() => {
+ ctx.fillStyle = '#eee';
+ ctx.fillRect(0, 0, 1280, 720);
+ ctx.fillStyle = '#222';
+ ctx.font = '36px sans-serif';
+ ctx.fillText('Local WebRTC test · ' + ++tick, 50, 90);
+ }, 60);
+ const rtc = new RTCPeerConnection({ iceServers: [] });
+ window.peer = rtc;
+ window.inputs = [];
+ const stream = canvas.captureStream(15);
+ stream.getTracks().forEach((track) => rtc.addTrack(track, stream));
+ rtc.ondatachannel = ({ channel }) => {
+ channel.onmessage = ({ data }) => {
+ window.inputs.push(...JSON.parse(data).events);
+ };
+ };
+ await rtc.setRemoteDescription({ type: 'offer', sdp });
+ await rtc.setLocalDescription(await rtc.createAnswer());
+ if (rtc.iceGatheringState !== 'complete')
+ await new Promise((resolve) => {
+ const timer = setTimeout(resolve, 5000);
+ rtc.onicegatheringstatechange = () => {
+ if (rtc.iceGatheringState === 'complete') {
+ clearTimeout(timer);
+ resolve();
+ }
+ };
+ });
+ return rtc.localDescription.sdp;
+ }, request.sdp),
+ };
+ default:
+ return {};
+ }
+ });
+ await viewer.addInitScript(() => {
+ const noop = () => {},
+ off = () => noop;
+ const scope = {
+ target: { deviceId: 'test-host', name: 'Test computer' },
+ generation: 1,
+ active: true,
+ };
+ window.electronAPI = {
+ platform: 'win32',
+ preferredSystemLocale: 'en',
+ logToMain: noop,
+ appearanceSettings: { getSync: () => null, onChanged: off },
+ localThemes: { listSync: () => ({ success: true, themes: [], diagnostics: [] }) },
+ authHasPersistedSessionHintSync: () => true,
+ appShortcuts: { getState: () => ({ overrides: {}, platform: 'win32' }), onChanged: off },
+ theme: { applyVibrancy: noop },
+ getFullscreenState: async () => false,
+ onFullscreenChange: off,
+ windowMinimize: noop,
+ windowMaximize: noop,
+ windowClose: noop,
+ remoteDesktopViewer: {
+ state: async () => scope,
+ onActive: off,
+ onLocale: off,
+ rendererReady: async () => {},
+ presentationReady: async () => {},
+ request: (_generation, request) => window.viewerRequest(request),
+ ice: async () => [],
+ inputFocus: async () => {},
+ close: async () => {},
+ fullscreen: async () => {},
+ clipboard: async () => {},
+ },
+ };
+ });
+ await viewer.goto(new URL('/?remoteDesktopViewer=1', origin.origin).href);
+ await viewer.waitForFunction(
+ () => document.querySelector('video')?.videoWidth > 0,
+ {},
+ { timeout: 25000 },
+ );
+ await viewer.waitForFunction(() => document.querySelector('.remote-viewer-network') !== null);
+ await viewer.locator('#stage').click({ position: { x: 400, y: 300 } });
+ await viewer.keyboard.type('desktop');
+ await host.waitForFunction(() =>
+ window.inputs.some((event) => event.kind === 'text' && event.text.includes('d')),
+ );
+ await viewer.screenshot({ path: path.join(artifacts, 'light.png') });
+ await viewer.evaluate(async () => {
+ const { themeService } = await import('/themes/theme-service.ts');
+ const { cindyDark } = await import('/themes/builtin/cindy-dark.ts');
+ themeService.applyTheme(cindyDark);
+ });
+ await viewer.screenshot({ path: path.join(artifacts, 'dark.png') });
+ await host.evaluate(() => window.peer.close());
+ await viewer.waitForFunction(
+ () => document.querySelector('.remote-viewer-network')?.textContent.includes('Compatibility'),
+ {},
+ { timeout: 12000 },
+ );
+ await viewer.waitForFunction(
+ () => document.querySelector('.remote-viewer-network')?.textContent.includes('Direct'),
+ {},
+ { timeout: 25000 },
+ );
+ assert.equal(
+ requests.filter((op) => op === 'start').length,
+ 1,
+ 'media recovery must retain its lease',
+ );
+ assert.deepEqual(errors, []);
+ console.log(
+ JSON.stringify({
+ video: true,
+ keyboard: true,
+ mediaRecovery: true,
+ lightDarkArtifacts: artifacts,
+ }),
+ );
+} finally {
+ await browser.close();
+}
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 1bb20105f1..08ce5985b4 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -633,6 +633,7 @@ import { RsbWindowController } from './right-sidebar-window/controller.js';
import { resolveRsbHostContextFromSession } from './right-sidebar-window/resolveHostContext.js';
import { createRightSidebarWindow } from './right-sidebar-window/window.js';
import { registerRsbWindowIpc } from './right-sidebar-window/ipc.js';
+import { RemoteDesktopViewerWindows } from './remote-desktop-viewer/windows.js';
import { ResourceUsageWindowController } from './resource-usage-window/controller.js';
import { createResourceUsageWindow } from './resource-usage-window/window.js';
import { registerResourceUsageWindowIpc } from './resource-usage-window/ipc.js';
@@ -1575,6 +1576,7 @@ function clearAccountBoundaryAbortMark(): void {
}
async function teardownAuthAccountBoundary(reason: string): Promise<void> {
+ remoteDesktopViewerWindows.reset();
const blockingFailures: unknown[] = [];
// Goal timers can dispatch through the outgoing Maker while launch-fence
// acquisition waits behind queued filesystem work. Invalidate them before
@@ -2344,6 +2346,10 @@ const resourceUsageWindowController = new ResourceUsageWindowController({
},
});
registerResourceUsageWindowIpc({ controller: resourceUsageWindowController });
+const remoteDesktopViewerWindows = new RemoteDesktopViewerWindows(sender =>
+ isResourceUsageOpenSender({ sender, mainWindow: mainWindowRef, senderWindow: BrowserWindow.fromWebContents(sender), isSecondaryAppWindow }),
+);
+remoteDesktopViewerWindows.register();
setGhostsChangedObserver((ghosts) => {
ghostPanelWindowsController.reconcile(ghosts);
@@ -2437,6 +2443,7 @@ registerGhostIpc();
registerPluginMarketIpc();
registerPluginPublisherIpc();
setAppSessionCommitBoundaryHook(() => {
+ remoteDesktopViewerWindows.reset();
ghostPanelWindowsController.closeForOwnerChange();
clearAllSessionProviders();
clearAllSessionRuntimeAxes();
@@ -2961,6 +2968,7 @@ ipcMain.handle('app-menu:set-locale', (_event, locale: unknown): { ok: true } =>
setSelectionContextMenuLocale(currentApplicationMenuLocale);
setMainLocale(currentApplicationMenuLocale);
resourceUsageWindowController.setLocale(currentApplicationMenuLocale);
+ remoteDesktopViewerWindows.setLocale(currentApplicationMenuLocale);
rsbWindowController.setLocale(currentApplicationMenuLocale);
ghostPanelWindowsController.setLocale(currentApplicationMenuLocale);
refreshGhostLocalization();
@@ -3767,6 +3775,7 @@ const createWindow = () => {
resourceUsagePrewarmTimer = null;
}
resourceUsageWindowController.destroyWindow();
+ remoteDesktopViewerWindows.reset();
rsbWindowController.destroyWindow();
ghostPanelWindowsController.destroyAllWindows();
if (mainWindowRef === mainWindow) mainWindowRef = null;
@@ -3885,6 +3894,8 @@ const createWindow = () => {
currentApplicationMenuLocale ?? getPreferredApplicationLocale(),
);
resourceUsageWindowController.prewarm();
+ remoteDesktopViewerWindows.setLocale(currentApplicationMenuLocale ?? getPreferredApplicationLocale());
+ remoteDesktopViewerWindows.prewarm();
// 右侧栏子窗口预热:复刻资源用量窗口模式,主窗口可见后后台创建
// 隐藏 BrowserWindow 并加载轻量 renderer,后续 detach 点击仅 show+focus。
rsbWindowController.prewarm();
@@ -9814,3 +9825,5 @@ function startReadyWorktreeMaintenance(): void {
void WorktreePool.recoverPool().catch((error) => dbClientLog.warn('worktree pool recovery postponed', error));
}
}
+
+onQuit('remote-desktop-viewer', () => remoteDesktopViewerWindows.reset(), 'sync');
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index aaee48f884..a8dd5d292e 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -1679,7 +1679,9 @@ export async function remoteInvoke(
deviceId: string,
channel: string,
args: unknown[],
+ options?: { preSend?: () => void },
): Promise<InvokeResultPayload> {
+ options?.preSend?.();
assertNotStandby();
assertRemoteControlTargetEnabled(deviceId);
// 取消代次快照(不变量 3 的对称路径,review P1):等待上线期间用户 CLOSE_LINK
@@ -1699,6 +1701,7 @@ export async function remoteInvoke(
// 授权),或显式 CLOSE_LINK(复验取消代次)(review P1 ×2)。
assertRemoteControlTargetEnabled(deviceId);
assertLinkNotClosedSinceStart();
+ options?.preSend?.();
if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
return client.invoke(deviceId, { channel, args }, INVOKE_TIMEOUT_OVERRIDES_MS[channel]);
};
diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.ts
index 095f9a121b..75c24b6b3a 100644
--- a/apps/desktop/src/main/lifecycle.ts
+++ b/apps/desktop/src/main/lifecycle.ts
@@ -50,6 +50,7 @@ import { noteQuitDisposersCompleted, noteShutdownBegin } from './startup-diagnos
import { isGhostSandboxWebContentsId } from './cindy-brain/runtime/electronSandboxAdapter';
import { isRsbNativePopupWebContentsId } from './rsb-browser-bridge/native-popup-surfaces';
import { isResourceUsageWebContentsId } from './resource-usage-window/registry.js';
+import { isRemoteDesktopViewer } from './remote-desktop-viewer/registry.js';
import { isRsbWindowWebContentsId } from './right-sidebar-window/registry.js';
import { isGhostPanelWebContentsId } from './ghost-panel-window/registry.js';
import { isReviewArtifactConfirmWebContentsId } from './reviewer/reviewArtifactConfirmWindowRegistry.js';
@@ -658,7 +659,7 @@ export function installQuitHandler(timeoutMs = 2000): void {
);
return;
}
- if (isResourceUsageWebContentsId(webContents.id)) {
+ if (isResourceUsageWebContentsId(webContents.id) || isRemoteDesktopViewer(webContents.id)) {
log.warn(
`resource usage render-process-gone (isolated, no shutdown): reason=${details.reason} exitCode=${details.exitCode}`,
);
diff --git a/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts b/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts
new file mode 100644
index 0000000000..6a15dd8c40
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts
@@ -0,0 +1,187 @@
+import { describe, it, expect, vi } from 'vitest';
+import { RemoteViewerConnection } from '../connection';
+import type { RemoteDesktopRequest } from '@cindy/device-link';
+
+function fixture() {
+ let owner = 'account-a:1';
+ const request = vi.fn(
+ async (_target: string, request: RemoteDesktopRequest, check: () => void): Promise<unknown> => {
+ check();
+ return request.op === 'start'
+ ? { lease: 'lease-a', controlling: false, display: { id: 'screen' } }
+ : { ok: true };
+ },
+ );
+ const readClipboard = vi.fn(() => 'local text'),
+ writeClipboard = vi.fn();
+ const connection = new RemoteViewerConnection({
+ owner: () => owner,
+ request,
+ readClipboard,
+ writeClipboard,
+ });
+ connection.bind({ deviceId: 'computer-a', name: 'Computer' });
+ connection.setActive(true);
+ return {
+ connection,
+ request,
+ readClipboard,
+ writeClipboard,
+ owner: (value: string) => {
+ owner = value;
+ },
+ };
+}
+describe('standalone remote viewer authority', () => {
+ it('view-only cannot read or write the local clipboard even when the renderer asks', async () => {
+ const f = fixture();
+ await f.connection.request(f.connection.generation, { op: 'start', displayId: 'screen' });
+ for (const action of ['copy', 'paste'])
+ expect(await f.connection.clipboard(f.connection.generation, action)).toEqual({
+ ok: false,
+ code: 'DESKTOP_VIEW_ONLY',
+ });
+ expect(f.readClipboard).not.toHaveBeenCalled();
+ expect(f.writeClipboard).not.toHaveBeenCalled();
+ expect(f.request).toHaveBeenCalledTimes(1);
+ });
+ it('a control release discards a pending copy and a stale heartbeat cannot restore clipboard access', async () => {
+ const f = fixture(),
+ generation = f.connection.generation;
+ await f.connection.request(generation, { op: 'start', displayId: 'screen' });
+ f.request.mockResolvedValueOnce({ controlling: true });
+ await f.connection.request(generation, { op: 'control', lease: 'lease-a', enabled: true });
+ let copied!: (value: unknown) => void, heartbeat!: (value: unknown) => void;
+ f.request.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ copied = resolve;
+ }),
+ );
+ const copy = f.connection.clipboard(generation, 'copy');
+ f.request.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ heartbeat = resolve;
+ }),
+ );
+ const renewal = f.connection.request(generation, { op: 'heartbeat', lease: 'lease-a' });
+ f.request.mockResolvedValueOnce({ controlling: false });
+ await f.connection.request(generation, { op: 'control', lease: 'lease-a', enabled: false });
+ heartbeat({ controlling: true });
+ await renewal;
+ copied({ text: 'stale remote text' });
+ expect(await copy).toEqual({ ok: false, code: 'DESKTOP_VIEW_ONLY' });
+ expect(f.writeClipboard).not.toHaveBeenCalled();
+ expect(await f.connection.clipboard(generation, 'paste')).toEqual({
+ ok: false,
+ code: 'DESKTOP_VIEW_ONLY',
+ });
+ expect(f.readClipboard).not.toHaveBeenCalled();
+ });
+ it('invalidates queued signaling after a newer media attempt without closing the lease', async () => {
+ const f = fixture();
+ await f.connection.request(f.connection.generation, { op: 'start', displayId: 'screen' });
+ const generation = f.connection.generation;
+ f.connection.beginMedia(generation, '1');
+ let beforeSend!: () => void;
+ f.request.mockImplementationOnce(async (_peer, _body, check) => {
+ beforeSend = check;
+ return { sdp: 'answer' };
+ });
+ await f.connection.request(generation, { op: 'offer', lease: 'lease-a', sdp: 'offer' }, '1');
+ f.connection.beginMedia(generation, '2');
+ expect(() => beforeSend()).toThrow('DESKTOP_VIDEO_STOPPED');
+ expect(f.connection.snapshot().active).toBe(true);
+ const count = f.request.mock.calls.length;
+ expect(
+ await f.connection.request(generation, { op: 'offer', lease: 'lease-a', sdp: 'old' }, '1'),
+ ).toEqual({ ok: false, code: 'DESKTOP_VIDEO_STOPPED' });
+ expect(f.request).toHaveBeenCalledTimes(count);
+ });
+ it('releases only its lease while another desktop link remains usable', async () => {
+ const { connection, request } = fixture();
+ await connection.request(connection.generation, { op: 'start', displayId: 'screen' });
+ connection.setActive(false);
+ expect(request.mock.calls.at(-1)?.slice(0, 2)).toEqual([
+ 'computer-a',
+ { op: 'stop', lease: 'lease-a' },
+ ]);
+ expect(
+ (
+ await connection.request(connection.generation, {
+ op: 'input',
+ lease: 'lease-a',
+ sequence: 1,
+ events: [{ kind: 'release' }],
+ })
+ ).ok,
+ ).toBe(false);
+ expect(connection.snapshot().resume).toBe(true);
+ });
+ it('retires a late successful start after the viewer closes', async () => {
+ const { connection, request } = fixture();
+ let finish!: (result: unknown) => void;
+ request.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const pending = connection.request(connection.generation, { op: 'start', displayId: 'screen' });
+ connection.setActive(false);
+ finish({ lease: 'late-lease' });
+ expect(await pending).toEqual({ ok: false, code: 'DESKTOP_STOPPED' });
+ expect(request.mock.calls.at(-1)?.[1]).toEqual({ op: 'stop', lease: 'late-lease' });
+ });
+ it('cannot send a stale queued input or cleanup through a new account', async () => {
+ const f = fixture();
+ await f.connection.request(f.connection.generation, { op: 'start', displayId: 'screen' });
+ const generation = f.connection.generation;
+ let check!: () => void;
+ f.request.mockImplementationOnce(async (_peer, _body, preSend) => {
+ check = preSend;
+ return null;
+ });
+ await f.connection.request(generation, { op: 'frame', lease: 'lease-a' });
+ f.owner('account-b:2');
+ expect(() => check()).toThrow('DESKTOP_STOPPED');
+ const count = f.request.mock.calls.length;
+ f.connection.deactivate();
+ expect(f.request).toHaveBeenCalledTimes(count);
+ });
+ it('rejects other leases, password operations and arbitrary clipboard access', async () => {
+ const { connection, request } = fixture();
+ for (const message of [
+ { op: 'input', lease: 'someone-else', sequence: 1, events: [] },
+ { op: 'credential', version: 1, kind: 'prepare' },
+ { op: 'clipboard', lease: 'someone-else', action: 'copy' },
+ ])
+ expect((await connection.request(connection.generation, message)).ok).toBe(false);
+ expect(request).not.toHaveBeenCalled();
+ });
+ it('keeps native clipboard text out of the renderer and never replays uncertain pastes', async () => {
+ const f = fixture();
+ await f.connection.request(f.connection.generation, { op: 'start', displayId: 'screen' });
+ f.request.mockResolvedValueOnce({ controlling: true });
+ await f.connection.request(f.connection.generation, {
+ op: 'control',
+ lease: 'lease-a',
+ enabled: true,
+ });
+ f.request.mockResolvedValueOnce({ text: 'remote text' });
+ expect(await f.connection.clipboard(f.connection.generation, 'copy')).toEqual({
+ ok: true,
+ result: null,
+ });
+ expect(f.writeClipboard).toHaveBeenCalledWith('remote text');
+ f.request.mockRejectedValueOnce(new Error('INVOKE_TIMEOUT'));
+ expect(await f.connection.clipboard(f.connection.generation, 'paste')).toEqual({
+ ok: false,
+ code: 'INVOKE_TIMEOUT',
+ });
+ expect(
+ f.request.mock.calls.filter(([, r]) => r.op === 'clipboard' && r.action === 'paste'),
+ ).toHaveLength(1);
+ });
+});
diff --git a/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.ts b/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.ts
new file mode 100644
index 0000000000..62d2b99d41
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.ts
@@ -0,0 +1,146 @@
+import { EventEmitter } from 'node:events';
+import { afterEach, expect, it, vi } from 'vitest';
+const fixture = vi.hoisted(() => ({
+ windows: [] as any[],
+ handlers: new Map<string, Function>(),
+ calls: [] as any[],
+ owner: 'a:1',
+}));
+vi.mock('electron', () => ({
+ BrowserWindow: { fromWebContents: () => null },
+ clipboard: { readText: () => '', writeText: vi.fn() },
+ ipcMain: { handle: (name: string, fn: Function) => fixture.handlers.set(name, fn) },
+}));
+vi.mock('../../logger', () => ({
+ createLogger: () => ({ warn: vi.fn(), error: vi.fn(), info: vi.fn() }),
+}));
+vi.mock('../../appSessionState', () => ({
+ activeOwnerScopeKey: () => fixture.owner,
+ isAppSessionBoundaryPending: () => false,
+}));
+vi.mock('../../appCapabilities', () => ({
+ getAppCapabilities: () => ({ canUseDeviceLink: true }),
+}));
+vi.mock('../../i18n', () => ({ t: (s: string) => s }));
+vi.mock('../../device-link/index', () => ({
+ getSelfDeviceId: () => 'local',
+ remoteInvoke: vi.fn(async (...args: any[]) => {
+ args[3]?.preSend?.();
+ fixture.calls.push(args);
+ return { ok: true, result: { lease: 'lease-' + args[0] } };
+ }),
+}));
+vi.mock('../../remote-desktop/iceConfig', () => ({ loadDesktopIceServers: async () => [] }));
+vi.mock('../../security/trustedAppRenderer', () => ({
+ assertTrustedAppRendererEvent: () => {},
+ isTrustedTopLevelCindyRendererEvent: (event: any) => event.senderFrame === event.sender.mainFrame,
+ isTrustedCindyRendererWindow: () => true,
+}));
+vi.mock('../../utils/ipcValidate', () => ({
+ throwIpcError: (_code: string, message: string) => {
+ throw new Error(message);
+ },
+}));
+vi.mock('../../resource-usage-window/window', () => ({
+ createResourceUsageWindow: () => {
+ const window: any = new EventEmitter();
+ const contents: any = new EventEmitter();
+ let visible = false,
+ destroyed = false;
+ Object.assign(contents, {
+ id: fixture.windows.length + 1,
+ mainFrame: {},
+ isDestroyed: () => destroyed,
+ send: vi.fn(),
+ setIgnoreMenuShortcuts: vi.fn(),
+ });
+ Object.assign(window, {
+ webContents: contents,
+ isDestroyed: () => destroyed,
+ isVisible: () => visible,
+ isMinimized: () => false,
+ isFullScreen: () => false,
+ setTitle: vi.fn(),
+ setFullScreen: vi.fn(),
+ restore: vi.fn(),
+ focus: vi.fn(),
+ isFocused: () => visible,
+ show: () => {
+ visible = true;
+ window.emit('show');
+ },
+ hide: () => {
+ visible = false;
+ window.emit('hide');
+ },
+ destroy: () => {
+ destroyed = true;
+ window.emit('closed');
+ },
+ });
+ fixture.windows.push(window);
+ return window;
+ },
+}));
+import { RemoteDesktopViewerWindows } from '../windows';
+import { REMOTE_VIEWER } from '../../../shared/remoteDesktopViewer';
+let manager: RemoteDesktopViewerWindows;
+afterEach(() => {
+ manager?.reset();
+ fixture.windows = [];
+ fixture.calls = [];
+ fixture.handlers.clear();
+ fixture.owner = 'a:1';
+});
+const event = (win: any) => ({ sender: win.webContents, senderFrame: win.webContents.mainFrame });
+const call = (channel: string, win: any, ...args: unknown[]) =>
+ fixture.handlers.get(channel)!(event(win), ...args);
+it('prewarms without network or focus, reuses the target window and cleans only its lease', async () => {
+ const sender: any = { id: 100 };
+ manager = new RemoteDesktopViewerWindows((value) => value === sender);
+ manager.register();
+ manager.prewarm();
+ const a = fixture.windows[0];
+ call(REMOTE_VIEWER.READY, a);
+ call(REMOTE_VIEWER.PRESENTED, a);
+ expect(fixture.calls).toHaveLength(0);
+ expect(a.focus).not.toHaveBeenCalled();
+ expect(a.isVisible()).toBe(false);
+ manager.open(sender, { deviceId: 'a', name: 'A' });
+ const size = fixture.windows.length;
+ manager.open(sender, { deviceId: 'a', name: 'A' });
+ expect(fixture.windows).toHaveLength(size);
+ const aState = call(REMOTE_VIEWER.STATE, a);
+ await call(REMOTE_VIEWER.REQUEST, a, aState.generation, { op: 'start', displayId: 'screen' });
+ manager.open(sender, { deviceId: 'b', name: 'B' });
+ const b = fixture.windows[1];
+ call(REMOTE_VIEWER.READY, b);
+ call(REMOTE_VIEWER.PRESENTED, b);
+ const bState = call(REMOTE_VIEWER.STATE, b);
+ await call(REMOTE_VIEWER.REQUEST, b, bState.generation, { op: 'start', displayId: 'screen' });
+ call(REMOTE_VIEWER.CLOSE, a);
+ await Promise.resolve();
+ expect(call(REMOTE_VIEWER.STATE, b).active).toBe(true);
+ expect(fixture.calls.filter((c) => c[2][0].op === 'stop').map((c) => c[0])).toEqual(['a']);
+ expect(a.isDestroyed()).toBe(false);
+});
+it('rejects subframes and stale window/account generations even with a valid channel', async () => {
+ const sender: any = { id: 100 };
+ manager = new RemoteDesktopViewerWindows((value) => value === sender);
+ manager.register();
+ manager.open(sender, { deviceId: 'a', name: 'A' });
+ const a = fixture.windows[0];
+ call(REMOTE_VIEWER.READY, a);
+ call(REMOTE_VIEWER.PRESENTED, a);
+ await expect(
+ fixture.handlers.get(REMOTE_VIEWER.REQUEST)!({ sender: a.webContents, senderFrame: {} }, 1, {
+ op: 'capabilities',
+ }),
+ ).rejects.toThrow('Invalid viewer');
+ const state = call(REMOTE_VIEWER.STATE, a);
+ fixture.owner = 'b:2';
+ await expect(
+ call(REMOTE_VIEWER.REQUEST, a, state.generation, { op: 'capabilities' }),
+ ).rejects.toThrow('DESKTOP_STOPPED');
+ expect(fixture.calls).toHaveLength(0);
+});
diff --git a/apps/desktop/src/main/remote-desktop-viewer/connection.ts b/apps/desktop/src/main/remote-desktop-viewer/connection.ts
new file mode 100644
index 0000000000..71edaf7906
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop-viewer/connection.ts
@@ -0,0 +1,244 @@
+import {
+ parseRemoteDesktopRequest,
+ isDesktopAttemptId,
+ REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS,
+ type RemoteDesktopRequest,
+ type RemoteDesktopLease,
+} from '@cindy/device-link';
+import type {
+ RemoteViewerReply,
+ RemoteViewerTarget,
+ RemoteViewerState,
+} from '../../shared/remoteDesktopViewer.js';
+
+/** Main owns the target, account generation and lease for one lightweight viewer.
+ * A destroyed/hidden window cannot leave late starts or inputs alive. No closeLink.
+ */
+export class RemoteViewerConnection {
+ target: RemoteViewerTarget | null = null;
+ active = false;
+ generation = 0;
+ private owner = '';
+ private lease: string | null = null;
+ private starting = false;
+ private pending = 0;
+ private attempted = false;
+ private mediaAttempt: string | null = null;
+ private controlling = false;
+ private wantsControl = false;
+ private controlGeneration = 0;
+ private controlPending = false;
+ private clipboardPending: object | null = null;
+ constructor(
+ private readonly deps: {
+ owner(): string;
+ request(deviceId: string, request: RemoteDesktopRequest, check: () => void): Promise<unknown>;
+ readClipboard(): string;
+ writeClipboard(value: string): void;
+ },
+ ) {}
+ bind(target: RemoteViewerTarget): void {
+ this.deactivate();
+ this.owner = this.deps.owner();
+ this.target = target;
+ this.attempted = false;
+ }
+ snapshot(): RemoteViewerState {
+ return {
+ target: this.target,
+ active: this.active,
+ generation: this.generation,
+ resume: this.attempted,
+ };
+ }
+ setActive(active: boolean): void {
+ if (this.owner !== this.deps.owner()) {
+ this.deactivate();
+ this.target = null;
+ return;
+ }
+ if (!active) {
+ if (this.active) this.deactivate();
+ return;
+ }
+ this.active = Boolean(this.target);
+ }
+ check(generation: number): void {
+ if (
+ !this.active ||
+ !this.target ||
+ generation !== this.generation ||
+ this.owner !== this.deps.owner()
+ )
+ throw new Error('DESKTOP_STOPPED');
+ }
+ beginMedia(generation: number, attempt: unknown): void {
+ this.check(generation);
+ if (!this.lease || !isDesktopAttemptId(attempt)) throw new Error('DESKTOP_VIDEO_STOPPED');
+ this.mediaAttempt = attempt;
+ }
+ checkMedia(generation: number, attempt: unknown): void {
+ this.check(generation);
+ if (!this.mediaAttempt || attempt !== this.mediaAttempt)
+ throw new Error('DESKTOP_VIDEO_STOPPED');
+ }
+ deactivate(): void {
+ this.generation++;
+ this.active = false;
+ const lease = this.lease,
+ target = this.target,
+ owner = this.owner;
+ this.lease = null;
+ this.mediaAttempt = null;
+ this.controlling = false;
+ this.wantsControl = false;
+ this.controlPending = false;
+ this.controlGeneration++;
+ this.clipboardPending = null;
+ this.starting = false;
+ if (lease && target && owner === this.deps.owner())
+ void this.deps
+ .request(target.deviceId, { op: 'stop', lease }, () => {
+ if (owner !== this.deps.owner()) throw new Error('DESKTOP_STOPPED');
+ })
+ .catch(() => {});
+ }
+ async request(
+ generation: number,
+ value: unknown,
+ mediaAttempt?: string,
+ ): Promise<RemoteViewerReply> {
+ try {
+ this.check(generation);
+ const request = parseRemoteDesktopRequest(value);
+ const check = () =>
+ request.op === 'offer' || request.op === 'ice'
+ ? this.checkMedia(generation, mediaAttempt)
+ : this.check(generation);
+ check();
+ if ('lease' in request && request.lease !== this.lease)
+ throw new Error('DESKTOP_LEASE_EXPIRED');
+ if (request.op === 'start' && this.starting) throw new Error('DESKTOP_BUSY');
+ // The renderer has no generic local clipboard API, password bridge, or lock-on-exit policy.
+ if (
+ request.op === 'clipboard' ||
+ request.op === 'clipboardContent' ||
+ request.op === 'presentation' ||
+ (request.op === 'stop' && request.lockScreen)
+ )
+ throw new Error('DESKTOP_UNAVAILABLE');
+ if (this.pending >= 12) throw new Error('DESKTOP_INPUT_BUSY');
+ const target = this.target!,
+ owner = this.owner;
+ const isStart = request.op === 'start';
+ const isControl = request.op === 'control';
+ if (isControl || request.op === 'stop' || isStart) {
+ this.controlGeneration++;
+ this.wantsControl = isControl && request.enabled;
+ this.controlling = false;
+ if (!isControl) this.controlPending = false;
+ }
+ const controlGeneration = this.controlGeneration;
+ const controlPendingAtStart = this.controlPending;
+ if (isControl) this.controlPending = true;
+ if (isStart) {
+ this.starting = true;
+ this.attempted = true;
+ }
+ this.pending++;
+ try {
+ const result = await this.deps.request(target.deviceId, request, check);
+ if (isStart) {
+ const lease = result as RemoteDesktopLease;
+ if (!lease || typeof lease.lease !== 'string') throw new Error('DESKTOP_UNAVAILABLE');
+ if (!this.active || generation !== this.generation || owner !== this.deps.owner()) {
+ if (owner === this.deps.owner())
+ void this.deps
+ .request(target.deviceId, { op: 'stop', lease: lease.lease }, () => {
+ if (owner !== this.deps.owner()) throw new Error('DESKTOP_STOPPED');
+ })
+ .catch(() => {});
+ throw new Error('DESKTOP_STOPPED');
+ }
+ this.lease = lease.lease;
+ }
+ this.check(generation);
+ if (
+ controlGeneration === this.controlGeneration &&
+ (isControl ||
+ (request.op === 'heartbeat' && !controlPendingAtStart && !this.controlPending))
+ ) {
+ this.controlling =
+ this.wantsControl &&
+ !!result &&
+ typeof result === 'object' &&
+ 'controlling' in result &&
+ result.controlling === true;
+ }
+ if (request.op === 'stop' && this.lease === request.lease) this.lease = null;
+ return { ok: true, result };
+ } finally {
+ this.pending--;
+ if (isControl && controlGeneration === this.controlGeneration) this.controlPending = false;
+ if (generation === this.generation && isStart) this.starting = false;
+ }
+ } catch (error) {
+ return viewerFailure(error);
+ }
+ }
+ async clipboard(generation: number, action: unknown): Promise<RemoteViewerReply> {
+ const transfer = {};
+ try {
+ this.check(generation);
+ const lease = this.lease;
+ if (!lease) throw new Error('DESKTOP_LEASE_EXPIRED');
+ if (!this.controlling) throw new Error('DESKTOP_VIEW_ONLY');
+ if (this.clipboardPending) throw new Error('DESKTOP_CLIPBOARD_BUSY');
+ this.clipboardPending = transfer;
+ const controlGeneration = this.controlGeneration;
+ const check = () => {
+ this.check(generation);
+ if (this.lease !== lease) throw new Error('DESKTOP_LEASE_EXPIRED');
+ if (!this.controlling || controlGeneration !== this.controlGeneration)
+ throw new Error('DESKTOP_VIEW_ONLY');
+ };
+ if (action === 'copy') {
+ const result = (await this.deps.request(
+ this.target!.deviceId,
+ { op: 'clipboard', lease, action: 'copy' },
+ check,
+ )) as { text?: unknown };
+ check();
+ if (
+ typeof result.text !== 'string' ||
+ !result.text ||
+ result.text.length > REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS
+ )
+ throw new Error('CLIPBOARD_TOO_LONG');
+ this.deps.writeClipboard(result.text);
+ } else if (action === 'paste') {
+ const text = this.deps.readClipboard();
+ if (!text || text.length > REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS)
+ throw new Error('CLIPBOARD_TOO_LONG');
+ await this.deps.request(
+ this.target!.deviceId,
+ { op: 'clipboard', lease, action: 'paste', text },
+ check,
+ );
+ check();
+ } else throw new Error('INVALID_REQUEST');
+ return { ok: true, result: null };
+ } catch (error) {
+ return viewerFailure(error);
+ } finally {
+ if (this.clipboardPending === transfer) this.clipboardPending = null;
+ }
+ }
+}
+
+/** Only stable codes cross the dedicated bridge; never raw IPC/OS error text. */
+export function viewerFailure(error: unknown): RemoteViewerReply {
+ const value = error instanceof Error ? error.message : '';
+ const code = /^[A-Z][A-Z0-9_]{1,80}$/.test(value) ? value : 'DESKTOP_UNAVAILABLE';
+ return { ok: false, code };
+}
diff --git a/apps/desktop/src/main/remote-desktop-viewer/registry.ts b/apps/desktop/src/main/remote-desktop-viewer/registry.ts
new file mode 100644
index 0000000000..3e10d94dd2
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop-viewer/registry.ts
@@ -0,0 +1,6 @@
+/** Crash isolation registration survives destroyed/gone event ordering. */
+const ids = new Set<number>();
+export const markRemoteDesktopViewer = (id: number): void => {
+ ids.add(id);
+};
+export const isRemoteDesktopViewer = (id: number): boolean => ids.has(id);
diff --git a/apps/desktop/src/main/remote-desktop-viewer/windows.ts b/apps/desktop/src/main/remote-desktop-viewer/windows.ts
new file mode 100644
index 0000000000..83b361fb85
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop-viewer/windows.ts
@@ -0,0 +1,228 @@
+import {
+ BrowserWindow,
+ clipboard,
+ ipcMain,
+ type IpcMainInvokeEvent,
+ type WebContents,
+} from 'electron';
+import { REMOTE_DESKTOP_CHANNEL, DeviceLinkError } from '@cindy/device-link';
+import { REMOTE_VIEWER, type RemoteViewerTarget } from '../../shared/remoteDesktopViewer.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { getAppCapabilities } from '../appCapabilities.js';
+import { getSelfDeviceId, remoteInvoke } from '../device-link/index.js';
+import { loadDesktopIceServers } from '../remote-desktop/iceConfig.js';
+import {
+ assertTrustedAppRendererEvent,
+ isTrustedTopLevelCindyRendererEvent,
+ isTrustedCindyRendererWindow,
+} from '../security/trustedAppRenderer.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { ResourceUsageWindowController } from '../resource-usage-window/controller.js';
+import { createResourceUsageWindow } from '../resource-usage-window/window.js';
+import type { SupportedLocale } from '../../shared/locale.js';
+import { t } from '../i18n.js';
+import { markRemoteDesktopViewer } from './registry.js';
+import { extractIpcError } from '../../shared/ipcError.js';
+import { RemoteViewerConnection } from './connection.js';
+
+type Entry = {
+ window: BrowserWindow | null;
+ controller: ResourceUsageWindowController;
+ connection: RemoteViewerConnection;
+};
+
+/** Reuses the existing auxiliary-window lifecycle. One window per target plus
+ * one unbound prewarmed shell; no capture, link or input during prewarming.
+ */
+export class RemoteDesktopViewerWindows {
+ private entries = new Set<Entry>();
+ private locale: SupportedLocale | null = null;
+ constructor(private readonly isOpenSender: (sender: WebContents) => boolean) {}
+ prewarm(): void {
+ if (![...this.entries].some((e) => e.connection.target === null))
+ this.create().controller.prewarm();
+ }
+ open(sender: WebContents, target: RemoteViewerTarget): void {
+ if (
+ !this.isOpenSender(sender) ||
+ !getAppCapabilities().canUseDeviceLink ||
+ isAppSessionBoundaryPending()
+ )
+ throwIpcError('PERMISSION_DENIED', 'Remote desktop unavailable');
+ if (
+ !target ||
+ typeof target.deviceId !== 'string' ||
+ !target.deviceId.trim() ||
+ target.deviceId.length > 256 ||
+ target.deviceId === getSelfDeviceId() ||
+ typeof target.name !== 'string' ||
+ target.name.length > 256
+ )
+ throwIpcError('INVALID_PARAMS', 'Invalid remote desktop target');
+ let entry = [...this.entries].find((e) => e.connection.target?.deviceId === target.deviceId);
+ if (!entry) entry = [...this.entries].find((e) => !e.connection.target) ?? this.create();
+ if (!entry.connection.active)
+ entry.connection.bind({ deviceId: target.deviceId, name: target.name });
+ entry.controller.open(sender);
+ // The spare shell is created off the next click path, never connects to a peer.
+ this.prewarm();
+ }
+ setLocale(locale: SupportedLocale): void {
+ this.locale = locale;
+ for (const e of this.entries) e.controller.setLocale(locale);
+ }
+ reset(): void {
+ for (const e of this.entries) {
+ e.connection.deactivate();
+ e.controller.dispose();
+ }
+ this.entries.clear();
+ }
+ private create(): Entry {
+ const connection = new RemoteViewerConnection({
+ owner: activeOwnerScopeKey,
+ readClipboard: () => clipboard.readText(),
+ writeClipboard: (value) => clipboard.writeText(value),
+ request: async (device, request, check) => {
+ check();
+ if (!getAppCapabilities().canUseDeviceLink || isAppSessionBoundaryPending())
+ throw new Error('DESKTOP_STOPPED');
+ try {
+ const result = await remoteInvoke(device, REMOTE_DESKTOP_CHANNEL, [request], {
+ preSend: () => {
+ check();
+ if (!getAppCapabilities().canUseDeviceLink || isAppSessionBoundaryPending())
+ throw new Error('DESKTOP_STOPPED');
+ },
+ });
+ if (!result.ok)
+ throw new Error(
+ result.error.code === 'IPC_ERROR' ? result.error.message : result.error.code,
+ );
+ return result.result;
+ } catch (error) {
+ if (error instanceof DeviceLinkError) throw new Error(error.code);
+ const parsed = extractIpcError(error);
+ if (parsed?.code === 'DEVICE_LINK_CONTROL_DISABLED') throw new Error('REMOTE_DISABLED');
+ if (parsed)
+ throw new Error(
+ /^(DESKTOP|CLIPBOARD)_[A-Z_]+$/.test(parsed.message) ? parsed.message : parsed.code,
+ );
+ throw error;
+ }
+ },
+ });
+ const entry: Entry = { window: null, connection, controller: null! };
+ entry.controller = new ResourceUsageWindowController({
+ isOpenSender: this.isOpenSender,
+ // Independent top-level windows do not follow main-window minimize/hide.
+ prewarmWork: false,
+ activityChannel: REMOTE_VIEWER.ACTIVE,
+ activityPayload: () => connection.snapshot(),
+ localeChannel: REMOTE_VIEWER.LOCALE,
+ resolveNativeTitle: () =>
+ [connection.target?.name, t('remoteDesktop.title')].filter(Boolean).join(' · '),
+ onActivityChanged: (win, active) => {
+ connection.setActive(active);
+ if (!active && !win.isDestroyed()) win.webContents.setIgnoreMenuShortcuts(false);
+ },
+ createWindow: () => {
+ const win = createResourceUsageWindow(undefined, {
+ title: t('remoteDesktop.title'),
+ preload: 'remoteDesktopViewerPreload.js',
+ query: 'remoteDesktopViewer',
+ hash: '/remote-desktop-viewer',
+ width: 1180,
+ height: 780,
+ minWidth: 720,
+ minHeight: 420,
+ register: markRemoteDesktopViewer,
+ });
+ entry.window = win;
+ // Local navigation/reloads/crashes immediately retire authority, including in-flight starts.
+ win.webContents.on('did-start-navigation', (_event, _url, isInPlace, isMainFrame) => {
+ if (isMainFrame && !isInPlace) connection.deactivate();
+ });
+ win.webContents.on('render-process-gone', () => connection.deactivate());
+ win.on('closed', () => connection.deactivate());
+ win.webContents.on('before-input-event', (event, input) => {
+ if (input.type === 'keyDown' && input.code === 'KeyW' && (input.meta || input.control)) {
+ event.preventDefault();
+ entry.controller.close(win.webContents);
+ }
+ });
+ return win;
+ },
+ });
+ this.entries.add(entry);
+ if (this.locale) entry.controller.setLocale(this.locale);
+ return entry;
+ }
+ private entry(event: IpcMainInvokeEvent): Entry {
+ if (!isTrustedTopLevelCindyRendererEvent(event))
+ throwIpcError('PERMISSION_DENIED', 'Invalid viewer');
+ const entry = [...this.entries].find(
+ (e) => e.window && !e.window.isDestroyed() && e.window.webContents === event.sender,
+ );
+ if (!entry || !isTrustedCindyRendererWindow(entry.window))
+ throwIpcError('PERMISSION_DENIED', 'Invalid viewer');
+ return entry;
+ }
+ register(): void {
+ ipcMain.handle(REMOTE_VIEWER.OPEN, (event, target) => {
+ assertTrustedAppRendererEvent(event);
+ this.open(event.sender, target);
+ });
+ ipcMain.handle(REMOTE_VIEWER.STATE, (event) => this.entry(event).connection.snapshot());
+ ipcMain.handle(REMOTE_VIEWER.READY, (event) => {
+ this.entry(event).controller.markRendererReady(event.sender);
+ });
+ ipcMain.handle(REMOTE_VIEWER.PRESENTED, (event) => {
+ this.entry(event).controller.markPresentationReady(event.sender);
+ });
+ ipcMain.handle(REMOTE_VIEWER.CLOSE, (event) => {
+ this.entry(event).controller.close(event.sender);
+ });
+ ipcMain.handle(REMOTE_VIEWER.REQUEST, async (event, generation, request, attempt) => {
+ const result = await this.entry(event).connection.request(generation, request, attempt);
+ if (!result.ok) throwIpcError('PRECONDITION_FAILED', result.code);
+ return result.result;
+ });
+ ipcMain.handle(REMOTE_VIEWER.CLIPBOARD, async (event, generation, action) => {
+ const result = await this.entry(event).connection.clipboard(generation, action);
+ if (!result.ok) throwIpcError('PRECONDITION_FAILED', result.code);
+ });
+ ipcMain.handle(REMOTE_VIEWER.ICE, async (event, generation, attempt) => {
+ const entry = this.entry(event);
+ try {
+ entry.connection.beginMedia(generation, attempt);
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'DESKTOP_VIDEO_STOPPED');
+ }
+ const result = await loadDesktopIceServers();
+ try {
+ entry.connection.checkMedia(generation, attempt);
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'DESKTOP_VIDEO_STOPPED');
+ }
+ return result;
+ });
+ ipcMain.handle(REMOTE_VIEWER.FULLSCREEN, (event) => {
+ const entry = this.entry(event);
+ const win = entry.window!;
+ win.setFullScreen(!win.isFullScreen());
+ });
+ ipcMain.handle(REMOTE_VIEWER.INPUT_FOCUS, (event, generation, focused) => {
+ const entry = this.entry(event);
+ if (typeof focused !== 'boolean') throwIpcError('INVALID_PARAMS', 'Invalid input focus');
+ if (focused) {
+ try {
+ entry.connection.check(generation);
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'DESKTOP_STOPPED');
+ }
+ } else if (generation !== entry.connection.generation) return;
+ event.sender.setIgnoreMenuShortcuts(focused && entry.window!.isFocused());
+ });
+ }
+}
diff --git a/apps/desktop/src/main/resource-usage-window/controller.ts b/apps/desktop/src/main/resource-usage-window/controller.ts
index ab8fe71036..9aaf0f3aee 100644
--- a/apps/desktop/src/main/resource-usage-window/controller.ts
+++ b/apps/desktop/src/main/resource-usage-window/controller.ts
@@ -34,6 +34,12 @@ export interface ResourceUsageOwnerWindow {
export interface ResourceUsageWindowControllerDeps {
createWindow: () => BrowserWindow;
+ /** Optional surface adapter; defaults preserve the resource monitor. */
+ activityChannel?: string;
+ activityPayload?: (active: boolean) => unknown;
+ localeChannel?: string;
+ prewarmWork?: boolean;
+ onActivityChanged?: (window: BrowserWindow, active: boolean) => void;
isOpenSender: (sender: WebContents) => boolean;
/** 打开监视器的那扇应用窗;用于跟随显隐并在关闭监视器后恢复焦点。 */
getOwnerWindow?: (sender: WebContents) => ResourceUsageOwnerWindow | null;
@@ -171,7 +177,7 @@ export class ResourceUsageWindowController {
private sendLocale(win: BrowserWindow, locale: SupportedLocale): void {
if (win.webContents.isDestroyed()) return;
try {
- win.webContents.send(RESOURCE_USAGE_WINDOW_LOCALE_CHANGED_CHANNEL, locale);
+ win.webContents.send(this.deps.localeChannel ?? RESOURCE_USAGE_WINDOW_LOCALE_CHANGED_CHANNEL, locale);
} catch {
// 窗口可能在 isDestroyed 检查与 send 之间被系统销毁。
}
@@ -229,7 +235,7 @@ export class ResourceUsageWindowController {
this.visible = false;
// Windows 预热只加载 BrowserWindow / renderer。昂贵且可能触发安全软件管道异常的
// OS 扫描必须等用户显式 open;其他平台保留既有首份快照预热体验。
- this.samplingActive = this.pendingOpen || this.platform() !== 'win32';
+ this.samplingActive = this.pendingOpen || (this.deps.prewarmWork ?? this.platform() !== 'win32');
this.destroyingWindow = false;
this.applyNativeTitle(win);
if (this.locale) this.sendLocale(win, this.locale);
@@ -422,9 +428,10 @@ export class ResourceUsageWindowController {
private setSamplingActive(win: BrowserWindow, active: boolean): void {
this.samplingActive = active;
+ this.deps.onActivityChanged?.(win, active);
if (win.isDestroyed() || win.webContents.isDestroyed()) return;
try {
- win.webContents.send(RESOURCE_USAGE_WINDOW_SAMPLING_ACTIVE_CHANNEL, active);
+ win.webContents.send(this.deps.activityChannel ?? RESOURCE_USAGE_WINDOW_SAMPLING_ACTIVE_CHANNEL, this.deps.activityPayload?.(active) ?? active);
} catch {
// 窗口可能在 isDestroyed 检查与 send 之间被系统销毁。
}
@@ -517,7 +524,7 @@ export class ResourceUsageWindowController {
if (this.visible) win.hide();
this.rendererReady = false;
this.presentationReady = false;
- this.setSamplingActive(win, shouldRestore || this.platform() !== 'win32');
+ this.setSamplingActive(win, shouldRestore || (this.deps.prewarmWork ?? this.platform() !== 'win32'));
if (shouldRestore) {
this.pendingOpen = true;
this.scheduleOpenFallback(win);
diff --git a/apps/desktop/src/main/resource-usage-window/window.ts b/apps/desktop/src/main/resource-usage-window/window.ts
index 72977be01d..71c1090e7c 100644
--- a/apps/desktop/src/main/resource-usage-window/window.ts
+++ b/apps/desktop/src/main/resource-usage-window/window.ts
@@ -27,7 +27,12 @@ import { markResourceUsageWebContentsId } from './registry.js';
const log = createLogger('resource-usage-window');
-export function createResourceUsageWindow(parent?: BrowserWindow): BrowserWindow {
+/** The same safe window factory also serves lightweight remote desktop viewers. */
+export function createResourceUsageWindow(parent?: BrowserWindow, surface?: {
+ title: string; preload: string; query: string; hash: string;
+ width: number; height: number; register(id: number): void;
+ minWidth?: number; minHeight?: number;
+}): BrowserWindow {
const platformOptions =
process.platform === 'darwin'
? { titleBarStyle: 'hidden' as const, trafficLightPosition: { x: 12, y: 16 } }
@@ -37,11 +42,11 @@ export function createResourceUsageWindow(parent?: BrowserWindow): BrowserWindow
process.platform === 'darwin' || !parent || parent.isDestroyed() ? {} : { parent };
const win = new BrowserWindow({
- width: 580,
- height: 520,
- minWidth: 380,
- minHeight: 320,
- title: t('titleBar.menuItems.resourceUsage'),
+ width: surface?.width ?? 580,
+ height: surface?.height ?? 520,
+ minWidth: surface?.minWidth ?? 380,
+ minHeight: surface?.minHeight ?? 320,
+ title: surface?.title ?? t('titleBar.menuItems.resourceUsage'),
icon: app.isPackaged
? path.join(process.resourcesPath, 'icon.png')
: path.join(__dirname, '../../resources/icon.png'),
@@ -51,7 +56,7 @@ export function createResourceUsageWindow(parent?: BrowserWindow): BrowserWindow
...platformOptions,
...parentOption,
webPreferences: {
- preload: path.join(__dirname, 'resourceUsagePreload.js'),
+ preload: surface ? path.join(__dirname, surface.preload) : path.join(__dirname, 'resourceUsagePreload.js'),
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
@@ -71,7 +76,7 @@ export function createResourceUsageWindow(parent?: BrowserWindow): BrowserWindow
installWindowFullscreenStateBroadcast(win, {
getDisplayBounds: (bounds) => screen.getDisplayMatching(bounds).bounds,
});
- markResourceUsageWebContentsId(win.webContents.id);
+ (surface?.register ?? markResourceUsageWebContentsId)(win.webContents.id);
markAppContentWindow(win);
applyAppearanceToWindow(win);
win.webContents.on('did-finish-load', () => {
@@ -81,18 +86,18 @@ export function createResourceUsageWindow(parent?: BrowserWindow): BrowserWindow
installSelectionContextMenu(win);
installExternalLinkGuards(win);
- const hash = '/resource-usage-window';
+ const hash = surface?.hash ?? '/resource-usage-window';
let loadPromise: Promise<void>;
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
const url = new URL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
- url.searchParams.set('resourceUsageWindow', '1');
+ url.searchParams.set(surface?.query ?? 'resourceUsageWindow', '1');
url.hash = hash;
loadPromise = win.loadURL(url.toString());
} else {
loadPromise = win.loadFile(
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
{
- query: { resourceUsageWindow: '1' },
+ query: { [surface?.query ?? 'resourceUsageWindow']: '1' },
hash,
},
);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index a3b018c13f..2a72f04f9d 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,3 +1,4 @@
+import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';
import type { RoutineInput } from '@cindy/maker-scheduler';
import type { BotToolsetContext } from '../shared/botRemoteCapabilities';
import { contextBridge, ipcRenderer, webUtils } from 'electron';
@@ -4245,6 +4246,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ── Device Link (设备互联/跨设备远程控制) ─────────────────────────────
// 同账号设备经 server relay 互联;此处只暴露开关 + 设备列表管理面,
// 隧道(远程会话控制)在 M3 接入。
+ openRemoteDesktop: (target: {deviceId: string; name: string}): Promise<void> => ipcRenderer.invoke(REMOTE_VIEWER.OPEN, target),
remoteDesktop: {
state: (checkWindowsSupport) => ipcRenderer.invoke(DESKTOP_LOCAL.STATE, checkWindowsSupport),
permissions: () => ipcRenderer.invoke(DESKTOP_LOCAL.PERMISSIONS),
diff --git a/apps/desktop/src/preload/remoteDesktopViewerPreload.ts b/apps/desktop/src/preload/remoteDesktopViewerPreload.ts
new file mode 100644
index 0000000000..dccc208a44
--- /dev/null
+++ b/apps/desktop/src/preload/remoteDesktopViewerPreload.ts
@@ -0,0 +1,95 @@
+/** Remote viewer: window chrome, appearance and peer-bound desktop operations only. */
+
+import { contextBridge, ipcRenderer } from 'electron';
+
+import type { AppearanceSettings } from '../shared/appearanceSettings';
+import type { LocalThemesResult } from '../shared/local-themes';
+import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from '../shared/locale';
+import { REMOTE_VIEWER, type RemoteDesktopViewerApi } from '../shared/remoteDesktopViewer';
+
+type ApplicationMenuLocale = SupportedLocale;
+
+function onPayload<T>(channel: string, cb: (payload: T) => void): () => void {
+ const listener = (_event: Electron.IpcRendererEvent, payload: T): void => cb(payload);
+ ipcRenderer.on(channel, listener);
+ return () => ipcRenderer.removeListener(channel, listener);
+}
+
+function readPreferredSystemLocale(): ApplicationMenuLocale {
+ try {
+ const value = ipcRenderer.sendSync('app-locale:get-preferred-system-locale-sync');
+ return typeof value === 'string' && (SUPPORTED_LOCALES as readonly string[]).includes(value)
+ ? (value as ApplicationMenuLocale)
+ : DEFAULT_LOCALE;
+ } catch {
+ return DEFAULT_LOCALE;
+ }
+}
+
+const appearanceSettings = ipcRenderer.sendSync(
+ 'appearance-settings:get-sync',
+) as AppearanceSettings | null;
+
+const fanOutFullscreenChange = (cb: (isFullscreen: boolean) => void): (() => void) =>
+ onPayload('fullscreen-change', cb);
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ platform: process.platform,
+ preferredSystemLocale: readPreferredSystemLocale(),
+ windowMinimize: (): void => ipcRenderer.send('window-minimize'),
+ windowMaximize: (): void => ipcRenderer.send('window-maximize'),
+ windowClose: (): void => ipcRenderer.send('window-close'),
+ logToMain: (
+ level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal',
+ scope: string,
+ msg: string,
+ ): void => ipcRenderer.send('renderer:log', level, scope, msg),
+ appearanceSettings: {
+ getSync: (): AppearanceSettings | null => appearanceSettings,
+ onChanged: (cb: (settings: AppearanceSettings) => void): (() => void) =>
+ onPayload('appearance-settings:changed', cb),
+ },
+ localThemes: {
+ listSync: (): LocalThemesResult => {
+ try {
+ return ipcRenderer.sendSync('local-themes:list-sync') as LocalThemesResult;
+ } catch (error) {
+ return { success: false, error: String(error), themes: [], diagnostics: [] };
+ }
+ },
+ },
+ appShortcuts: {
+ getState: (): { overrides: Record<string, unknown>; platform: string } =>
+ ipcRenderer.sendSync('app-shortcuts:get'),
+ onChanged: (cb: (payload: { overrides?: Record<string, unknown> }) => void): (() => void) =>
+ onPayload('app-shortcuts:changed', cb),
+ },
+ theme: {
+ applyVibrancy: (familyId: string, isDark: boolean): void => {
+ ipcRenderer.send('theme:apply-vibrancy', { familyId, isDark });
+ },
+ },
+ // macOS 原生全屏时红绿灯会隐藏;资源窗口自己的标题栏据此撤销左侧让位。
+ onFullscreenChange: fanOutFullscreenChange,
+ getFullscreenState: (): Promise<boolean> => ipcRenderer.invoke('get-fullscreen-state'),
+ // 资源监视器是独立 renderer,localStorage 默认是空的。没有这条主进程线索时,
+ // 首启亮色门会把已登录用户的暗色主题锁成浅色。
+ authHasPersistedSessionHintSync: (): boolean =>
+ ipcRenderer.sendSync('auth:has-persisted-session-hint-sync') === true,
+ remoteDesktopViewer: {
+ state: () => ipcRenderer.invoke(REMOTE_VIEWER.STATE),
+ request: (generation, request, attempt) =>
+ ipcRenderer.invoke(REMOTE_VIEWER.REQUEST, generation, request, attempt),
+ ice: (generation, attempt) => ipcRenderer.invoke(REMOTE_VIEWER.ICE, generation, attempt),
+ clipboard: (generation, action) =>
+ ipcRenderer.invoke(REMOTE_VIEWER.CLIPBOARD, generation, action),
+ close: () => ipcRenderer.invoke(REMOTE_VIEWER.CLOSE),
+ fullscreen: () => ipcRenderer.invoke(REMOTE_VIEWER.FULLSCREEN),
+ rendererReady: () => ipcRenderer.invoke(REMOTE_VIEWER.READY),
+ presentationReady: () => ipcRenderer.invoke(REMOTE_VIEWER.PRESENTED),
+ onActive: (cb) => onPayload(REMOTE_VIEWER.ACTIVE, cb),
+ onLocale: (cb) => onPayload(REMOTE_VIEWER.LOCALE, cb),
+ inputFocus: (generation, focused) =>
+ ipcRenderer.invoke(REMOTE_VIEWER.INPUT_FOCUS, generation, focused),
+ } satisfies RemoteDesktopViewerApi,
+});
diff --git a/apps/desktop/src/renderer/__tests__/windowCloseBehavior.test.tsx b/apps/desktop/src/renderer/__tests__/windowCloseBehavior.test.tsx
index 48eec44909..6dd9d9e27c 100644
--- a/apps/desktop/src/renderer/__tests__/windowCloseBehavior.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/windowCloseBehavior.test.tsx
@@ -9,6 +9,14 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
+it('auxiliary close overrides do not require the main-window behavior bridge', () => {
+ const close = vi.fn();
+ Object.defineProperty(window, 'electronAPI', { configurable:true, value:{platform:'win32'} });
+ render(<WindowControls onClose={close} />);
+ fireEvent.click(screen.getByRole('button', {name:'titleBar.close'}));
+ expect(close).toHaveBeenCalledOnce();
+});
+
function installWindowsApi(closeBehavior: 'quit' | 'tray' | null) {
let closeBehaviorRequested: (() => void) | null = null;
const getWindowsCloseBehavior = vi.fn(async () => closeBehavior);
diff --git a/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx b/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
index 9c29955f82..ecb7189da1 100644
--- a/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
+++ b/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
@@ -15,7 +15,8 @@
import { useState, useSyncExternalStore, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import { RefreshCw, Pencil, Trash2, Check, X } from 'lucide-react';
+import { RefreshCw, Pencil, Trash2, Check, X, Monitor } from 'lucide-react';
+import { toast } from '@/lib/toast';
import { Spinner } from '@/components/ui/spinner';
import { Switch } from '@/components/ui/switch';
@@ -385,6 +386,14 @@ export function MyDevicesPanel({
</div>
{editingId !== d.deviceId && (
<div className="flex shrink-0 items-center gap-1">
+ {canBeControlledPlatform(d.platform) && !peerRevoked && (
+ <button type="button" className="inline-flex min-h-11 min-w-11 items-center justify-center rounded-full text-[var(--text-primary)] hover:bg-[var(--surface-chip)] disabled:opacity-40"
+ disabled={!d.online || !d.remoteControlEnabled || !d.controlEnabled}
+ title={t('remoteDesktop.title')} aria-label={t('remoteDesktop.title')}
+ onClick={() => void window.electronAPI.openRemoteDesktop({deviceId:d.deviceId,name:d.name}).catch(() => toast.error(t('remoteDesktop.connectionError')))}>
+ <Monitor size={16}/>
+ </button>
+ )}
<button
type="button"
onClick={() => {
diff --git a/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx b/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
index 5d27e11af5..e87f03650d 100644
--- a/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
+++ b/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
@@ -58,6 +58,7 @@ export function WindowControls({
useEffect(() => {
if (
+ onClose ||
(window.electronAPI.platform !== 'win32' && window.electronAPI.platform !== 'linux') ||
isSecondaryWindow() ||
isSidebarWindow() ||
@@ -79,7 +80,7 @@ export function WindowControls({
return window.electronAPI.platform === 'win32'
? window.electronAPI.windowBehavior.onWindowsCloseBehaviorRequested(onCloseBehaviorRequested)
: window.electronAPI.windowBehavior.onLinuxCloseBehaviorRequested(onCloseBehaviorRequested);
- }, []);
+ }, [onClose]);
useEffect(() => {
closeBehaviorDialogVisibleRef.current = showCloseBehaviorDialog;
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSettingsDrawer.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSettingsDrawer.test.tsx
index d1aff6a458..c1fc067174 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettingsDrawer.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettingsDrawer.test.tsx
@@ -4,6 +4,13 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libra
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createMemoryRouter, RouterProvider, useLocation } from 'react-router-dom';
+import { transferableAbortController } from 'node:util';
+
+// jsdom supplies its own AbortController while Request remains Node's native
+// fetch implementation. React Router must construct both in the same realm.
+const NativeAbortController = transferableAbortController().constructor;
+beforeEach(() => vi.stubGlobal('AbortController', NativeAbortController));
+afterEach(() => vi.unstubAllGlobals());
const guard = vi.hoisted(() => vi.fn(async () => true));
beforeEach(() => guard.mockReset().mockResolvedValue(true));
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/MachineSwitcherMenu.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/MachineSwitcherMenu.tsx
index 3010e97414..ccc55616d7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/MachineSwitcherMenu.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/MachineSwitcherMenu.tsx
@@ -69,7 +69,10 @@ import {
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
+ DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent,
} from '@/components/ui/dropdown-menu';
+import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
+import { isMobilePlatform } from '@cindy/maker-shared/device-list';
import {
isMachineSelected,
MACHINE_ALL,
@@ -94,6 +97,7 @@ export function MachineSwitcherMenu({
const { t } = useTranslation();
const navigate = useNavigate();
const { devices, selectedDeviceId, select, toggle } = useMachineSwitcher();
+ const desktopTargets=(useDeviceLinkDeviceList()??[]).filter(device=>!device.isSelf&&!isMobilePlatform(device.platform));
// 设备列表只看当前是否真有可展示的远程设备。hasRemote 还会把「目录已空、
// raw 仍记着远端」算进去——那是旧逃生口,标题恒在后会误画出「所有 / 本机」。
const showDeviceList = devices.length > 0;
@@ -130,6 +134,15 @@ export function MachineSwitcherMenu({
const triggerLabel = t('ccAgent.sidebar.machineSwitcher.menuTrigger');
const settingsItems = (
<>
+ {desktopTargets.length>0 && <DropdownMenuSub>
+ <DropdownMenuSubTrigger className={MENU_ITEM_CLASS}><Monitor size={14}/><span>{t('remoteDesktop.title')}</span></DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className={MENU_CONTENT_CLASS}>{desktopTargets.map(device=><DropdownMenuItem
+ key={device.deviceId} className={MENU_ITEM_CLASS}
+ disabled={!device.online||!device.remoteControlEnabled||!device.controlEnabled}
+ onSelect={()=>void window.electronAPI.openRemoteDesktop({deviceId:device.deviceId,name:device.name}).catch(()=>toast.error(t('remoteDesktop.connectionError')))}>
+ <span>{device.name}</span>
+ </DropdownMenuItem>)}</DropdownMenuSubContent>
+ </DropdownMenuSub>}
<DropdownMenuItem
className={MENU_ITEM_CLASS}
onSelect={() => navigate('/settings?tab=remote-control')}
diff --git a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx
new file mode 100644
index 0000000000..623e05ec47
--- /dev/null
+++ b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx
@@ -0,0 +1,370 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ Maximize2,
+ Minimize2,
+ Volume2,
+ VolumeX,
+ Settings2,
+ LogOut,
+ Monitor,
+ Clipboard,
+ Eye,
+ MousePointer2,
+} from 'lucide-react';
+import type { RemoteDesktopDisplayMode } from '@cindy/device-link';
+import { WindowControls } from '@/components/title-bar/WindowControls';
+import { useMacFullscreen } from '@/hooks/useMacFullscreen';
+import { DesktopViewerController, type ViewerSnapshot } from './viewerController';
+
+/** A clean, standalone remote desktop surface. No App, router, agent or task providers. */
+export function RemoteDesktopViewerWindow() {
+ const { t, i18n } = useTranslation();
+ const { isMac, isFullscreen } = useMacFullscreen();
+ const api = window.electronAPI.remoteDesktopViewer;
+ const root = useRef<HTMLDivElement>(null),
+ controller = useRef<DesktopViewerController | null>(null);
+ const [state, setState] = useState<ViewerSnapshot | null>(null);
+ const [settings, setSettings] = useState(false),
+ [notice, setNotice] = useState<string | null>(null),
+ [clipboardBusy, setClipboardBusy] = useState(false);
+ const [modes, setModes] = useState<RemoteDesktopDisplayMode[]>([]);
+ const generation = useRef(-1);
+ useEffect(() => {
+ if (!root.current) return;
+ controller.current = new DesktopViewerController(api, root.current, setState);
+ const off = api.onActive((value) => {
+ generation.current = value.generation;
+ if (!value.active) {
+ setSettings(false);
+ setNotice(null);
+ setModes([]);
+ setClipboardBusy(false);
+ (document.activeElement as HTMLElement | null)?.blur();
+ }
+ });
+ const locale = api.onLocale((value) => {
+ void i18n.changeLanguage(value);
+ });
+ const blur = () => {
+ controller.current?.releaseInput();
+ void api.inputFocus(generation.current, false).catch(() => {});
+ };
+ const focus = (event: FocusEvent) => {
+ void api
+ .inputFocus(generation.current, (event.target as HTMLElement)?.id === 'keyboard-input')
+ .catch(() => {});
+ };
+ document.addEventListener('focusin', focus);
+ window.addEventListener('blur', blur);
+ void api
+ .state()
+ .then((value) => {
+ generation.current = Math.max(generation.current, value.generation);
+ })
+ .catch(() => {});
+ // The quiet connecting shell is renderable content; network setup never gates opening the window.
+ void api
+ .rendererReady()
+ .then(() => api.presentationReady())
+ .catch(() => {});
+ return () => {
+ off();
+ locale();
+ document.removeEventListener('focusin', focus);
+ window.removeEventListener('blur', blur);
+ controller.current?.dispose();
+ controller.current = null;
+ };
+ }, [api, i18n]);
+ const clipboard = async (action: 'copy' | 'paste') => {
+ if (clipboardBusy) return;
+ setClipboardBusy(true);
+ setNotice(null);
+ const current = generation.current;
+ try {
+ await controller.current?.clipboard(action);
+ if (current === generation.current) setNotice(t('remoteDesktop.viewer.clipboardDone'));
+ } catch {
+ if (current === generation.current) setNotice(t('remoteDesktop.viewer.clipboardFailed'));
+ } finally {
+ if (current === generation.current) setClipboardBusy(false);
+ }
+ };
+ const toggleSettings = () => {
+ controller.current?.releaseInput();
+ setSettings((value) => !value);
+ if (state?.caps?.displayModes)
+ void controller.current
+ ?.displayModes()
+ .then(setModes)
+ .catch(() => setModes([]));
+ };
+ const action = 'remote-viewer-action';
+ return (
+ <div className={`remote-viewer-window ${isFullscreen ? 'remote-viewer-fullscreen' : ''}`}>
+ <header
+ className="remote-viewer-toolbar"
+ style={{ paddingLeft: isMac && !isFullscreen ? 82 : 12 }}
+ >
+ <Monitor size={16} />
+ <span className="remote-viewer-title">
+ {state?.target?.name ?? t('remoteDesktop.title')}
+ </span>
+ <span className="remote-viewer-status">
+ {state?.ready
+ ? t(state.controlling ? 'remoteDesktop.controlling' : 'remoteDesktop.viewOnly')
+ : t('remoteDesktop.connecting')}
+ </span>
+ {(state?.caps?.displays.length ?? 0) > 1 && (
+ <select
+ aria-label={t('remoteDesktop.display')}
+ value={state?.displayId}
+ onChange={(e) => controller.current?.selectDisplay(e.target.value)}
+ >
+ {state?.caps?.displays.map((display) => (
+ <option key={display.id} value={display.id}>
+ {display.name}
+ </option>
+ ))}
+ </select>
+ )}
+ <button
+ className={action}
+ disabled={!state?.ready || !state.caps?.canControl}
+ title={t(
+ state?.controlling ? 'remoteDesktop.releaseControl' : 'remoteDesktop.takeControl',
+ )}
+ aria-label={t(
+ state?.controlling ? 'remoteDesktop.releaseControl' : 'remoteDesktop.takeControl',
+ )}
+ onClick={() => void controller.current?.setControl(!state?.controlling)}
+ >
+ {state?.controlling ? <MousePointer2 size={16} /> : <Eye size={16} />}
+ </button>
+ {state?.caps?.systemAudio && (
+ <button
+ className={action}
+ aria-label={t('remoteDesktop.viewer.sound')}
+ aria-pressed={state.settings.audio}
+ onClick={() => controller.current?.settings({ audio: !state.settings.audio })}
+ >
+ {state.settings.audio ? <Volume2 size={16} /> : <VolumeX size={16} />}
+ </button>
+ )}
+ <button
+ className={action}
+ aria-label={t(
+ isFullscreen
+ ? 'remoteDesktop.viewer.exitFullscreen'
+ : 'remoteDesktop.viewer.fullscreen',
+ )}
+ onClick={() => void api.fullscreen()}
+ >
+ {isFullscreen ? <Minimize2 size={16} /> : <Maximize2 size={16} />}
+ </button>
+ <button
+ className={action}
+ aria-label={t('remoteDesktop.viewer.settings')}
+ aria-expanded={settings}
+ onClick={toggleSettings}
+ >
+ <Settings2 size={16} />
+ </button>
+ <button
+ className={action}
+ aria-label={t('remoteDesktop.disconnect')}
+ onClick={() => void api.close()}
+ >
+ <LogOut size={16} />
+ </button>
+ {!isMac && <WindowControls onClose={() => api.close()} />}
+ </header>
+ <div ref={root} className="remote-viewer-content">
+ <div id="stage" tabIndex={0} aria-label={t('remoteDesktop.title')}>
+ <img id="image" alt="" />
+ <video id="video" autoPlay muted playsInline />
+ <div id="cursor">
+ <img id="cursor-image" alt="" />
+ </div>
+ </div>
+ <textarea
+ id="keyboard-input"
+ autoCapitalize="off"
+ autoComplete="off"
+ autoCorrect="off"
+ spellCheck={false}
+ aria-label={t('remoteDesktop.viewer.inputHint')}
+ />
+ <div id="mouse-buttons" hidden>
+ <button id="mouse-left" />
+ <button id="mouse-right" />
+ <button id="mouse-wheel">
+ <span id="mouse-wheel-grip" />
+ </button>
+ </div>
+ {(!state?.ready || state?.error || state?.status === 'reconnecting') && (
+ <div className="remote-viewer-connection" role="status">
+ <span>
+ {state?.error
+ ? t(
+ state.error === 'connectionBusy' && state.caps?.connectionTakeover
+ ? 'remoteDesktop.connectionBusyTakeover'
+ : `remoteDesktop.${state.error}`,
+ )
+ : t(
+ state?.status === 'reconnecting'
+ ? 'remoteDesktop.reconnecting'
+ : 'remoteDesktop.connecting',
+ )}
+ </span>
+ {state?.error && (
+ <button className={action} onClick={() => controller.current?.retry()}>
+ {t(
+ state.error === 'connectionBusy' && state.caps?.connectionTakeover
+ ? 'remoteDesktop.takeoverConnection'
+ : 'remoteDesktop.connect',
+ )}
+ </button>
+ )}
+ {state?.error === 'permissionHint' && <button className={action} onClick={() => {
+ void controller.current?.permissionGuide().then(() => setNotice(t('remoteDesktop.permissionGuideOpened')))
+ .catch(() => setNotice(t('remoteDesktop.permissionActionFailed')));
+ setSettings(true);
+ }}>{t('remoteDesktop.openGuideOnComputer')}</button>}
+ </div>
+ )}
+ {state?.ready && (
+ <div className="remote-viewer-network">
+ {state.transport === 'screenshots'
+ ? t('remoteDesktop.compatibility')
+ : state.transport === 'relay'
+ ? t('remoteDesktop.viewer.relay')
+ : state.transport === 'direct'
+ ? t('remoteDesktop.viewer.direct')
+ : t('remoteDesktop.live')}
+ {state.latency !== null ? ` · ${Math.round(state.latency)} ms` : ''}
+ </div>
+ )}
+ </div>
+ {settings && (
+ <aside className="remote-viewer-settings" aria-label={t('remoteDesktop.viewer.settings')}>
+ <div className="flex items-center justify-between">
+ <strong>{t('remoteDesktop.viewer.settings')}</strong>
+ <button className={action} onClick={() => setSettings(false)}>
+ {t('remoteDesktop.closePermissionGuide')}
+ </button>
+ </div>
+ <button className={action} onClick={() => controller.current?.fit()}>
+ {t('remoteDesktop.fit')}
+ </button>
+ {state?.caps?.videoSettings && (
+ <>
+ <label>
+ {t('remoteDesktop.viewer.fps')}
+ <select
+ value={state.settings.fps}
+ onChange={(e) =>
+ controller.current?.settings({ fps: Number(e.target.value) as 30 | 60 })
+ }
+ >
+ <option value={30}>30 fps</option>
+ <option value={60}>60 fps</option>
+ </select>
+ </label>
+ <label>
+ {t('remoteDesktop.viewer.quality')}
+ <select
+ value={state.settings.bitrate}
+ onChange={(e) =>
+ controller.current?.settings({
+ bitrate: Number(e.target.value) as 0 | 2000000 | 8000000 | 20000000,
+ })
+ }
+ >
+ {[0, 2000000, 8000000, 20000000].map((value, index) => (
+ <option key={value} value={value}>
+ {t(
+ `remoteDesktop.viewer.${['automatic', 'smooth', 'balanced', 'clear'][index]}`,
+ )}
+ </option>
+ ))}
+ </select>
+ </label>
+ </>
+ )}
+ {modes.length > 0 && (
+ <label>
+ {t('remoteDesktop.viewer.resolution')}
+ <select
+ disabled={!state?.controlling}
+ value={modes.find((mode) => mode.current)?.id ?? ''}
+ onChange={(e) =>
+ void controller.current
+ ?.resolution(e.target.value)
+ .then(() => setModes([]))
+ .catch(() => setNotice(t('remoteDesktop.viewer.settingsFailed')))
+ }
+ >
+ {modes.map((mode) => (
+ <option key={mode.id} value={mode.id}>
+ {mode.width} × {mode.height}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {state?.caps?.clipboardText && (
+ <div className="flex flex-col gap-2">
+ <span className="flex items-center gap-2">
+ <Clipboard size={16} />
+ {t('remoteDesktop.viewer.clipboard')}
+ </span>
+ <button
+ className={action}
+ disabled={!state.controlling || clipboardBusy}
+ onClick={() => void clipboard('copy')}
+ >
+ {t('remoteDesktop.viewer.copy')}
+ </button>
+ <button
+ className={action}
+ disabled={!state.controlling || clipboardBusy}
+ onClick={() => void clipboard('paste')}
+ >
+ {t('remoteDesktop.viewer.paste')}
+ </button>
+ </div>
+ )}
+ <button
+ className={action}
+ disabled={!state?.controlling}
+ onClick={() =>
+ controller.current?.keys(
+ state?.caps?.platform === 'darwin' ? ['MetaLeft', 'F3'] : ['MetaLeft', 'KeyD'],
+ )
+ }
+ >
+ {t('remoteDesktop.showDesktop')}
+ </button>
+ <button
+ className={action}
+ disabled={!state?.controlling}
+ onClick={() =>
+ controller.current?.keys(
+ state?.caps?.platform === 'darwin'
+ ? ['ControlLeft', 'ArrowUp']
+ : ['MetaLeft', 'Tab'],
+ )
+ }
+ >
+ {t('remoteDesktop.allWindows')}
+ </button>
+ <p>{t('remoteDesktop.viewer.inputHint')}</p>
+ {state?.caps?.displayModes && <p>{t('remoteDesktop.viewer.resolutionHint')}</p>}
+ {notice && <p role="status">{notice}</p>}
+ </aside>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts
new file mode 100644
index 0000000000..d8874840e9
--- /dev/null
+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts
@@ -0,0 +1,53 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, it, expect, vi } from 'vitest';
+import { mountRemoteDesktopViewer } from '@cindy/maker-shared/remote-desktop-viewer';
+import { DESKTOP_KEY_CODES, REMOTE_DESKTOP_NETWORK } from '@cindy/device-link';
+
+let viewer: ReturnType<typeof mountRemoteDesktopViewer>;
+let messages: Record<string,unknown>[];
+let stage: HTMLElement;
+beforeEach(()=>{
+ vi.useFakeTimers();
+ vi.stubGlobal('ResizeObserver',class {observe(){}disconnect(){}});
+ vi.stubGlobal('matchMedia',()=>({matches:true}));
+ vi.spyOn(HTMLMediaElement.prototype,'play').mockResolvedValue();
+ document.body.innerHTML='<div id="stage"><img id="image"><video id="video"></video><div id="cursor"><img id="cursor-image"></div></div><textarea id="keyboard-input"></textarea><div id="mouse-buttons"><button id="mouse-left"></button><button id="mouse-right"></button><button id="mouse-wheel"><span id="mouse-wheel-grip"></span></button></div>';
+ stage=document.getElementById('stage')!;
+ Object.defineProperties(stage,{clientWidth:{value:1000},clientHeight:{value:600}});
+ stage.setPointerCapture=vi.fn();
+ vi.spyOn(stage,'getBoundingClientRect').mockReturnValue({x:0,y:52,left:0,top:52,width:1000,height:600,right:1000,bottom:652,toJSON(){}});
+ messages=[];
+ viewer=mountRemoteDesktopViewer(document,message=>{
+ messages.push(message);
+ if(message.type==='input')viewer.receive({type:'ack',epoch:'lease',sequence:message.sequence});
+ },{desktop:true,net:REMOTE_DESKTOP_NETWORK,iceServers:[],keyCodes:DESKTOP_KEY_CODES});
+ viewer.receive({type:'init',epoch:'lease',width:1000,height:600});
+ viewer.receive({type:'control',enabled:true});
+});
+afterEach(()=>{viewer.dispose();vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllGlobals();});
+function pointer(type:string,x=500,y=352,button=0){const e=new MouseEvent(type,{clientX:x,clientY:y,button,bubbles:true,cancelable:true});Object.defineProperty(e,'pointerId',{value:1});stage.dispatchEvent(e);}
+function events(){return messages.flatMap(m=>m.type==='input'?m.events as Record<string,unknown>[]:[]);}
+it('maps real mouse movement, right button and wheel to the picture below the toolbar',()=>{
+ pointer('pointermove');vi.advanceTimersByTime(34);
+ expect(events()).toContainEqual({kind:'move',x:.5,y:.5});
+ expect(document.getElementById('cursor')!.style.display).toBe('none');
+ pointer('pointerdown',500,352,2);pointer('pointerup',500,352,2);
+ stage.dispatchEvent(new WheelEvent('wheel',{deltaY:32,bubbles:true,cancelable:true}));
+ expect(events()).toContainEqual({kind:'button',button:2,down:true,x:.5,y:.5});
+ expect(events()).toContainEqual({kind:'button',button:2,down:false,x:.5,y:.5});
+ expect(events()).toContainEqual({kind:'scroll',dx:0,dy:32});
+});
+it('commits IME text once and never forwards local toolbar keyboard input',()=>{
+ pointer('pointerdown');pointer('pointerup');
+ const input=document.getElementById('keyboard-input') as HTMLTextAreaElement;
+ input.dispatchEvent(new CompositionEvent('compositionstart',{bubbles:true}));
+ input.dispatchEvent(new KeyboardEvent('keydown',{code:'KeyN',key:'Process',isComposing:true,bubbles:true}));
+ input.value='你好';input.dispatchEvent(new CompositionEvent('compositionend',{bubbles:true}));
+ expect(events().filter(e=>e.kind==='text')).toEqual([{kind:'text',text:'你好'}]);
+ input.blur();document.dispatchEvent(new KeyboardEvent('keydown',{code:'KeyA',key:'a',bubbles:true}));
+ vi.advanceTimersByTime(34);expect(events().some(e=>e.kind==='key'&&e.code==='KeyA')).toBe(false);
+});
+it('releases held buttons on window blur and disposal removes all timers',()=>{
+ pointer('pointerdown');window.dispatchEvent(new Event('blur'));expect(events()).toContainEqual({kind:'release'});
+ viewer.dispose();messages=[];vi.advanceTimersByTime(5000);expect(messages).toEqual([]);
+});
diff --git a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts b/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts
new file mode 100644
index 0000000000..3333369b69
--- /dev/null
+++ b/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts
@@ -0,0 +1,406 @@
+import {
+ DESKTOP_KEY_CODES,
+ REMOTE_DESKTOP_NETWORK,
+ REMOTE_DESKTOP_ICE_SERVERS,
+ REMOTE_DESKTOP_MAX_FRAME_BYTES,
+ RemoteDesktopViewerSession,
+ RemoteDesktopViewerMedia,
+ remoteDesktopFailureKey,
+ isDesktopInput,
+ type RemoteDesktopCapabilities,
+ type RemoteDesktopVideoSettings,
+ type RemoteDesktopRequest,
+ type DesktopInput,
+} from '@cindy/device-link';
+import { mountRemoteDesktopViewer } from '@cindy/maker-shared/remote-desktop-viewer';
+import { extractIpcError } from '@/utils/ipcError';
+import type {
+ RemoteDesktopViewerApi,
+ RemoteViewerState,
+} from '../../../shared/remoteDesktopViewer';
+
+export interface ViewerSnapshot {
+ target: RemoteViewerState['target'];
+ status: string;
+ error: string | null;
+ controlling: boolean;
+ caps: RemoteDesktopCapabilities | null;
+ displayId: string;
+ transport: string;
+ latency: number | null;
+ settings: RemoteDesktopVideoSettings;
+ ready: boolean;
+}
+
+/** Desktop presentation adapter. Reuses the Mobile lease, browser media and
+ * input queue; only window visibility and native clipboard live on Desktop.
+ */
+export class DesktopViewerController {
+ private state: ViewerSnapshot = {
+ target: null,
+ status: 'connecting',
+ error: null,
+ controlling: false,
+ caps: null,
+ displayId: '',
+ transport: '',
+ latency: null,
+ settings: { fps: 30, bitrate: 0, audio: true },
+ ready: false,
+ };
+ private scope: RemoteViewerState = { target: null, active: false, generation: -1 };
+ private disposed = false;
+ private opening = false;
+ private epoch = 0;
+ private resuming = false;
+ private wantsControl = true;
+ private retryAt = 0;
+ private retryDelay = 1000;
+ private frameBusy: string | null = null;
+ private heartbeatBusy: string | null = null;
+ private streaming = false;
+ private session: RemoteDesktopViewerSession;
+ private media: RemoteDesktopViewerMedia;
+ private runtime: ReturnType<typeof mountRemoteDesktopViewer>;
+ private timers: ReturnType<typeof setInterval>[];
+ private unsubscribers: (() => void)[];
+ constructor(
+ private readonly api: RemoteDesktopViewerApi,
+ root: HTMLElement,
+ private readonly changed: (state: ViewerSnapshot) => void,
+ ) {
+ this.session = new RemoteDesktopViewerSession(this.request);
+ this.media = new RemoteDesktopViewerMedia({
+ request: this.request,
+ send: (message) => this.runtime.receive(message),
+ loadIce: (attempt) => api.ice(this.scope.generation, attempt),
+ current: () =>
+ this.session.lease && this.state.caps
+ ? {
+ lease: this.session.lease,
+ caps: this.state.caps,
+ settings: {
+ ...this.state.settings,
+ audio: this.state.settings.audio && this.state.caps.systemAudio === true,
+ },
+ }
+ : null,
+ });
+ this.runtime = mountRemoteDesktopViewer(root, (message) => this.message(message), {
+ desktop: true,
+ net: REMOTE_DESKTOP_NETWORK,
+ iceServers: REMOTE_DESKTOP_ICE_SERVERS,
+ keyCodes: DESKTOP_KEY_CODES,
+ });
+ this.unsubscribers = [api.onActive((scope) => this.updateScope(scope))];
+ void api
+ .state()
+ .then((scope) => this.updateScope(scope))
+ .catch(() => {});
+ this.timers = [
+ setInterval(() => void this.heartbeat(), 3000),
+ setInterval(() => void this.frame(), 350),
+ ];
+ }
+ private publish(patch: Partial<ViewerSnapshot>): void {
+ this.state = { ...this.state, ...patch };
+ if (!this.disposed) this.changed(this.state);
+ }
+ private request = async <T>(
+ request: RemoteDesktopRequest,
+ beforeSend?: () => void,
+ ): Promise<T> => {
+ beforeSend?.();
+ const scope = this.scope;
+ if (!scope.active || this.disposed) throw new Error('DESKTOP_STOPPED');
+ try {
+ return (await this.api.request(
+ scope.generation,
+ request,
+ request.op === 'offer' || request.op === 'ice' ? this.media.attemptId : undefined,
+ )) as T;
+ } catch (error) {
+ throw new Error(extractIpcError(error)?.message ?? 'DESKTOP_UNAVAILABLE');
+ }
+ };
+ private updateScope(scope: RemoteViewerState): void {
+ if (this.disposed || scope.generation < this.scope.generation) return;
+ if (scope.generation === this.scope.generation && scope.active === this.scope.active) return;
+ this.cancel();
+ this.scope = scope;
+ this.resuming = scope.resume === true;
+ this.retryDelay = 1000;
+ this.publish({
+ target: scope.target,
+ error: null,
+ status: 'connecting',
+ caps: null,
+ ready: false,
+ });
+ if (scope.active) void this.connect();
+ }
+ private cancel(preserveFrame = false): void {
+ this.epoch++;
+ this.opening = false;
+ this.streaming = false;
+ this.media.reset();
+ this.runtime?.receive({ type: 'releaseInput' });
+ void this.session.stop().catch(() => {});
+ this.runtime?.receive({ type: 'stop', preserveFrame });
+ this.publish({ controlling: false, ready: false, transport: '', latency: null });
+ }
+ private async connect(takeover = false): Promise<void> {
+ if (this.opening || !this.scope.active || this.disposed) return;
+ this.opening = true;
+ const epoch = this.epoch;
+ this.publish({
+ error: null,
+ status: this.resuming ? 'reconnecting' : 'connecting',
+ ready: false,
+ });
+ try {
+ const resume = this.resuming;
+ this.resuming = true;
+ const { caps, lease } = await this.session.connect({
+ displayId: this.state.displayId || undefined,
+ resume,
+ takeover,
+ isCurrent: () => this.epoch === epoch && !this.disposed && this.scope.active,
+ onCapabilities: (caps) => this.publish({ caps }),
+ });
+ if (epoch !== this.epoch) return;
+ this.publish({ caps, displayId: lease.display.id, status: 'connecting' });
+ this.runtime.receive({
+ type: 'init',
+ epoch: lease.lease,
+ width: lease.display.width,
+ height: lease.display.height,
+ fillHeight: false,
+ trickleIce: caps.trickleIce === true,
+ audio: caps.systemAudio && this.state.settings.audio,
+ });
+ this.runtime.receive({ type: 'mode', mode: 'pointer' });
+ if (caps.canControl && this.wantsControl) await this.setControl(true);
+ } catch (error) {
+ if (epoch === this.epoch) this.fail(error);
+ } finally {
+ if (epoch === this.epoch) this.opening = false;
+ }
+ }
+ private fail(error: unknown): void {
+ const code = error instanceof Error ? error.message : '';
+ const blocked = remoteDesktopFailureKey(code);
+ this.cancel(true);
+ this.publish({ status: 'reconnecting', error: blocked });
+ this.retryAt = Date.now() + this.retryDelay;
+ this.retryDelay = Math.min(15000, this.retryDelay * 2);
+ }
+ retry(): void {
+ this.cancel(true);
+ this.resuming = false;
+ void this.connect(this.state.error === 'connectionBusy');
+ }
+ async setControl(enabled: boolean): Promise<void> {
+ this.wantsControl = enabled;
+ this.runtime.receive({ type: 'releaseInput' });
+ const lease = this.session.lease;
+ try {
+ const result = await this.session.control(enabled);
+ if (lease !== this.session.lease) return;
+ this.publish({ controlling: result.controlling, error: null });
+ this.runtime.receive({ type: 'control', enabled: result.controlling && this.state.ready });
+ } catch (error) {
+ if (lease !== this.session.lease) return;
+ const code = error instanceof Error ? error.message : '';
+ if (/DESKTOP_(LEASE_EXPIRED|STOPPED|DISABLED)|ACCESS_REVOKED|REMOTE_DISABLED/.test(code)) {
+ this.fail(error); return;
+ }
+ this.publish({ controlling: lease?.controlling === true,
+ error: enabled ? remoteDesktopFailureKey(code) ?? 'busy' : null });
+ this.runtime.receive({ type: 'control', enabled: false });
+ }
+ }
+ selectDisplay(displayId: string): void {
+ if (
+ !this.state.caps?.displays.some((d) => d.id === displayId) ||
+ displayId === this.state.displayId
+ )
+ return;
+ this.cancel(true);
+ this.resuming = false;
+ this.publish({ displayId });
+ void this.connect();
+ }
+ settings(patch: Partial<RemoteDesktopVideoSettings>): void {
+ this.publish({ settings: { ...this.state.settings, ...patch } });
+ this.runtime.receive({
+ type: 'videoSettings',
+ audio: this.state.settings.audio && this.state.caps?.systemAudio === true,
+ });
+ }
+ releaseInput(): void {
+ this.runtime.receive({ type: 'releaseInput' });
+ }
+ fit(): void {
+ this.runtime.receive({ type: 'fit' });
+ }
+ keys(codes: string[]): void {
+ const events: DesktopInput[] = [
+ ...codes.map((code) => ({ kind: 'key' as const, code, down: true })),
+ ...codes
+ .slice()
+ .reverse()
+ .map((code) => ({ kind: 'key' as const, code, down: false })),
+ ];
+ this.runtime.receive({ type: 'events', events });
+ }
+ async clipboard(action: 'copy' | 'paste'): Promise<void> {
+ this.releaseInput();
+ await this.api.clipboard(this.scope.generation, action);
+ }
+ async permissionGuide(): Promise<void> {
+ await this.request({ op: 'permissions', action: 'guide' });
+ }
+ displayModes() {
+ const lease = this.session.lease;
+ if (!lease) return Promise.resolve([]);
+ return this.request<import('@cindy/device-link').RemoteDesktopDisplayMode[]>({
+ op: 'displayModes',
+ lease: lease.lease,
+ });
+ }
+ async resolution(modeId: string): Promise<void> {
+ const lease = this.session.lease;
+ if (!lease) return;
+ await this.request({ op: 'resolution', lease: lease.lease, modeId });
+ this.cancel(true);
+ this.resuming = false;
+ void this.connect();
+ }
+ private async heartbeat(): Promise<void> {
+ if (!this.scope.active || this.disposed) return;
+ if (!this.session.lease) {
+ if (!this.state.error && Date.now() >= this.retryAt) void this.connect();
+ return;
+ }
+ const leaseId = this.session.lease.lease;
+ if (this.heartbeatBusy === leaseId) return;
+ this.heartbeatBusy = leaseId;
+ const epoch = this.epoch;
+ try {
+ const result = await this.session.heartbeat();
+ if (epoch === this.epoch) {
+ if (result.controlling !== this.state.controlling) {
+ this.publish({ controlling: result.controlling });
+ this.runtime.receive({
+ type: 'control',
+ enabled: result.controlling && this.state.ready,
+ });
+ }
+ }
+ } catch (error) {
+ if (epoch === this.epoch && !(error instanceof Error && error.message === 'INVOKE_TIMEOUT'))
+ this.fail(error);
+ } finally {
+ if (this.heartbeatBusy === leaseId) this.heartbeatBusy = null;
+ }
+ }
+ private async frame(): Promise<void> {
+ const lease = this.session.lease;
+ if (!lease || this.streaming || this.frameBusy === lease.lease || !this.scope.active) return;
+ this.frameBusy = lease.lease;
+ try {
+ const result = await this.request<{ jpeg: string | null; cursor?: unknown }>({
+ op: 'frame',
+ lease: lease.lease,
+ cursorOverlay: this.state.caps?.cursorOverlay === true,
+ });
+ if (
+ this.session.lease === lease &&
+ !this.streaming &&
+ typeof result.jpeg === 'string' &&
+ result.jpeg.length <= Math.ceil(REMOTE_DESKTOP_MAX_FRAME_BYTES / 3) * 4
+ )
+ this.runtime.receive({
+ type: 'frame',
+ jpeg: result.jpeg,
+ ...('cursor' in result ? { cursor: result.cursor } : {}),
+ });
+ } catch (error) {
+ if (this.session.lease === lease) this.fail(error);
+ } finally {
+ if (this.frameBusy === lease.lease) this.frameBusy = null;
+ }
+ }
+ private message(message: Record<string, unknown>): void {
+ const lease = this.session.lease;
+ if (!lease || message.epoch !== lease.lease || this.disposed) return;
+ if (['iceConfig', 'offer', 'ice'].includes(String(message.type))) {
+ void this.media.handle(message).catch((error) => {
+ if (this.session.lease === lease) this.fail(error);
+ });
+ return;
+ }
+ switch (message.type) {
+ case 'streaming':
+ this.streaming = true;
+ this.present('live');
+ break;
+ case 'framePresented':
+ this.present('compatibility');
+ break;
+ case 'fallback':
+ this.streaming = false;
+ this.publish({ transport: 'screenshots', status: 'compatibility' });
+ break;
+ case 'reconnecting':
+ this.publish({ status: 'reconnecting' });
+ break;
+ case 'network':
+ this.publish({
+ transport: String(message.transport),
+ latency: typeof message.latencyMs === 'number' ? message.latencyMs : null,
+ });
+ break;
+ case 'inputOverflow':
+ void this.setControl(false);
+ break;
+ case 'input':
+ if (
+ !Number.isSafeInteger(message.sequence) ||
+ !Array.isArray(message.events) ||
+ message.events.length > 64 ||
+ !message.events.every(isDesktopInput)
+ )
+ return;
+ void this.request({
+ op: 'input',
+ lease: lease.lease,
+ sequence: message.sequence as number,
+ events: message.events,
+ })
+ .catch(() => {
+ if (this.session.lease === lease) void this.setControl(false);
+ })
+ .finally(() => {
+ if (this.session.lease === lease)
+ this.runtime.receive({ type: 'ack', epoch: lease.lease, sequence: message.sequence });
+ });
+ break;
+ }
+ }
+ private present(status: string): void {
+ const wasReady = this.state.ready;
+ this.retryDelay = 1000;
+ this.publish({ ready: true, status });
+ if (!wasReady)
+ this.runtime.receive({ type: 'control', enabled: this.session.lease?.controlling === true });
+ }
+ dispose(): void {
+ this.cancel();
+ this.disposed = true;
+ for (const t of this.timers) clearInterval(t);
+ for (const off of this.unsubscribers) off();
+ this.runtime.dispose();
+ }
+}
diff --git a/apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css b/apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css
new file mode 100644
index 0000000000..3422299ee1
--- /dev/null
+++ b/apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css
@@ -0,0 +1,195 @@
+.remote-viewer-window {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+ background: var(--surface);
+ color: var(--text-primary);
+}
+.remote-viewer-toolbar {
+ display: flex;
+ flex: none;
+ height: 52px;
+ gap: 6px;
+ align-items: center;
+ border-bottom: 1px solid var(--border-default);
+ background: var(--surface);
+ -webkit-app-region: drag;
+ z-index: 5;
+}
+.remote-viewer-toolbar button,
+.remote-viewer-toolbar select {
+ -webkit-app-region: no-drag;
+}
+.remote-viewer-title {
+ flex: 1;
+ min-width: 60px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 13px;
+}
+.remote-viewer-status {
+ color: var(--text-secondary);
+ font-size: 12px;
+}
+.remote-viewer-action {
+ display: inline-flex;
+ justify-content: center;
+ align-items: center;
+ min-height: 44px;
+ min-width: 44px;
+ padding: 0 12px;
+ border-radius: 9999px;
+ cursor: pointer;
+ font-size: 13px;
+}
+.remote-viewer-action:hover {
+ background: var(--surface-chip);
+}
+.remote-viewer-action:disabled {
+ opacity: 0.4;
+ cursor: default;
+}
+.remote-viewer-action:focus-visible,
+.remote-viewer-window select:focus-visible {
+ outline: 2px solid var(--focus-ring);
+ outline-offset: 2px;
+}
+.remote-viewer-content {
+ --foreground: var(--text-primary);
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+}
+.remote-viewer-content #stage {
+ position: absolute;
+ inset: 0;
+ overflow: hidden;
+ touch-action: none;
+ user-select: none;
+}
+.remote-viewer-content #stage > img,
+.remote-viewer-content video {
+ position: absolute;
+ max-width: none;
+ pointer-events: none;
+ transform-origin: 0 0;
+}
+.remote-viewer-content video {
+ display: none;
+ z-index: 0;
+}
+.remote-viewer-content #image {
+ z-index: 1;
+}
+.remote-viewer-content img:not([src]) {
+ visibility: hidden;
+}
+.remote-viewer-content #cursor {
+ position: absolute;
+ z-index: 3;
+ width: 18px;
+ height: 18px;
+ border: 0;
+ pointer-events: none;
+ display: none;
+}
+.remote-viewer-content #cursor-image {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+}
+.remote-viewer-content #keyboard-input {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 1px;
+ height: 1px;
+ opacity: 0.01;
+ pointer-events: none;
+ border: 0;
+ padding: 0;
+ resize: none;
+}
+.remote-viewer-connection {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ max-width: 90%;
+ border: 1px solid var(--border-default);
+ border-radius: 12px;
+ padding: 12px 20px;
+ background: var(--surface);
+ font-size: 13px;
+ z-index: 4;
+}
+.remote-viewer-network {
+ position: absolute;
+ bottom: 12px;
+ left: 12px;
+ padding: 4px 10px;
+ border-radius: 9999px;
+ background: var(--surface);
+ color: var(--text-secondary);
+ font-size: 11px;
+ pointer-events: none;
+ z-index: 4;
+}
+.remote-viewer-settings {
+ position: absolute;
+ right: 12px;
+ top: 60px;
+ max-height: calc(100vh - 80px);
+ overflow: auto;
+ width: 320px;
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ border: 1px solid var(--border-default);
+ border-radius: 12px;
+ background: var(--surface);
+ z-index: 6;
+}
+.remote-viewer-settings label {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+}
+.remote-viewer-window select {
+ min-height: 36px;
+ max-width: 150px;
+ padding: 4px 8px;
+ border: 1px solid var(--border-default);
+ border-radius: 9999px;
+ color: var(--text-primary);
+ background: var(--surface);
+ font-size: 12px;
+}
+.remote-viewer-settings p {
+ font-size: 12px;
+ color: var(--text-secondary);
+}
+.remote-viewer-fullscreen .remote-viewer-toolbar {
+ position: absolute;
+ inset: 0 0 auto;
+ transition: transform 150ms ease-out;
+ transform: translateY(calc(-100% + 8px));
+}
+.remote-viewer-fullscreen .remote-viewer-toolbar:hover,
+.remote-viewer-fullscreen .remote-viewer-toolbar:focus-within {
+ transform: translateY(0);
+}
+@media (prefers-reduced-motion: reduce) {
+ .remote-viewer-fullscreen .remote-viewer-toolbar {
+ transition: none;
+ }
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b874cdc35d..14a0640c1a 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -60,7 +60,36 @@
"sendText": "Send text",
"keys": "Keys",
"showDesktop": "Desktop",
- "allWindows": "All windows"
+ "allWindows": "All windows",
+ "reconnecting": "Reconnecting…",
+ "connectionBusy": "Another device is connected to this remote desktop. Exit remote desktop on that device, then try connecting again.",
+ "takeoverConnection": "Take over connection",
+ "connectionBusyTakeover": "Another device is connected to this desktop. Taking over will disconnect that device.",
+ "remoteDisabled": "Remote control is disabled on the computer.",
+ "accessRevoked": "Access to this computer was revoked.",
+ "viewer": {
+ "settings": "Controls",
+ "sound": "Sound",
+ "fullscreen": "Full screen",
+ "exitFullscreen": "Exit full screen",
+ "fps": "Frame rate",
+ "quality": "Video quality",
+ "automatic": "Automatic",
+ "smooth": "Smooth",
+ "balanced": "Balanced",
+ "clear": "Clear",
+ "resolution": "Computer resolution",
+ "clipboard": "Text clipboard",
+ "copy": "Copy remote text to this computer",
+ "paste": "Paste local text remotely",
+ "clipboardDone": "Text transferred",
+ "clipboardFailed": "Could not transfer text. Check control access and keep text under 16,384 characters.",
+ "settingsFailed": "Could not change the display setting.",
+ "inputHint": "Click the picture to type. Ctrl+Alt+Esc releases keyboard focus; Cmd/Ctrl+W closes this window.",
+ "resolutionHint": "Resolution changes affect the actual remote monitor.",
+ "relay": "Video relay",
+ "direct": "Direct connection"
+ }
},
"ipcError": {
"INVALID_PARAMS": "Invalid input. Please check and try again.",
@@ -12228,7 +12257,6 @@
"unsavedDescription": "Leaving will discard these changes to the routine.",
"discard": "Discard Changes",
"continueEditing": "Keep Editing",
-
"title": "Routines",
"add": "Add Routine",
"back": "Back to Routines",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index b37e289e20..d10018ac9a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -60,7 +60,36 @@
"sendText": "文字を送信",
"keys": "キー",
"showDesktop": "デスクトップ",
- "allWindows": "すべてのウィンドウ"
+ "allWindows": "すべてのウィンドウ",
+ "reconnecting": "再接続中…",
+ "connectionBusy": "別のデバイスがこのリモートデスクトップに接続しています。そのデバイスでリモートデスクトップを終了してから、もう一度接続してください。",
+ "takeoverConnection": "接続を引き継ぐ",
+ "connectionBusyTakeover": "別のデバイスが接続中です。接続を引き継ぐと、そのデバイスは切断されます。",
+ "remoteDisabled": "????????????????????????",
+ "accessRevoked": "????????????????????????",
+ "viewer": {
+ "settings": "??",
+ "sound": "??",
+ "fullscreen": "?????",
+ "exitFullscreen": "????????",
+ "fps": "???????",
+ "quality": "??",
+ "automatic": "??",
+ "smooth": "????",
+ "balanced": "????",
+ "clear": "???",
+ "resolution": "??????????",
+ "clipboard": "???????????",
+ "copy": "??????????????????????",
+ "paste": "???????????????????",
+ "clipboardDone": "???????????",
+ "clipboardFailed": "??????????????????????16,384 ????????????",
+ "settingsFailed": "????????????????",
+ "inputHint": "???????????????Ctrl+Alt+Esc ?????????????????Cmd/Ctrl+W ??????????????",
+ "resolutionHint": "???????????????????????????",
+ "relay": "????",
+ "direct": "????"
+ }
},
"ipcError": {
"INVALID_PARAMS": "パラメータが無効です。確認して再試行してください。",
@@ -12211,7 +12240,6 @@
"unsavedDescription": "戻ると、このルーチンへの変更が破棄されます。",
"discard": "変更を破棄",
"continueEditing": "編集を続ける",
-
"title": "ルーティン",
"add": "ルーティンを追加",
"back": "ルーティンに戻る",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5059a98cff..88fe0c5023 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -60,7 +60,36 @@
"sendText": "텍스트 전송",
"keys": "키",
"showDesktop": "데스크톱",
- "allWindows": "모든 창"
+ "allWindows": "모든 창",
+ "reconnecting": "다시 연결 중…",
+ "connectionBusy": "다른 기기가 이 원격 데스크톱에 연결되어 있습니다. 해당 기기에서 원격 데스크톱을 종료한 후 다시 연결하세요.",
+ "takeoverConnection": "연결 넘겨받기",
+ "connectionBusyTakeover": "다른 기기가 연결되어 있습니다. 연결을 넘겨받으면 해당 기기의 연결이 끊어집니다.",
+ "remoteDisabled": "????? ?? ??? ?? ????.",
+ "accessRevoked": "? ???? ?? ?? ??? ???????.",
+ "viewer": {
+ "settings": "??",
+ "sound": "??",
+ "fullscreen": "?? ??",
+ "exitFullscreen": "?? ?? ??",
+ "fps": "??? ??",
+ "quality": "??",
+ "automatic": "??",
+ "smooth": "??",
+ "balanced": "??",
+ "clear": "??",
+ "resolution": "??? ???",
+ "clipboard": "??? ????",
+ "copy": "?? ???? ? ???? ??",
+ "paste": "?? ???? ???? ????",
+ "clipboardDone": "???? ??????",
+ "clipboardFailed": "???? ??? ? ????. ?? ??? ???? ??? 16,384? ??? ????.",
+ "settingsFailed": "????? ??? ??? ? ????.",
+ "inputHint": "??? ???? ?????. Ctrl+Alt+Esc? ??? ???? ???? Cmd/Ctrl+W? ? ?? ????.",
+ "resolutionHint": "???? ???? ?? ???? ?? ???? ?????.",
+ "relay": "?? ??",
+ "direct": "?? ??"
+ }
},
"ipcError": {
"INVALID_PARAMS": "매개변수가 잘못되었습니다. 확인 후 다시 시도하세요.",
@@ -12211,7 +12240,6 @@
"unsavedDescription": "돌아가면 이 루틴의 변경 사항이 삭제됩니다.",
"discard": "변경 사항 버리기",
"continueEditing": "계속 편집",
-
"title": "루틴",
"add": "루틴 추가",
"back": "루틴으로 돌아가기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 74bf570d19..846ca8ba80 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -60,7 +60,36 @@
"sendText": "发送文字",
"keys": "按键",
"showDesktop": "桌面",
- "allWindows": "所有窗口"
+ "allWindows": "所有窗口",
+ "reconnecting": "正在重新连接…",
+ "connectionBusy": "已有其他设备连接此远程桌面。请先在那台设备上退出远程桌面,再尝试连接。",
+ "takeoverConnection": "接管连接",
+ "connectionBusyTakeover": "已有其他设备连接此远程桌面。接管连接后,上一台设备会断开。",
+ "remoteDisabled": "???????????",
+ "accessRevoked": "????????????",
+ "viewer": {
+ "settings": "??",
+ "sound": "??",
+ "fullscreen": "??",
+ "exitFullscreen": "????",
+ "fps": "??",
+ "quality": "??",
+ "automatic": "??",
+ "smooth": "??",
+ "balanced": "??",
+ "clear": "??",
+ "resolution": "?????",
+ "clipboard": "?????",
+ "copy": "??????????",
+ "paste": "??????????",
+ "clipboardDone": "?????",
+ "clipboardFailed": "??????????????????????? 16,384 ???",
+ "settingsFailed": "?????????",
+ "inputHint": "?????????Ctrl+Alt+Esc ???????Cmd/Ctrl+W ???????",
+ "resolutionHint": "?????????????????",
+ "relay": "????",
+ "direct": "??"
+ }
},
"ipcError": {
"INVALID_PARAMS": "参数无效,请检查后重试。",
@@ -12211,7 +12240,6 @@
"unsavedDescription": "离开后会丢弃这次对例行任务的修改。",
"discard": "放弃修改",
"continueEditing": "继续编辑",
-
"title": "例行任务",
"add": "添加例行任务",
"back": "返回例行任务",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index e70fb7af4b..f151c69f06 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -60,7 +60,36 @@
"sendText": "傳送文字",
"keys": "按鍵",
"showDesktop": "桌面",
- "allWindows": "所有視窗"
+ "allWindows": "所有視窗",
+ "reconnecting": "正在重新連線…",
+ "connectionBusy": "已有其他裝置連線至此遠端桌面。請先在該裝置上退出遠端桌面,再嘗試連線。",
+ "takeoverConnection": "接管連線",
+ "connectionBusyTakeover": "已有其他裝置連線至此遠端桌面。接管連線後,上一台裝置會中斷。",
+ "remoteDisabled": "???????????",
+ "accessRevoked": "?????????????",
+ "viewer": {
+ "settings": "??",
+ "sound": "??",
+ "fullscreen": "???",
+ "exitFullscreen": "?????",
+ "fps": "???",
+ "quality": "??",
+ "automatic": "??",
+ "smooth": "??",
+ "balanced": "??",
+ "clear": "??",
+ "resolution": "?????",
+ "clipboard": "?????",
+ "copy": "??????????",
+ "paste": "?????????",
+ "clipboardDone": "?????",
+ "clipboardFailed": "??????????????????????? 16,384 ???",
+ "settingsFailed": "?????????",
+ "inputHint": "?????????Ctrl+Alt+Esc ???????Cmd/Ctrl+W ???????",
+ "resolutionHint": "?????????????????",
+ "relay": "????",
+ "direct": "????"
+ }
},
"ipcError": {
"INVALID_PARAMS": "引數無效,請檢查後重試。",
@@ -12211,7 +12240,6 @@
"unsavedDescription": "離開後會捨棄這次對例行任務的修改。",
"discard": "放棄修改",
"continueEditing": "繼續編輯",
-
"title": "例行任務",
"add": "新增例行任務",
"back": "返回例行任務",
diff --git a/apps/desktop/src/renderer/index.tsx b/apps/desktop/src/renderer/index.tsx
index 8a0a26fe36..e65c36a3d0 100644
--- a/apps/desktop/src/renderer/index.tsx
+++ b/apps/desktop/src/renderer/index.tsx
@@ -7,11 +7,14 @@
*/
const urlParams = new URLSearchParams(window.location.search);
+const isRemoteDesktopViewer = urlParams.get('remoteDesktopViewer') === '1';
const isResourceUsageWindow = urlParams.get('resourceUsageWindow') === '1';
const isSidebarWindow = urlParams.get('sidebarWindow') === '1';
const ghostPanelWindowId = urlParams.get('ghostPanelWindow');
-void (isResourceUsageWindow
+void (isRemoteDesktopViewer
+ ? import('./remote-desktop-viewer-entry')
+ : isResourceUsageWindow
? import('./resource-usage-entry')
: isSidebarWindow
? import('./sidebar-window-entry')
diff --git a/apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx b/apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx
new file mode 100644
index 0000000000..614e7026e3
--- /dev/null
+++ b/apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx
@@ -0,0 +1,33 @@
+import { createRoot } from 'react-dom/client';
+import '@fontsource-variable/inter';
+import 'harmonyos-sans-sc-webfont-splitted';
+import '@/i18n';
+import './themes/colors';
+import './styles/globals.css';
+import './features/remote-desktop/viewerWindow.css';
+import { getInitialThemeVariant, ThemeProvider } from './hooks/useTheme';
+import {
+ applyFontSettings,
+ getInitialFontSettings,
+ FontSettingsProvider,
+} from './hooks/useFontSettings';
+import { bootstrapLocalThemesSync } from './themes/local-themes';
+import { themeService } from './themes/theme-service';
+import { RemoteDesktopViewerWindow } from './features/remote-desktop/RemoteDesktopViewerWindow';
+import { TopLevelErrorBoundary } from './components/error/TopLevelErrorBoundary';
+
+document.documentElement.dataset.platform = window.electronAPI.platform;
+bootstrapLocalThemesSync();
+themeService.applyTheme(getInitialThemeVariant().theme);
+applyFontSettings(getInitialFontSettings());
+const root = document.getElementById('root');
+if (!root) throw new Error('Missing viewer root');
+createRoot(root).render(
+ <TopLevelErrorBoundary>
+ <ThemeProvider syncWindowVibrancy={false}>
+ <FontSettingsProvider>
+ <RemoteDesktopViewerWindow />
+ </FontSettingsProvider>
+ </ThemeProvider>
+ </TopLevelErrorBoundary>,
+);
diff --git a/apps/desktop/src/renderer/utils/ipcError.ts b/apps/desktop/src/renderer/utils/ipcError.ts
index 3fbc1cffc5..6181a5836c 100644
--- a/apps/desktop/src/renderer/utils/ipcError.ts
+++ b/apps/desktop/src/renderer/utils/ipcError.ts
@@ -1,24 +1,2 @@
-import { isIpcError, isIpcErrorCode, type IpcError } from '../../shared/ipc-errors';
-
-const IPC_ERROR_MESSAGE_RE = /(?:^|: Error: )\[([A-Z0-9_]+)\]\s*([\s\S]*)$/;
-
-export function extractIpcError(err: unknown): IpcError | null {
- if (isIpcError(err)) {
- return { code: err.code, message: err.message };
- }
- if (!(err instanceof Error)) return null;
- const match = IPC_ERROR_MESSAGE_RE.exec(err.message);
- if (!match) return null;
- const code = match[1];
- if (!isIpcErrorCode(code)) return null;
- return { code, message: match[2] };
-}
-
-export function mapIpcErrorToI18nKey(
- err: unknown,
- options?: { namespace?: string; fallback?: string },
-): string {
- const ipcError = extractIpcError(err);
- if (!ipcError) return options?.fallback ?? 'ipcError.unknown';
- return `${options?.namespace ?? 'ipcError'}.${ipcError.code}`;
-}
+// Shared decoding keeps Electron and renderer adapters on the same error contract.
+export * from '../../shared/ipcError';
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index e98212f99e..bf0af7bdd6 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3783,6 +3783,8 @@ interface ElectronAPI {
fetchReleaseNotesIndex: () => Promise<string[] | null>;
// ── Device Link (设备互联/跨设备远程控制) ─────────────────────────────
+ openRemoteDesktop: (target: {deviceId: string; name: string}) => Promise<void>;
+ remoteDesktopViewer: import('../shared/remoteDesktopViewer').RemoteDesktopViewerApi;
remoteDesktop: import('../shared/remoteDesktop').RemoteDesktopApi;
deviceLink: {
getState: () => Promise<{
diff --git a/apps/desktop/src/shared/ipcError.ts b/apps/desktop/src/shared/ipcError.ts
new file mode 100644
index 0000000000..958341b6bc
--- /dev/null
+++ b/apps/desktop/src/shared/ipcError.ts
@@ -0,0 +1,24 @@
+import { isIpcError, isIpcErrorCode, type IpcError } from './ipc-errors';
+
+const IPC_ERROR_MESSAGE_RE = /(?:^|: Error: )\[([A-Z0-9_]+)\]\s*([\s\S]*)$/;
+
+export function extractIpcError(err: unknown): IpcError | null {
+ if (isIpcError(err)) {
+ return { code: err.code, message: err.message };
+ }
+ if (!(err instanceof Error)) return null;
+ const match = IPC_ERROR_MESSAGE_RE.exec(err.message);
+ if (!match) return null;
+ const code = match[1];
+ if (!isIpcErrorCode(code)) return null;
+ return { code, message: match[2] };
+}
+
+export function mapIpcErrorToI18nKey(
+ err: unknown,
+ options?: { namespace?: string; fallback?: string },
+): string {
+ const ipcError = extractIpcError(err);
+ if (!ipcError) return options?.fallback ?? 'ipcError.unknown';
+ return `${options?.namespace ?? 'ipcError'}.${ipcError.code}`;
+}
diff --git a/apps/desktop/src/shared/remoteDesktopViewer.ts b/apps/desktop/src/shared/remoteDesktopViewer.ts
new file mode 100644
index 0000000000..6e9acd46b9
--- /dev/null
+++ b/apps/desktop/src/shared/remoteDesktopViewer.ts
@@ -0,0 +1,46 @@
+import type { DesktopIceServer, RemoteDesktopRequest } from '@cindy/device-link';
+
+export const REMOTE_VIEWER = {
+ OPEN: 'remote-desktop-viewer:open',
+ STATE: 'remote-desktop-viewer:state',
+ REQUEST: 'remote-desktop-viewer:request',
+ ICE: 'remote-desktop-viewer:ice',
+ CLIPBOARD: 'remote-desktop-viewer:clipboard',
+ CLOSE: 'remote-desktop-viewer:close',
+ READY: 'remote-desktop-viewer:ready',
+ PRESENTED: 'remote-desktop-viewer:presented',
+ ACTIVE: 'remote-desktop-viewer:active',
+ LOCALE: 'remote-desktop-viewer:locale',
+ FULLSCREEN: 'remote-desktop-viewer:fullscreen',
+ INPUT_FOCUS: 'remote-desktop-viewer:input-focus',
+} as const;
+
+export interface RemoteViewerTarget {
+ deviceId: string;
+ name: string;
+}
+export interface RemoteViewerState {
+ target: RemoteViewerTarget | null;
+ active: boolean;
+ generation: number;
+ resume?: boolean;
+}
+export type RemoteViewerReply = { ok: true; result: unknown } | { ok: false; code: string };
+/** Dedicated window bridge. The target and account are bound by Main, never by payload. */
+export interface RemoteDesktopViewerApi {
+ state(): Promise<RemoteViewerState>;
+ request(
+ generation: number,
+ request: RemoteDesktopRequest,
+ mediaAttempt?: string,
+ ): Promise<unknown>;
+ ice(generation: number, mediaAttempt: string): Promise<DesktopIceServer[]>;
+ clipboard(generation: number, action: 'copy' | 'paste'): Promise<void>;
+ close(): Promise<void>;
+ fullscreen(): Promise<void>;
+ rendererReady(): Promise<void>;
+ presentationReady(): Promise<void>;
+ onActive(listener: (state: RemoteViewerState) => void): () => void;
+ onLocale(listener: (locale: string) => void): () => void;
+ inputFocus(generation: number, focused: boolean): Promise<void>;
+}
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index d1dd95989f..1fc62df9b5 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -1,5 +1,6 @@
import {
useCallback,
+ useMemo,
useEffect,
useRef,
useState,
@@ -37,13 +38,11 @@ import { RemoteDesktopPanelButton } from "./RemoteDesktopPanelButton";
import { useTranslation } from "react-i18next";
import SegmentedControl from "@expo/ui/community/segmented-control";
import {
+ RemoteDesktopViewerSession,
+ RemoteDesktopViewerMedia,
+ remoteDesktopFailureKey,
REMOTE_DESKTOP_CHANNEL,
REMOTE_DESKTOP_MAX_FRAME_BYTES,
- isDesktopAttemptId,
- isDesktopIceCursor,
- parseDesktopIceCandidates,
- parseDesktopIceReply,
- type RemoteDesktopIceReply,
isRemoteDesktopCursor,
type RemoteDesktopCursor,
REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS,
@@ -313,6 +312,65 @@ export default function RemoteDesktopScreen() {
}),
[deviceId],
);
+ const viewerSession = useMemo(
+ () => ({ current: new RemoteDesktopViewerSession(request) }),
+ [request],
+ );
+ const authRef = useRef(auth);
+ authRef.current = auth;
+ const viewerMedia = useMemo(
+ () =>
+ new RemoteDesktopViewerMedia({
+ request,
+ send,
+ loadIce: () =>
+ resolveDesktopIceServers(() =>
+ authRef.current.apiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {
+ baseUrl: DEVICE_LINK_API_BASE_URL,
+ timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+ cache: "no-store",
+ }),
+ ),
+ current: () => {
+ const lease = active.current,
+ caps = capsRef.current?.value;
+ return lease && caps
+ ? {
+ lease,
+ caps,
+ settings: {
+ ...videoSettingsRef.current,
+ audio: Boolean(
+ caps.systemAudio &&
+ videoSettingsRef.current.audio &&
+ !audioUnavailable.current,
+ ),
+ },
+ }
+ : null;
+ },
+ onAttempt: (attempt) => {
+ mediaAttempt.current = attempt;
+ },
+ onOfferStart: (lease) =>
+ pendingMediaOffers.current.set(
+ lease,
+ (pendingMediaOffers.current.get(lease) ?? 0) + 1,
+ ),
+ onOfferSettled: (lease) => {
+ const remaining = (pendingMediaOffers.current.get(lease) ?? 1) - 1;
+ if (remaining > 0) pendingMediaOffers.current.set(lease, remaining);
+ else pendingMediaOffers.current.delete(lease);
+ if (alive.current) setSettingsRevision((value) => value + 1);
+ },
+ onOfferFailure: () => {
+ setStatus("compatibility");
+ setSettingBusy(false);
+ setSettingNotice(t("remoteDesktop.videoSettingsFailed"));
+ },
+ }),
+ [request, send, t],
+ );
const transferClipboard = async (action: "copy" | "paste") => {
const current = active.current;
const epoch = generation.current;
@@ -405,6 +463,7 @@ export default function RemoteDesktopScreen() {
pendingVideoSettings.current = null;
if (previous) pendingMediaOffers.current.delete(previous);
mediaAttempt.current = null;
+ viewerMedia.reset();
heldKeys.current.clear();
streaming.current = false;
receiveWindow.current = {
@@ -426,23 +485,19 @@ export default function RemoteDesktopScreen() {
setKeyboard(false);
setBusy(false);
}
- if (previous) {
- const lockScreen = exiting && exitLock.current;
- return request({
- op: "stop",
- lease: previous.lease,
- ...(lockScreen ? { lockScreen: true } : {}),
- }).catch(() => {
+ const lockScreen = Boolean(previous && exiting && exitLock.current);
+ return viewerSession
+ .current!.stop(lockScreen)
+ .then(() => {})
+ .catch(() => {
if (lockScreen)
Alert.alert(
t("remoteDesktop.lockOnExit"),
t("remoteDesktop.lockOnExitFailed"),
);
});
- }
- return Promise.resolve();
},
- [request, send, t],
+ [request, send, t, viewerSession, viewerMedia],
);
const stopRef = useRef(stop);
stopRef.current = stop;
@@ -470,23 +525,7 @@ export default function RemoteDesktopScreen() {
console.debug("[remote-desktop] connection failed", {
code: code && /^[A-Z_]+$/.test(code) ? code : "UNKNOWN",
});
- const blocked =
- code === "ACCESS_REVOKED"
- ? "accessRevoked"
- : code === "REMOTE_DISABLED"
- ? "remoteDisabled"
- : code === "DESKTOP_BUSY"
- ? "connectionBusy"
- : code === "CHANNEL_NOT_ALLOWED"
- ? "upgrade"
- : message.includes("DESKTOP_DISABLED")
- ? "disabled"
- : message.includes("PERMISSION") ||
- message.includes("ACCESSIBILITY")
- ? "permissionHint"
- : message.includes("DESKTOP_STOPPED")
- ? "disconnected"
- : null;
+ const blocked = remoteDesktopFailureKey(code ?? message);
stop(!blocked);
setError(blocked);
if (blocked) recovery.current.enabled = false;
@@ -525,53 +564,36 @@ export default function RemoteDesktopScreen() {
await linkRef.current.openLink(deviceId);
if (current !== generation.current) return;
mark("link-ready");
- const result = await request<RemoteDesktopCapabilities>({
- op: "capabilities",
- });
- if (current !== generation.current) return;
- mark("capabilities");
- if (result?.version !== 1) throw new Error("CHANNEL_NOT_ALLOWED");
- capsRef.current = { deviceId, value: result };
- setHostCaps({ deviceId, value: result });
- if (!result.enabled) throw new Error("DESKTOP_DISABLED");
- if (recovery.current.resuming && !result.automaticReconnect)
- throw new Error("CHANNEL_NOT_ALLOWED");
- const display =
- result.displays.find(
- (d) => d.id === (displayId ?? recovery.current.displayId),
- ) ?? result.displays[0];
- if (!display) throw new Error("DESKTOP_DISPLAY_MISSING");
- if (supportsAutoUnlock(result.platform)) {
- const firstFrame = new Promise<boolean>((resolve) => {
- unlockFrame.current = resolve;
- });
- void securityRef.current.maybeUnlock(async () => {
- if (
- !(await firstFrame) ||
- current !== generation.current ||
- !focusedRef.current ||
- !recovery.current.enabled
- )
- throw new Error("CREDENTIAL_CANCELLED");
+ const resuming = displayId ? false : recovery.current.resuming;
+ recovery.current.resuming = true;
+ const { caps: result, lease: next } =
+ await viewerSession.current!.connect({
+ displayId: displayId ?? recovery.current.displayId,
+ resume: resuming,
+ takeover,
+ isCurrent: () => current === generation.current && alive.current,
+ onCapabilities: (result) => {
+ mark("capabilities");
+ capsRef.current = { deviceId, value: result };
+ setHostCaps({ deviceId, value: result });
+ if (supportsAutoUnlock(result.platform)) {
+ const firstFrame = new Promise<boolean>((resolve) => {
+ unlockFrame.current = resolve;
+ });
+ void securityRef.current.maybeUnlock(async () => {
+ if (
+ !(await firstFrame) ||
+ current !== generation.current ||
+ !focusedRef.current ||
+ !recovery.current.enabled
+ )
+ throw new Error("CREDENTIAL_CANCELLED");
+ });
+ }
+ },
});
- }
+ const display = next.display;
recovery.current.displayId = display.id;
- const resuming = recovery.current.resuming;
- // The host may start successfully even when its reply is lost.
- recovery.current.resuming = true;
- const next = await request<RemoteDesktopLease>({
- op: "start",
- displayId: display.id,
- ...(takeover && result.connectionTakeover
- ? { takeover: true }
- : resuming
- ? { resume: true }
- : {}),
- });
- if (current !== generation.current) {
- void request({ op: "stop", lease: next.lease }).catch(() => {});
- return;
- }
mark("capture-started");
active.current = next;
receiveWindow.current = {
@@ -611,11 +633,7 @@ export default function RemoteDesktopScreen() {
// Entering remote desktop is the user's intent to control. The existing
// host permission and ownership gates still decide whether it is allowed.
if (result.canControl && wantsControl.current) {
- const control = await request<{ controlling: boolean }>({
- op: "control",
- lease: next.lease,
- enabled: true,
- });
+ const control = await viewerSession.current!.control(true);
if (current !== generation.current) return;
// Control changes keep the same session identity for in-flight replies.
next.controlling = control.controlling;
@@ -928,167 +946,13 @@ export default function RemoteDesktopScreen() {
}
const current = active.current;
if (!current || message.epoch !== current.lease) return;
- const requireMediaAttempt = () => {
- if (
- active.current !== current ||
- mediaAttempt.current !== message.attemptId
- )
- throw new Error("DESKTOP_VIDEO_STOPPED");
- };
+ if (["iceConfig", "offer", "ice"].includes(String(message.type))) {
+ void viewerMedia.handle(message).catch((cause) => {
+ if (active.current === current) fail(cause);
+ });
+ return;
+ }
switch (message.type) {
- case "iceConfig":
- if (!isDesktopAttemptId(message.attemptId)) return;
- mediaAttempt.current = message.attemptId;
- void resolveDesktopIceServers(() =>
- auth.apiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {
- baseUrl: DEVICE_LINK_API_BASE_URL,
- timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
- cache: "no-store",
- }),
- ).then((iceServers) => {
- if (
- !alive.current ||
- active.current !== current ||
- mediaAttempt.current !== message.attemptId
- )
- return;
- send({
- type: "iceConfig",
- epoch: current.lease,
- attemptId: message.attemptId,
- iceServers,
- });
- });
- break;
- case "offer":
- if (
- typeof message.sdp !== "string" ||
- message.sdp.length > 64_000 ||
- !isDesktopAttemptId(message.attemptId)
- )
- return;
- mediaAttempt.current = message.attemptId;
- pendingMediaOffers.current.set(
- current,
- (pendingMediaOffers.current.get(current) ?? 0) + 1,
- );
- void request<{ sdp: string }>(
- {
- op: "offer",
- lease: current.lease,
- sdp: message.sdp,
- ...(caps?.trickleIce ? { attemptId: message.attemptId } : {}),
- cursorOverlay: caps?.cursorOverlay === true,
- ...(caps?.videoSettings
- ? {
- settings: {
- ...videoSettingsRef.current,
- audio: Boolean(
- caps.systemAudio &&
- videoSettingsRef.current.audio &&
- !audioUnavailable.current,
- ),
- },
- }
- : {}),
- },
- requireMediaAttempt,
- )
- .then((answer) => {
- if (
- active.current === current &&
- mediaAttempt.current === message.attemptId
- )
- send({
- type: "answer",
- epoch: current.lease,
- attemptId: message.attemptId,
- sdp: answer.sdp,
- });
- })
- .catch((error) => {
- if (
- active.current === current &&
- mediaAttempt.current === message.attemptId
- ) {
- const permanent =
- /DESKTOP_(AUDIO_UNAVAILABLE|SCREEN_PERMISSION_REQUIRED|DISABLED|STOPPED|LEASE_EXPIRED)/.test(
- String(error),
- );
- send({
- type: "fallback",
- epoch: current.lease,
- attemptId: message.attemptId,
- retry: !permanent,
- });
- setStatus("compatibility");
- setSettingBusy(false);
- setSettingNotice(t("remoteDesktop.videoSettingsFailed"));
- }
- })
- .finally(() => {
- const remaining =
- (pendingMediaOffers.current.get(current) ?? 1) - 1;
- if (remaining > 0)
- pendingMediaOffers.current.set(current, remaining);
- else pendingMediaOffers.current.delete(current);
- if (alive.current) setSettingsRevision((value) => value + 1);
- });
- break;
- case "ice": {
- if (
- !caps?.trickleIce ||
- message.attemptId !== mediaAttempt.current ||
- !isDesktopAttemptId(message.attemptId) ||
- !isDesktopIceCursor(message.after) ||
- !Number.isSafeInteger(message.exchangeId)
- )
- return;
- let candidates;
- try {
- candidates = parseDesktopIceCandidates(message.candidates);
- } catch {
- return;
- }
- void request<RemoteDesktopIceReply>(
- {
- op: "ice",
- lease: current.lease,
- attemptId: message.attemptId,
- after: message.after,
- candidates,
- },
- requireMediaAttempt,
- )
- .then((value) => {
- const reply = parseDesktopIceReply(value);
- if (
- active.current === current &&
- mediaAttempt.current === message.attemptId &&
- reply.attemptId === message.attemptId
- )
- send({
- type: "ice",
- epoch: current.lease,
- exchangeId: message.exchangeId,
- ...reply,
- });
- })
- .catch(() => {
- if (
- active.current === current &&
- mediaAttempt.current === message.attemptId
- )
- send({
- type: "ice",
- epoch: current.lease,
- attemptId: message.attemptId,
- exchangeId: message.exchangeId,
- error: true,
- });
- });
- break;
- }
case "reconnecting":
if (message.attemptId === mediaAttempt.current)
setStatus("reconnecting");
@@ -1224,11 +1088,7 @@ export default function RemoteDesktopScreen() {
send({ type: "presentation", enabled: false });
}
send({ type: "control", enabled: false });
- const result = await request<{ controlling: boolean }>({
- op: "control",
- lease: current.lease,
- enabled: !current.controlling,
- });
+ const result = await viewerSession.current.control(!current.controlling);
if (active.current !== current) return;
wantsControl.current = result.controlling;
current.controlling = result.controlling;
diff --git a/apps/mobile/src/remote-desktop/geometry.ts b/apps/mobile/src/remote-desktop/geometry.ts
index ad7826952f..5fbe747851 100644
--- a/apps/mobile/src/remote-desktop/geometry.ts
+++ b/apps/mobile/src/remote-desktop/geometry.ts
@@ -1,28 +1 @@
-// This runs inside the WebView. Keep its source literal: Hermes function.toString()
-// does not preserve executable JavaScript source, even in development builds.
-/** Preserve the remote focus point when the phone rotates or the keyboard resizes it. */
-export const DESKTOP_TRANSFORM_SCRIPT = String.raw`function desktopTransform(
- vw,
- vh,
- dw,
- dh,
- zoom,
- fx,
- fy,
- fillHeight = false,
-) {
- const scale =
- (fillHeight ? vh / Math.max(1, dh) : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *
- Math.max(1, Math.min(5, zoom));
- const width = dw * scale;
- const height = dh * scale;
- const x =
- width <= vw
- ? (vw - width) / 2
- : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));
- const y =
- height <= vh
- ? (vh - height) / 2
- : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));
- return { x, y, width, height, scale };
-}`;
+export { DESKTOP_TRANSFORM_SCRIPT } from '@cindy/maker-shared/remote-desktop-scripts';
diff --git a/apps/mobile/src/remote-desktop/networkStats.ts b/apps/mobile/src/remote-desktop/networkStats.ts
index 121858e88a..7e4d822235 100644
--- a/apps/mobile/src/remote-desktop/networkStats.ts
+++ b/apps/mobile/src/remote-desktop/networkStats.ts
@@ -12,21 +12,4 @@ export function formatReceiveRate(bytes: number | null): string {
: `${Math.round(bytes / 1000)} KB/s`;
}
-// Executed in the WebView; keep literal source for Hermes.
-// https://www.w3.org/TR/webrtc-stats/ — received media bytes, selected ICE path, RTT.
-export const DESKTOP_NETWORK_STATS_SCRIPT = String.raw`function networkStats(stats, previous) {
- const rows=[...stats.values()];
- const video=rows.find(s=>s.type==='inbound-rtp'&&(s.kind==='video'||s.mediaType==='video'));
- const transport=rows.find(s=>s.type==='transport'&&s.selectedCandidatePairId);
- const pair=transport?stats.get(transport.selectedCandidatePairId):rows.find(s=>s.type==='candidate-pair'&&s.state==='succeeded'&&s.nominated);
- const local=pair&&stats.get(pair.localCandidateId),remote=pair&&stats.get(pair.remoteCandidateId);
- const direct=['host','srflx','prflx'];
- const route=local?.candidateType==='relay'||remote?.candidateType==='relay'?'relay':direct.includes(local?.candidateType)&&direct.includes(remote?.candidateType)?'direct':'video';
- const sample=video&&Number.isFinite(video.bytesReceived)&&Number.isFinite(video.timestamp)
- ?{id:video.id,path:pair?.id,bytes:video.bytesReceived,time:video.timestamp}:null;
- let bytesPerSecond=null;
- if(sample&&previous&&sample.id===previous.id&&sample.path===previous.path&&sample.time>previous.time&&sample.bytes>=previous.bytes)
- bytesPerSecond=(sample.bytes-previous.bytes)*1000/(sample.time-previous.time);
- const latencyMs=Number.isFinite(pair?.currentRoundTripTime)&&pair.currentRoundTripTime>=0?pair.currentRoundTripTime*1000:null;
- return {transport:route,bytesPerSecond,latencyMs,sample};
-}`;
+export { DESKTOP_NETWORK_STATS_SCRIPT } from '@cindy/maker-shared/remote-desktop-scripts';
diff --git a/apps/mobile/src/remote-desktop/viewerHtml.ts b/apps/mobile/src/remote-desktop/viewerHtml.ts
index 23baf5fe24..e5b5e2f841 100644
--- a/apps/mobile/src/remote-desktop/viewerHtml.ts
+++ b/apps/mobile/src/remote-desktop/viewerHtml.ts
@@ -1,342 +1,5 @@
-import { DESKTOP_TRANSFORM_SCRIPT } from "./geometry";
-import {
- DESKTOP_KEY_CODES,
- REMOTE_DESKTOP_ICE_SERVERS,
- REMOTE_DESKTOP_NETWORK,
-} from "@cindy/device-link";
-import { DESKTOP_RTC_SCRIPT } from "./viewerRtc";
-import { DESKTOP_NETWORK_STATS_SCRIPT } from "./networkStats";
-
-export function remoteDesktopViewerHtml(
- surface: string,
- foreground: string,
-): string {
- // Only theme token colors enter markup. No device names, SDP, or remote HTML.
- const color = (v: string) =>
- /^#[0-9a-f]{3,8}$/i.test(v) ? v : "transparent";
- return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; media-src blob:; connect-src 'none'"><style>
- *{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:${color(surface)};touch-action:none;overscroll-behavior:none}#stage{position:absolute;inset:0;overflow:hidden;z-index:0}video,img{position:absolute;max-width:none;pointer-events:none;transform-origin:0 0}video{display:none;z-index:0}#cursor{position:absolute;z-index:3;width:18px;height:18px;border:2px solid ${color(foreground)};border-radius:50%;pointer-events:none;display:none;transform:translate(-50%,-50%)}
- #cursor-image{position:absolute;inset:0;width:100%;height:100%}
- #stage,#stage *{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-user-drag:none}
- video,img{border:0;outline:0}#image{z-index:1}img:not([src]){visibility:hidden}
- :root{--surface:${color(surface)};--foreground:${color(foreground)}}
- #keyboard-input{position:absolute;left:0;bottom:0;width:1px;height:1px;opacity:.01;font-size:16px;pointer-events:none;border:0;padding:0;resize:none}
- #mouse-buttons{position:absolute;inset:0;pointer-events:none;display:none;color:var(--foreground);opacity:.85}
- #mouse-buttons button,#mouse-wheel{pointer-events:auto;touch-action:none;user-select:none;-webkit-user-select:none;color:inherit;background:color-mix(in srgb,var(--surface) 90%,var(--foreground));border:1px solid color-mix(in srgb,var(--foreground) 18%,transparent)}
- .mouse-button{position:absolute;width:56px;height:56px;border-radius:9999px;padding:14px}
- .mouse-button svg{width:100%;height:100%;pointer-events:none}
- .mouse-button[aria-pressed="true"]{background:var(--foreground)!important;color:var(--surface)!important}
- #mouse-left{left:calc(50% - 96px);bottom:16px}#mouse-right{left:calc(50% + 40px);bottom:16px}
- #mouse-wheel{position:absolute;right:12px;bottom:80px;width:56px;height:120px;padding:12px 0;border-radius:9999px;display:flex;flex-direction:column;align-items:center;justify-content:space-between;font-size:20px}
- #mouse-wheel:active{background:var(--foreground);color:var(--surface)}
- #mouse-wheel>*{pointer-events:none}
- #mouse-wheel-grip{width:20px;height:34px}
- @media(max-height:400px){#mouse-wheel{bottom:12px}}
- </style></head><body><div id="stage"><img id="image" alt=""><video id="video" autoplay muted playsinline></video><div id="cursor"><img id="cursor-image" alt=""></div></div>
- <div id="mouse-buttons">
- ${(["left", "right"] as const).map((button) => `<button type="button" id="mouse-${button}" class="mouse-button" aria-pressed="false"><svg viewBox="0 0 24 32" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="2" width="18" height="28" rx="9"/><path d="M12 2v12M3 14h18"/><path d="${button === "left" ? "M11 3C6 3 4 6 4 10v3h7Z" : "M13 3c5 0 7 3 7 7v3h-7Z"}" fill="currentColor" stroke="none"/></svg></button>`).join("")}
- <button type="button" id="mouse-wheel"><span aria-hidden="true">▴</span><svg id="mouse-wheel-grip" viewBox="0 0 20 34" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="1" y="1" width="18" height="32" rx="8"/><path d="M3 10h14M2 17h16M3 24h14"/></svg><span aria-hidden="true">▾</span></button>
- </div><textarea id="keyboard-input" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" aria-label="Keyboard"></textarea><script>
- const transform=${DESKTOP_TRANSFORM_SCRIPT};
- const networkStats=${DESKTOP_NETWORK_STATS_SCRIPT};
- const net=${JSON.stringify(REMOTE_DESKTOP_NETWORK)},iceServers=${JSON.stringify(REMOTE_DESKTOP_ICE_SERVERS)};
- const validKeys=new Set(${JSON.stringify(DESKTOP_KEY_CODES)});
- ${VIEWER_SCRIPT}
- </script></body></html>`;
+import { remoteDesktopViewerHtml as createHtml } from '@cindy/maker-shared/remote-desktop-mobile';
+import { DESKTOP_KEY_CODES, REMOTE_DESKTOP_NETWORK, REMOTE_DESKTOP_ICE_SERVERS } from '@cindy/device-link';
+export function remoteDesktopViewerHtml(surface: string, foreground: string): string {
+ return createHtml(surface, foreground, {net: REMOTE_DESKTOP_NETWORK, iceServers: REMOTE_DESKTOP_ICE_SERVERS, keyCodes: DESKTOP_KEY_CODES});
}
-
-const VIEWER_SCRIPT = String.raw`
-(() => {
- const stage=document.getElementById('stage'), image=document.getElementById('image'), video=document.getElementById('video'), cursor=document.getElementById('cursor');
- let dw=1920,dh=1080,zoom=1,fx=.5,fy=.5,mode='pointer',control=false,pc=null,dc=null,seq=0,generation=0,epoch=null,gestureFrame=null;
- let remoteCursor=null,lastLocalMove=0,localCursorAwake=false;
- let touchCursor=null,touchCursorTimer=null,touchCursorVisible=false;
- const reducedMotion=matchMedia("(prefers-reduced-motion: reduce)");
- const cursorImage=document.getElementById('cursor-image');
- let pending=[],sending=false,cx=.5,cy=.5,drag=false,start=null,last=null,multi=null,hold=null,moved=false;
- const pointers=new Map();
- const mouseButtons=document.getElementById('mouse-buttons'), wheel=document.getElementById('mouse-wheel'), wheelGrip=document.getElementById('mouse-wheel-grip');
- const keyboardInput=document.getElementById('keyboard-input');
- let keyboardEnabled=false,composing=false;
- const keyboardSentinel='\u200b';
- function resetKeyboard(){keyboardInput.value=keyboardSentinel;keyboardInput.setSelectionRange(1,1);}
- function showKeyboard(enabled){
- keyboardEnabled=enabled&&control;
- if(!keyboardEnabled){composing=false;resetKeyboard();keyboardInput.blur();return;}
- if(composing)return;
- // Keep focus inside the native evaluateJavaScript call; WebKit can reject
- // keyboard presentation after requestAnimationFrame loses user activation.
- keyboardInput.blur();resetKeyboard();keyboardInput.focus({preventScroll:true});
- }
- function keyboardKey(code){if(!keyboardEnabled||!control)return;queue({kind:'key',code,down:true});queue({kind:'key',code,down:false});flush();}
- function commitKeyboard(){if(!keyboardEnabled||!control||composing)return;const text=keyboardInput.value.replace(keyboardSentinel,'');if(text){for(let i=0;i<text.length;i+=4096)queue({kind:'text',text:text.slice(i,i+4096)});flush();}resetKeyboard();}
- keyboardInput.addEventListener('compositionstart',()=>{composing=true;});
- keyboardInput.addEventListener('compositionend',()=>{composing=false;commitKeyboard();});
- keyboardInput.addEventListener('input',e=>{if(!e.isComposing)commitKeyboard();});
- keyboardInput.addEventListener('beforeinput',e=>{
- if(composing||e.isComposing)return;
- if(e.inputType==='deleteContentBackward'){e.preventDefault();keyboardKey('Backspace');resetKeyboard();}
- else if(e.inputType==='insertLineBreak'||e.inputType==='insertParagraph'){e.preventDefault();keyboardKey('Enter');resetKeyboard();}
- });
- const heldMouse=new Map();
- let showMouseButtons=false,wheelY=null;
- function resetWheel(){wheelY=null;wheelGrip.style.transform='translateY(0px)';}
- let statsTimer=null,statsSample=null;
- const post=(message)=>window.ReactNativeWebView.postMessage(JSON.stringify({...message,epoch}));
- const clamp=(v)=>Math.max(0,Math.min(1,v));
- let fillHeight=false;
- let panAnimation=null,viewportRightInset=0,viewportLeftInset=0,viewportBottomInset=0,keyboardViewportInset=0;
- let cursorNeedsEntry=true,manualViewMoved=false,followRest=null;
- // Insets guide centering and pan limits without clipping the full-screen
- // video surface or adding an opaque strip beside the Dynamic Island.
- const viewportLeft=()=>fillHeight?viewportLeftInset:0;
- const viewportWidth=()=>Math.max(1,stage.clientWidth-viewportLeft()-(fillHeight?viewportRightInset:0));
- const layout=()=>{const r=transform(viewportWidth(),stage.clientHeight,dw,dh,zoom,fx,fy,fillHeight);
- return {...r,x:(viewportLeft()+viewportWidth()/2)-fx*r.width,y:stage.clientHeight/2-fy*r.height};};
- function panBounds(r){const vw=viewportWidth(),vh=stage.clientHeight;
- // Grow extra resting travel continuously from zero at fit to 180 screen
- // points at maximum zoom. Never count the unused space of a fitting axis.
- const clearance=180*(Math.max(1,Math.min(5,zoom))-1)/4;
- const axis=(viewport,content)=>content<=viewport
- ? {min:(viewport-content)/2-clearance,max:(viewport-content)/2+clearance}
- : {min:viewport-content-clearance,max:clearance};
- const x=axis(vw,r.width),y=axis(vh,r.height);
- const bounds={minX:viewportLeft()+x.min,maxX:viewportLeft()+x.max,minY:y.min,maxY:y.max};
- // A camera position required to expose the cursor is a valid resting point,
- // not elastic overshoot. Preserve it across the next pan/pinch handoff.
- if(followRest){const restX=viewportLeft()+vw/2-followRest.fx*r.width,restY=vh/2-followRest.fy*r.height;
- const weight=followRest.zoom>1?clamp((zoom-1)/(followRest.zoom-1)):1;
- bounds.minX+=Math.min(0,restX-bounds.minX)*weight;bounds.maxX+=Math.max(0,restX-bounds.maxX)*weight;
- bounds.minY+=Math.min(0,restY-bounds.minY)*weight;bounds.maxY+=Math.max(0,restY-bounds.maxY)*weight;}
- return bounds;}
- const bounded=(v,min,max)=>Math.max(min,Math.min(max,v));
- // Convert displayed overshoot back to finger travel before the next delta,
- // so reversing direction unwinds smoothly without an edge jump.
- function rubber(v,min,max,inverse=false){const edge=bounded(v,min,max),d=v-edge;
- const reach=40+10*(Math.max(1,Math.min(5,zoom))-1);
- return edge+Math.sign(d)*(inverse?reach*Math.abs(d)/Math.max(1,reach-Math.abs(d)):reach*Math.abs(d)/(reach+Math.abs(d)));}
- function place(x,y,r){fx=((viewportLeft()+viewportWidth()/2)-x)/r.width;fy=(stage.clientHeight/2-y)/r.height;}
- function cursorViewport(){
- const hotX=remoteCursor?.hotX??9,hotY=remoteCursor?.hotY??9;
- const w=remoteCursor?.width??18,h=remoteCursor?.height??18;
- const left=viewportLeft(),right=left+viewportWidth(),bottom=Math.max(1,stage.clientHeight-viewportBottomInset);
- // Keep the entire cursor, including its hotspot offset, clear of chrome.
- const minX=Math.min(right-1,left+8+hotX),minY=Math.min(bottom-1,8+hotY);
- return {minX,maxX:Math.max(minX,right-8-(w-hotX)),minY,maxY:Math.max(minY,bottom-8-(h-hotY))};
- }
- function moveTouchpad(dx,dy){
- stopPanAnimation();const r=layout(),v=cursorViewport();
- if(cursorNeedsEntry){
- // Re-enter at the nearest visible edge; do not pull a manually positioned
- // desktop back to the old off-screen cursor before applying this movement.
- cx=clamp((bounded(r.x+cx*r.width,v.minX,v.maxX)-r.x)/r.width);
- cy=clamp((bounded(r.y+cy*r.height,v.minY,v.maxY)-r.y)/r.height);
- cursorNeedsEntry=false;
- }
- cx=clamp(cx+dx/r.width);cy=clamp(cy+dy/r.height);
- const x=r.x+cx*r.width,y=r.y+cy*r.height;
- if(zoom>1||r.width>viewportWidth()||r.height>stage.clientHeight-viewportBottomInset){
- place(r.x+bounded(x,v.minX,v.maxX)-x,r.y+bounded(y,v.minY,v.maxY)-y,r);
- followRest={fx,fy,zoom};
- }
- manualViewMoved=false;
- }
- function stopPanAnimation(){if(panAnimation!==null)cancelAnimationFrame(panAnimation);panAnimation=null;}
- function settlePan(){stopPanAnimation();
- const r=layout(),b=panBounds(r),x=bounded(r.x,b.minX,b.maxX),y=bounded(r.y,b.minY,b.maxY);
- if(x===r.x&&y===r.y)return;
- if(reducedMotion.matches){place(x,y,r);render();return;}
- const started=performance.now();
- const tick=now=>{const t=Math.min(1,(now-started)/280),ease=1-Math.pow(1-t,3);
- place(r.x+(x-r.x)*ease,r.y+(y-r.y)*ease,r);render();
- panAnimation=t<1?requestAnimationFrame(tick):null;};panAnimation=requestAnimationFrame(tick);
- }
- function render(){const r=layout();
- const touchFeedback=control&&mode==='touch'&&touchCursorVisible;
- const cursorX=mode==='touch'&&touchCursor?touchCursor.x:cx;
- const cursorY=mode==='touch'&&touchCursor?touchCursor.y:cy;
- cursor.style.transition=mode==='touch'&&!touchFeedback&&!reducedMotion.matches?'opacity 120ms ease-out':'none';for(const el of [image,video]){el.style.width=r.width+'px';el.style.height=r.height+'px';el.style.left=r.x+'px';el.style.top=r.y+'px';}if(remoteCursor){
- cursor.style.width=remoteCursor.width+'px';cursor.style.height=remoteCursor.height+'px';
- cursor.style.border='0';cursor.style.borderRadius='0';cursor.style.transform='none';
- cursor.style.left=(r.x+cursorX*r.width-remoteCursor.hotX)+'px';cursor.style.top=(r.y+cursorY*r.height-remoteCursor.hotY)+'px';
- cursor.style.display='block';
- cursor.style.opacity=(mode==='touch'?touchFeedback:(remoteCursor.visible||(control&&mode==='pointer'&&localCursorAwake)))?'1':'0';
- }else{
- cursor.style.opacity=(mode==='touch'?!touchFeedback:false)?'0':'1';cursor.style.width='18px';cursor.style.height='18px';cursor.style.border='2px solid var(--foreground)';
- cursor.style.borderRadius='50%';cursor.style.transform='translate(-50%,-50%)';
- cursor.style.left=(r.x+cursorX*r.width)+'px';cursor.style.top=(r.y+cursorY*r.height)+'px';
- cursor.style.display=control&&(mode==='pointer'||mode==='touch')?'block':'none';
- }}
- // Literal source is required: Hermes function.toString() yields bytecode.
- function validCursor(v){
- return !!v && typeof v==='object' && typeof v.visible==='boolean' &&
- [v.x,v.y,v.width,v.height,v.hotX,v.hotY].every(Number.isFinite) &&
- v.x>=0&&v.x<=1&&v.y>=0&&v.y<=1&&v.width>0&&v.width<=256&&v.height>0&&v.height<=256&&
- v.hotX>=0&&v.hotX<=v.width&&v.hotY>=0&&v.hotY<=v.height&&
- typeof v.png==='string'&&v.png.length<=65536&&/^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png);
- }
- function receiveCursor(value){
- if(value===null){if(remoteCursor){remoteCursor={...remoteCursor,visible:false};render();}return;}
- if(!validCursor(value))return;
- if(!remoteCursor||remoteCursor.png!==value.png)cursorImage.src='data:image/png;base64,'+value.png;
- // Keep delayed host coordinates from pulling the local touchpad backwards.
- if(!remoteCursor||!control||mode!=='pointer'||(!pointers.size&&performance.now()-lastLocalMove>200)){
- cx=value.x;cy=value.y;
- }
- if(value.visible)localCursorAwake=false;
- remoteCursor=value;render();
- }
- function resetCursor(){clearTimeout(touchCursorTimer);touchCursorVisible=false;touchCursor=null;localCursorAwake=false;remoteCursor=null;cursorImage.removeAttribute('src');render();}
- function queue(event){if(!control)return;
- // Remote visibility can remain hidden after synthetic mouse movement. Wake
- // the local touchpad cursor until the host reports a visible cursor again.
- if(event.kind==='move'&&mode==='pointer')localCursorAwake=true;
- if(event.kind==='key'||event.kind==='text'){localCursorAwake=false;render();}
- if(event.kind==='move'||event.kind==='button')lastLocalMove=performance.now();const tail=pending[pending.length-1];
- if(event.kind==='move'&&tail?.kind==='move')pending[pending.length-1]=event;
- // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the
- // accumulated distance so a delayed ACK cannot replay a large scroll backlog.
- else if(event.kind==='scroll'&&tail?.kind==='scroll'){tail.dx=Math.max(-2000,Math.min(2000,tail.dx+event.dx));tail.dy=Math.max(-2000,Math.min(2000,tail.dy+event.dy));}
- else pending.push(event);
- if(pending.length>64){pending=[{kind:'release'}];control=false;post({type:'inputOverflow'});}}
- function flush(){if(!pending.length||sending)return;const events=pending.splice(0,64),sequence=++seq;if(pc?.connectionState==='connected'&&dc&&dc.readyState==='open'&&dc.bufferedAmount<16384){dc.send(JSON.stringify({sequence,events}));}else{sending=true;post({type:'input',sequence,events});}}
- setInterval(()=>{
- // Hold displacement controls speed, even without further pointer moves.
- // Skip missed ticks while awaiting ACK instead of building a scroll backlog.
- if(wheelY?.moved&&!sending){const offset=Math.max(-24,Math.min(24,wheelY.y-wheelY.start));if(Math.abs(offset)>4)scrollMouse(Math.sign(offset)*(Math.abs(offset)-4)*1.5);}
- flush();
- },33);
- function release(){clearTimeout(hold);if(gestureFrame!==null)cancelAnimationFrame(gestureFrame);gestureFrame=null;if(control){queue({kind:'release'});flush();}heldMouse.clear();resetWheel();updateMouseButtons();drag=false;pointers.clear();start=null;last=null;multi=null;}
- function updateMouseButtons(){mouseButtons.style.display=showMouseButtons&&control?'block':'none';for(const [name,button] of [['left',0],['right',2]])document.getElementById('mouse-'+name).setAttribute('aria-pressed',String(heldMouse.has(button)));}
- for(const [name,button] of [['left',0],['right',2]]){
- const el=document.getElementById('mouse-'+name);
- el.addEventListener('pointerdown',e=>{e.preventDefault();if(!control||!showMouseButtons||heldMouse.has(button))return;clearTimeout(hold);el.setPointerCapture(e.pointerId);heldMouse.set(button,e.pointerId);queue({kind:'button',button,down:true,x:cx,y:cy});flush();updateMouseButtons();});
- const up=e=>{e.preventDefault();if(heldMouse.get(button)!==e.pointerId)return;heldMouse.delete(button);queue({kind:'button',button,down:false,x:cx,y:cy});flush();updateMouseButtons();};
- el.addEventListener('pointerup',up);el.addEventListener('pointercancel',up);el.addEventListener('lostpointercapture',up);
- el.addEventListener('click',e=>{if(e.detail===0&&control&&showMouseButtons){click(button);flush();}});
- }
- const scrollMouse=dy=>{if(control&&showMouseButtons&&Number.isFinite(dy)){queue({kind:'scroll',dx:0,dy:Math.max(-2000,Math.min(2000,dy))});}};
- wheel.addEventListener('pointerdown',e=>{e.preventDefault();if(!control||!showMouseButtons||wheelY)return;wheel.setPointerCapture(e.pointerId);wheelY={id:e.pointerId,y:e.clientY,start:e.clientY,moved:false};});
- // A small dead zone preserves middle clicks; displacement drives the timer.
- wheel.addEventListener('pointermove',e=>{if(!wheelY||wheelY.id!==e.pointerId)return;e.preventDefault();wheelGrip.style.transform='translateY('+Math.max(-24,Math.min(24,e.clientY-wheelY.start))+'px)';wheelY.y=e.clientY;if(Math.abs(e.clientY-wheelY.start)>4)wheelY.moved=true;});
- wheel.addEventListener('pointerup',e=>{if(!wheelY||wheelY.id!==e.pointerId)return;e.preventDefault();if(!wheelY.moved&&control&&showMouseButtons){click(1);flush();}resetWheel();});
- const cancelWheel=e=>{if(wheelY?.id===e.pointerId)resetWheel();};
- wheel.addEventListener('pointercancel',cancelWheel);wheel.addEventListener('lostpointercapture',cancelWheel);
- wheel.addEventListener('click',e=>{if(e.detail===0&&control&&showMouseButtons){click(1);flush();}});
- wheel.addEventListener('keydown',e=>{if(e.key==='ArrowUp'||e.key==='ArrowDown'){e.preventDefault();scrollMouse(e.key==='ArrowUp'?-120:120);}});
- function insideDesktop(p){const r=layout();return p.x>=r.x&&p.x<=r.x+r.width&&p.y>=r.y&&p.y<=r.y+r.height;}
- function point(p){const r=layout();return{x:clamp((p.x-r.x)/r.width),y:clamp((p.y-r.y)/r.height)};}
- function click(button=0){if(control&&mode==='touch'){clearTimeout(touchCursorTimer);touchCursor={x:cx,y:cy};touchCursorVisible=true;render();touchCursorTimer=setTimeout(()=>{touchCursorVisible=false;render();},450);}queue({kind:'button',button,down:true,x:cx,y:cy});queue({kind:'button',button,down:false,x:cx,y:cy});}
- function pan(dx,dy){manualViewMoved=true;cursorNeedsEntry=true;stopPanAnimation();const r=layout(),b=panBounds(r);place(rubber(rubber(r.x,b.minX,b.maxX,true)+dx,b.minX,b.maxX),rubber(rubber(r.y,b.minY,b.maxY,true)+dy,b.minY,b.maxY),r);render();}
- function pair(){const [a,b]=[...pointers.values()];return{x:(a.x+b.x)/2,y:(a.y+b.y)/2,d:Math.hypot(a.x-b.x,a.y-b.y)};}
- function movePair(){gestureFrame=null;if(pointers.size<2||!multi)return;const next=pair(),span=Math.abs(next.d-multi.d),travel=Math.hypot(next.x-multi.x,next.y-multi.y);
- if(multi.kind!=='pinch'){
- const pinchSlop=Math.max(6,Math.min(12,multi.d*.04));
- if(span>=pinchSlop&&span>travel*.65){
- // A parallel scroll may deliver its two pointer updates in different
- // frames. Confirm separation briefly before taking over as a pinch.
- if(!multi.candidate)multi.candidate={at:Date.now(),d:next.d,zoom,anchor:point(next)};
- if(Date.now()-multi.candidate.at>=40){
- if(multi.kind==='scroll'){multi.d=multi.candidate.d;multi.zoom=multi.candidate.zoom;multi.anchor=multi.candidate.anchor;}
- multi.kind='pinch';multi.candidate=null;
- }else{gestureFrame=requestAnimationFrame(movePair);return;}
- }else{multi.candidate=null;if(!multi.kind&&travel>8&&travel>span)multi.kind='scroll';}
- }
- if(multi.kind==='pinch'){manualViewMoved=true;cursorNeedsEntry=true;zoom=Math.max(1,Math.min(5,multi.zoom*next.d/Math.max(1,multi.d)));const r=layout();fx=multi.anchor.x+((viewportLeft()+viewportWidth()/2)-next.x)/r.width;fy=multi.anchor.y+(stage.clientHeight/2-next.y)/r.height;const moved=layout(),b=panBounds(moved);place(rubber(moved.x,b.minX,b.maxX),rubber(moved.y,b.minY,b.maxY),moved);}
- else if(multi.kind==='scroll'){const dx=next.x-multi.lastX,dy=next.y-multi.lastY;if(control&&mode!=='pan')queue({kind:'scroll',dx:Math.max(-2000,Math.min(2000,-dx)),dy:Math.max(-2000,Math.min(2000,-dy))});else pan(dx,dy);}
- if(multi.kind){multi.lastX=next.x;multi.lastY=next.y;}render();
- }
- stage.addEventListener('pointerdown',e=>{
- e.preventDefault();stopPanAnimation();stage.setPointerCapture(e.pointerId);pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
- if(pointers.size===1){cursorNeedsEntry=true;start={x:e.clientX,y:e.clientY};last=start;moved=false;
- hold=setTimeout(()=>{if(control&&mode!=='pan'&&!moved&&pointers.size===1&&!heldMouse.size&&(mode!=='touch'||insideDesktop(start))){if(mode==='touch'){const p=point(start);cx=p.x;cy=p.y;}queue({kind:'button',button:0,down:true,x:cx,y:cy});drag=true;}},400);
- }else {clearTimeout(hold);if(drag)queue({kind:'release'});drag=false;start=null;const p=pair();multi={...p,lastX:p.x,lastY:p.y,zoom,anchor:point(p),kind:null};}
- });
- stage.addEventListener('pointermove',e=>{
- if(!pointers.has(e.pointerId))return;e.preventDefault();pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
- if(pointers.size>=2){if(gestureFrame===null)gestureFrame=requestAnimationFrame(movePair);return;}
- if(!start||!last)return;const now={x:e.clientX,y:e.clientY},dx=now.x-last.x,dy=now.y-last.y;last=now;
- if(Math.hypot(now.x-start.x,now.y-start.y)>6){moved=true;clearTimeout(hold);}
- if(!control||mode==='pan'||(mode==='touch'&&!drag&&!heldMouse.size)){pan(dx,dy);return;}
- if(mode==='pointer'){moveTouchpad(dx,dy);}else{const p=point(now);cx=p.x;cy=p.y;}
- queue({kind:'move',x:cx,y:cy});render();
- });
- function up(e){if(!pointers.has(e.pointerId))return;clearTimeout(hold);
- if(pointers.size>=2&&multi){
- pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
- if(gestureFrame!==null)cancelAnimationFrame(gestureFrame);
- movePair();
- if(gestureFrame!==null)cancelAnimationFrame(gestureFrame);gestureFrame=null;
- }
- pointers.delete(e.pointerId);
- if(drag){queue({kind:'button',button:0,down:false,x:cx,y:cy});drag=false;}
- else if(start&&!moved&&control&&mode!=='pan'&&!heldMouse.size&&e.type==='pointerup'&&(mode!=='touch'||insideDesktop({x:e.clientX,y:e.clientY}))){if(mode==='touch'){const p=point({x:e.clientX,y:e.clientY});cx=p.x;cy=p.y;}click();}
- start=null;last=null;multi=null;render();if(!pointers.size&&manualViewMoved)settlePan();
- }
- stage.addEventListener('pointerup',up);stage.addEventListener('pointercancel',()=>{release();settlePan();});
- document.addEventListener('contextmenu',e=>e.preventDefault());
- // Scope selection suppression to the desktop surface, preserving the hidden
- // textarea's native keyboard/IME editing and programmatic selection.
- stage.addEventListener('selectstart',e=>e.preventDefault());
- stage.addEventListener('dragstart',e=>e.preventDefault());
- const normalizedKey=code=>/^(Shift|Control|Alt|Meta)Right$/.test(code)?code.replace(/Right$/,'Left'):code;
- document.addEventListener('keydown',e=>{if(control&&validKeys.has(normalizedKey(e.code))){e.preventDefault();queue({kind:'key',code:normalizedKey(e.code),down:true});}});
- document.addEventListener('keyup',e=>{if(control&&validKeys.has(normalizedKey(e.code))){e.preventDefault();queue({kind:'key',code:normalizedKey(e.code),down:false});}});
- window.addEventListener('blur',()=>{release();settlePan();});new ResizeObserver(()=>{release();settlePan();render();}).observe(stage);
- // Keep one bounded frame in this document only; never persist desktop pixels.
- // Snapshot before detaching the track. A JPEG fallback already lives in image.
- function retainFrame(){
- if(!videoPresented||video.style.display!=='block'||video.readyState<2||!video.videoWidth||!video.videoHeight)return;
- const canvas=document.createElement('canvas');
- try{const scale=Math.min(1,1280/Math.max(video.videoWidth,video.videoHeight));canvas.width=Math.max(1,Math.round(video.videoWidth*scale));canvas.height=Math.max(1,Math.round(video.videoHeight*scale));const context=canvas.getContext('2d');if(context){context.drawImage(video,0,0,canvas.width,canvas.height);image.src=canvas.toDataURL('image/jpeg',.7);}}catch{/* Keep the previous compatibility frame if WebKit cannot read video. */}finally{canvas.width=0;canvas.height=0;}
- }
- ${DESKTOP_RTC_SCRIPT}
- function reportPresentation(){post({type:'presentation',active:video.webkitPresentationMode==='picture-in-picture'||document.pictureInPictureElement===video});}
- video.addEventListener('webkitpresentationmodechanged',reportPresentation);
- video.addEventListener('enterpictureinpicture',reportPresentation);
- video.addEventListener('leavepictureinpicture',reportPresentation);
- function receive(event){let message;try{message=JSON.parse(event.data);}catch{return;}
- switch(message.type){
- case 'presentation':
- try {
- if(message.enabled){
- release();showKeyboard(false);
- if(video.webkitSupportsPresentationMode?.('picture-in-picture'))video.webkitSetPresentationMode('picture-in-picture');
- else if(video.requestPictureInPicture)video.requestPictureInPicture().catch(()=>post({type:'presentationFailed'}));
- else post({type:'presentationFailed'});
- }else if(video.webkitSetPresentationMode)video.webkitSetPresentationMode('inline');
- else if(document.pictureInPictureElement)document.exitPictureInPicture().catch(()=>{});
- }catch{post({type:'presentationFailed'});}break;
- case 'videoSettings':video.muted=!message.audio;retries=0;connect();break;
- case 'keyboard':showKeyboard(message.enabled===true);break;
- case 'resume':if(video.srcObject)video.play().catch(()=>{});break;
- case 'releaseInput':release();break;
- case 'theme':if(/^#[0-9a-f]{3,8}$/i.test(message.surface)){document.body.style.background=message.surface;document.documentElement.style.background=message.surface;document.documentElement.style.setProperty('--surface',message.surface);}if(/^#[0-9a-f]{3,8}$/i.test(message.foreground)){cursor.style.borderColor=message.foreground;document.documentElement.style.setProperty('--foreground',message.foreground);}break;
- case 'mouseButtons':if(Number.isFinite(message.bottomInset))viewportBottomInset=Math.max(0,Math.min(stage.clientHeight-1,message.bottomInset));if(Number.isFinite(message.leftInset)){const left=Math.max(0,Math.min(stage.clientWidth-1,message.leftInset));if(left!==viewportLeftInset){viewportLeftInset=left;settlePan();render();}}if(Number.isFinite(message.rightInset)){const inset=Math.max(0,Math.min(stage.clientWidth-1,message.rightInset));if(inset!==viewportRightInset){viewportRightInset=inset;settlePan();render();}}const keyboardInset=fillHeight&&message.keyboardOpen===true?viewportBottomInset:0;
- if(keyboardInset!==keyboardViewportInset){
- const wasOpen=keyboardViewportInset>0;keyboardViewportInset=keyboardInset;
- if(fillHeight&&(keyboardInset>0||wasOpen)){
- stopPanAnimation();const r=layout(),v=cursorViewport();
- place((v.minX+v.maxX)/2-cx*r.width,(v.minY+v.maxY)/2-cy*r.height,r);
- followRest={fx,fy,zoom};cursorNeedsEntry=false;manualViewMoved=false;render();
- }
- }
- if(!message.enabled){for(const button of heldMouse.keys())queue({kind:'button',button,down:false,x:cx,y:cy});heldMouse.clear();resetWheel();flush();}for(const [edge,value] of [['bottom',message.bottomInset],['right',message.rightInset]])if(Number.isFinite(value)&&value>=0&&value<=4096)mouseButtons.style[edge]=value+'px';showMouseButtons=message.enabled===true;for(const name of ['left','right','wheel'])if(typeof message.labels?.[name]==='string')document.getElementById('mouse-'+name).setAttribute('aria-label',message.labels[name]);updateMouseButtons();break;
- case 'init':followRest=null;cursorNeedsEntry=true;stopPanAnimation();resetCursor();control=false;release();pending=[];sending=false;seq=0;epoch=message.epoch;dw=message.width;dh=message.height;fillHeight=message.fillHeight===true;video.muted=!message.audio;trickleIce=message.trickleIce===true;retries=0;render();connect();break;
- case 'viewport':fillHeight=message.fillHeight===true;release();render();break;
- case 'answer':if(message.epoch===epoch)void receiveAnswer(message);break;
- case 'iceConfig':if(message.epoch===epoch)void receiveIceConfig(message);break;
- case 'ice':if(message.epoch===epoch)void receiveIce(message);break;
- case 'fallback':if(message.epoch===epoch&&message.attemptId===attemptId)failRtc('host',message.retry!==false);break;
- case 'frame':{if('cursor' in message)receiveCursor(message.cursor);else resetCursor();const frameEpoch=epoch;image.onload=()=>{if(epoch===frameEpoch)post({type:'framePresented'});};image.src='data:image/jpeg;base64,'+message.jpeg;break;}
- case 'control':release();control=message.enabled;if(!control)showKeyboard(false);pending=[];updateMouseButtons();render();break;
- case 'mode':release();if(message.mode!=='pointer')followRest=null;settlePan();clearTimeout(touchCursorTimer);touchCursorVisible=false;mode=message.mode;render();break;
- case 'fit':followRest=null;cursorNeedsEntry=true;manualViewMoved=false;stopPanAnimation();zoom=1;fx=.5;fy=.5;render();break;
- case 'rightClick':click(2);break;
- case 'events':for(const e of message.events)queue(e);flush();break;
- case 'ack':if(message.epoch===epoch&&message.sequence===seq)sending=false;break;
- case 'stop':showKeyboard(false);control=false;release();pending=[];sending=false;epoch=null;closeRtc(message.preserveFrame===true);updateMouseButtons();render();break;
- }
- }
- window.addEventListener('message',receive);document.addEventListener('message',receive);render();post({type:'ready'});
-})();`;
diff --git a/apps/mobile/src/remote-desktop/viewerRtc.ts b/apps/mobile/src/remote-desktop/viewerRtc.ts
index 3b3c828e2a..a94b7b80b4 100644
--- a/apps/mobile/src/remote-desktop/viewerRtc.ts
+++ b/apps/mobile/src/remote-desktop/viewerRtc.ts
@@ -1,160 +1 @@
-/** Static WebView code: stays independent of Hermes function serialization.
- * A media attempt owns its timers/candidates. The native screen retains the human lease.
- */
-export const DESKTOP_RTC_SCRIPT = String.raw`
- let trickleIce=false,attemptId=null,retries=0,exchangeId=0;
- let configPending=false;
- let videoPresented=false,videoFrameCallback=null,videoPaintCallback=null;
- function cancelVideoHandoff(){
- if(videoFrameCallback!==null)video.cancelVideoFrameCallback?.(videoFrameCallback);
- if(videoPaintCallback!==null)cancelAnimationFrame(videoPaintCallback);
- videoFrameCallback=videoPaintCallback=null;
- }
- function revealVideo(g){
- post({type:'videoFrameReady',attemptId});
- // Keep the JPEG decoded and painted as a backing layer. Promote the video
- // only after its first frame; removing the image exposes WebKit repaint gaps.
- videoPaintCallback=requestAnimationFrame(()=>{
- if(g!==generation)return;
- videoPaintCallback=requestAnimationFrame(()=>{
- if(g!==generation)return;
- videoPaintCallback=null;videoPresented=true;video.style.zIndex='2';
- post({type:'streaming',attemptId});
- post({type:'pipCapability',supported:!!(video.webkitSupportsPresentationMode?.('picture-in-picture')||document.pictureInPictureEnabled)});
- });
- });
- }
- function waitForVideoFrame(g){
- if(g!==generation)return;
- if(video.readyState>=2&&video.videoWidth>0&&video.videoHeight>0){revealVideo(g);return;}
- videoPaintCallback=requestAnimationFrame(()=>waitForVideoFrame(g));
- }
- let retryTimer=null,deadlineTimer=null,disconnectTimer=null,stableTimer=null,iceTimer=null,gatherTimer=null,gatherDone=null;
- let localCandidates=[],localAck=0,remoteAfter=0,icePending=null,remoteSeen=new Set(),exchangeUntil=0,remoteComplete=false;
- function clearRtcTimers(){
- for(const timer of [retryTimer,deadlineTimer,disconnectTimer,stableTimer,iceTimer,gatherTimer])clearTimeout(timer);
- retryTimer=deadlineTimer=disconnectTimer=stableTimer=iceTimer=gatherTimer=null;
- if(gatherDone){gatherDone();gatherDone=null;}
- }
- function closeRtc(preserveFrame=true){
- configPending=false;
- if(preserveFrame)retainFrame();generation++;clearRtcTimers();
- cancelVideoHandoff();videoPresented=false;
- localCandidates=[];localAck=remoteAfter=0;icePending=null;remoteSeen=new Set();attemptId=null;
- clearInterval(statsTimer);statsTimer=null;statsSample=null;
- if(dc)dc.close();if(pc)pc.close();pc=null;dc=null;
- video.onplaying=null;video.srcObject=null;video.style.display='none';video.style.zIndex='0';image.style.display='block';
- if(!preserveFrame)image.removeAttribute('src');
- }
- function failRtc(reason,canRetry=true){
- const failedAttempt=attemptId;
- release();closeRtc();post({type:'fallback',attemptId:failedAttempt,reason});
- if(canRetry&&epoch&&retries<net.retryMs.length){
- const delay=net.retryMs[retries++];
- retryTimer=setTimeout(()=>{retryTimer=null;if(epoch)connect();},delay);
- }
- }
- function pollIce(){
- if(!pc||!trickleIce||!pc.remoteDescription||icePending||Date.now()>=exchangeUntil)return;
- const candidates=localCandidates.slice(localAck,localAck+net.batchSize);
- icePending={after:remoteAfter,sent:candidates.length,exchangeId:++exchangeId};
- post({type:'ice',attemptId,candidates,after:remoteAfter,exchangeId});
- iceTimer=setTimeout(()=>{icePending=null;pollIce();},4500);
- }
- async function receiveIce(message){
- if(!pc||!icePending||message.attemptId!==attemptId||message.exchangeId!==icePending.exchangeId)return;
- const rtc=pc,g=generation,batch=icePending;
- clearTimeout(iceTimer);
- try{
- if(message.error){icePending=null;iceTimer=setTimeout(pollIce,1000);return;}
- if(!Array.isArray(message.candidates)||message.candidates.length>net.batchSize||message.next!==batch.after+message.candidates.length||message.next>net.maxCandidates)throw new Error();
- for(const candidate of message.candidates){
- if(g!==generation)return;
- const key=JSON.stringify(candidate);
- if(remoteSeen.has(key))continue;
- if(remoteSeen.size>=net.maxCandidates)throw new Error();
- await rtc.addIceCandidate(candidate);
- if(g!==generation)return;
- remoteSeen.add(key);
- }
- if(g!==generation)return;
- localAck+=batch.sent;remoteAfter=message.next;remoteComplete=message.complete===true;icePending=null;
- if(!(remoteComplete&&rtc.iceGatheringState==='complete'&&localAck===localCandidates.length))
- iceTimer=setTimeout(pollIce,net.pollMs);
- }catch{if(g===generation)failRtc('candidates');}
- }
- async function receiveAnswer(message){
- if(!pc||message.attemptId!==attemptId)return;
- const rtc=pc,g=generation;
- try{
- await rtc.setRemoteDescription({type:'answer',sdp:message.sdp});
- if(g!==generation)return;
- clearTimeout(deadlineTimer);
- deadlineTimer=setTimeout(()=>{if(g===generation&&rtc.connectionState!=='connected')failRtc('connect-timeout');},net.connectMs);
- exchangeUntil=Date.now()+net.exchangeMs;pollIce();
- }catch{if(g===generation)failRtc('answer');}
- }
- async function connect(){
- closeRtc();const g=generation;attemptId=String(g);
- if(!window.RTCPeerConnection){failRtc('unsupported',false);return;}
- configPending=true;
- deadlineTimer=setTimeout(()=>{if(g===generation&&configPending){configPending=false;void startRtc(g,iceServers);}},3500);
- return post({type:'iceConfig',attemptId});
- }
- async function receiveIceConfig(message){
- if(!epoch||!configPending||message.attemptId!==attemptId)return;
- configPending=false;clearTimeout(deadlineTimer);deadlineTimer=null;
- await startRtc(generation,message.iceServers);
- }
- async function startRtc(g,servers){
- try{
- const rtc=new RTCPeerConnection({iceServers:servers});pc=rtc;
- dc=rtc.createDataChannel('input-v1');rtc.addTransceiver('video',{direction:'recvonly'});rtc.addTransceiver('audio',{direction:'recvonly'});
- rtc.onicecandidate=({candidate})=>{
- if(g!==generation||!candidate?.candidate||!trickleIce)return;
- if(localCandidates.length>=net.maxCandidates){failRtc('candidate-limit',false);return;}
- localCandidates.push({candidate:candidate.candidate,sdpMid:candidate.sdpMid,sdpMLineIndex:candidate.sdpMLineIndex,
- ...(candidate.usernameFragment?{usernameFragment:candidate.usernameFragment}:{})});
- // Gathering continues after the offer; the serial exchange flushes late addresses.
- };
- dc.onmessage=e=>{try{if(g!==generation||pc!==rtc)return;if(typeof e.data!=='string'||e.data.length>80000)return;const message=JSON.parse(e.data);if(message.type==='cursor')receiveCursor(message.cursor);if((video.webkitPresentationMode==='picture-in-picture'||document.pictureInPictureElement===video)&&message.type==='viewPing'&&typeof message.challenge==='string'&&message.challenge.length<=64&&dc?.readyState==='open')dc.send(message.challenge);}catch{}};
- let readingStats=false;
- statsTimer=setInterval(async()=>{
- if(readingStats||g!==generation)return;readingStats=true;
- try{const stats=await rtc.getStats();if(g!==generation||pc!==rtc)return;const result=networkStats(stats,statsSample);statsSample=result.sample;post({type:'network',transport:result.transport,bytesPerSecond:result.bytesPerSecond,latencyMs:result.latencyMs});}catch{}finally{readingStats=false;}
- },1000);
- rtc.ontrack=e=>{if(g!==generation)return;video.srcObject=e.streams[0]||new MediaStream([e.track]);video.play().catch(()=>{});};
- video.onplaying=()=>{
- if(g!==generation||videoPresented||videoFrameCallback!==null||videoPaintCallback!==null)return;
- video.style.display='block';render();
- if(typeof video.requestVideoFrameCallback==='function'){
- videoFrameCallback=video.requestVideoFrameCallback(()=>{
- if(g!==generation)return;
- videoFrameCallback=null;revealVideo(g);
- });
- }else waitForVideoFrame(g);
- };
- rtc.onconnectionstatechange=()=>{
- if(g!==generation)return;
- if(['failed','closed'].includes(rtc.connectionState)){failRtc('transport');return;}
- if(rtc.connectionState==='disconnected'){
- clearTimeout(stableTimer);stableTimer=null;
- if(!disconnectTimer){release();post({type:'reconnecting',attemptId});disconnectTimer=setTimeout(()=>{if(g===generation)failRtc('disconnected');},net.disconnectedMs);}
- }else if(rtc.connectionState==='connected'){
- clearTimeout(disconnectTimer);disconnectTimer=null;clearTimeout(deadlineTimer);
- if(!stableTimer)stableTimer=setTimeout(()=>{if(g===generation)retries=0;},net.stableMs);
- if(videoPresented)post({type:'streaming',attemptId});
- }
- };
- await rtc.setLocalDescription(await rtc.createOffer());
- if(!trickleIce)await new Promise(resolve=>{
- if(rtc.iceGatheringState==='complete')return resolve();gatherDone=resolve;
- gatherTimer=setTimeout(resolve,net.legacyGatherMs);
- rtc.onicegatheringstatechange=()=>{if(rtc.iceGatheringState==='complete'){clearTimeout(gatherTimer);resolve();}};
- });
- if(g!==generation)return;
- post({type:'offer',attemptId,sdp:rtc.localDescription.sdp});
- deadlineTimer=setTimeout(()=>{if(g===generation)failRtc('answer-timeout');},net.answerMs);
- }catch{if(g===generation)failRtc('setup');}
- }
-`;
+export { DESKTOP_RTC_SCRIPT } from '@cindy/maker-shared/remote-desktop-scripts';
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 3f9f87ae3f..2e4b2fd7db 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -11,7 +11,7 @@
计数快照日期:2026-09-11。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。
-登记 surface 数:49。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。
+登记 surface 数:50。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。
| ID | 平台 | 标题 | 生产入口 | 可达组件 | 样式来源 | Token 数 | 裸颜色 | 裸圆角 |
| --- | --- | --- | --- | --- | --- | ---: | ---: | ---: |
@@ -38,12 +38,13 @@
| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 7 | 4 | 3 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 49 | 0 | 82 |
-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSegmentedControl.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 155 | 109 | 733 |
+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSegmentedControl.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 155 | 109 | 734 |
| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 146 | 58 | 291 |
| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及详情 `/skillhub/local/:kind/global/:name`、`/skillhub/local/:kind/project/:projectHash/:name` | InstallTargetPicker, PluginManagementLayout, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubMarketPreviewPanel | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx | 41 | 0 | 66 |
| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketListView, SkillhubMarketPreviewPanel, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 47 | 0 | 63 |
| `desktop.window.computer-permission-guide` | desktop | 电脑使用权限引导 | `?view=computer-permission-guide` → ComputerPermissionGuideWindow;backdrop 同文件 | ComputerPermissionBackdrop, ComputerPermissionGuideWindow | apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts, apps/desktop/src/main/computer-permission-guide/placement.ts, apps/desktop/src/main/computer-permission-guide/request.ts, apps/desktop/src/main/computer-permission-guide/switch-target.ts, apps/desktop/src/main/computer-permission-guide/window.ts, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx | 7 | 2 | 9 |
| `desktop.window.ghost-panel` | desktop | 插件面板独立窗口 | `?ghostPanelWindow=<id>` → renderer/ghost-panel-window-entry.tsx;hash `/ghost-panel-window` | GhostPanelWindowLayout | apps/desktop/src/main/ghost-panel-window/controller.ts, apps/desktop/src/main/ghost-panel-window/ipc.ts, apps/desktop/src/main/ghost-panel-window/registry.ts, apps/desktop/src/main/ghost-panel-window/settings-store.ts, apps/desktop/src/main/ghost-panel-window/window.ts, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/ghost-panel-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 59 | 50 | 14 |
+| `desktop.window.remote-desktop` | desktop | 远程桌面独立窗口 | `?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx | RemoteDesktopViewerWindow | apps/desktop/src/main/remote-desktop-viewer/connection.ts, apps/desktop/src/main/remote-desktop-viewer/registry.ts, apps/desktop/src/main/remote-desktop-viewer/windows.ts, apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx, apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css, apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 60 | 48 | 19 |
| `desktop.window.resource-usage` | desktop | 资源用量窗口 | `?resourceUsageWindow=1` → renderer/resource-usage-entry.tsx(不走 router.tsx) | ResourceUsageWindowLayout, ResourceUsageWindowRoot | apps/desktop/src/main/resource-usage-window/controller.ts, apps/desktop/src/main/resource-usage-window/ipc.ts, apps/desktop/src/main/resource-usage-window/open-sender.ts, apps/desktop/src/main/resource-usage-window/registry.ts, apps/desktop/src/main/resource-usage-window/window.ts, apps/desktop/src/renderer/components/resource-usage/ResourceUsageWindowLayout.tsx, apps/desktop/src/renderer/resource-usage-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 59 | 50 | 14 |
| `desktop.window.review-artifact-confirm` | desktop | Review 成果确认窗 | main/reviewer/reviewArtifactConfirmWindow.ts 内联 HTML/CSS(不走 renderer 路由) | reviewArtifactConfirmWindow | apps/desktop/src/main/reviewer/reviewArtifactConfirmWindow.ts | 8 | 18 | 2 |
| `desktop.window.session-drag-preview` | desktop | 会话拖拽预览 | main/session-drag-preview.ts 透明预览窗 | session-drag-preview | apps/desktop/src/main/session-drag-preview.ts | 0 | 1 | 0 |
@@ -61,7 +62,7 @@
| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HtmlFileReader, ImageLightbox, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 202 | 36 |
| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RenameSessionModal, SessionActionSheet, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, ThemeProvider, _layout, gestureHandler, index, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 53 |
| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, DeviceLinkContext, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 13 |
-| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PermissionGuide, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopIcons, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 2 | 170 | 42 |
+| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PermissionGuide, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopIcons, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 39 |
| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 18 |
| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 22 |
@@ -195,6 +196,7 @@ Mobile 已由 DS-7 纳入同一台账(2026-09-10 静态入口发现),保
| `desktop.skillhub.market` | unassigned | legacy | — | DS-8 提供适用数值;DS-9 按入口核对标准组件与呈现继承 | DS-9 核对实际消费者、局部 alias 与跨入口影响;保留现有保护合同,残余项登记理由、实际负责人及复查日期 |
| `desktop.window.computer-permission-guide` | unassigned | legacy | — | DS-8 提供适用数值;DS-9 按入口核对标准组件与呈现继承 | DS-9 核对实际消费者、局部 alias 与跨入口影响;保留现有保护合同,残余项登记理由、实际负责人及复查日期 |
| `desktop.window.ghost-panel` | unassigned | legacy | — | DS-8 提供适用数值;DS-9 按入口核对标准组件与呈现继承 | DS-9 核对实际消费者、局部 alias 与跨入口影响;保留现有保护合同,残余项登记理由、实际负责人及复查日期 |
+| `desktop.window.remote-desktop` | unassigned | legacy | — | 查现有标准组件与治理 §12 当前路线;按人工下一动作接管 | 保持现状;发现问题记下一动作,本张不修视觉 |
| `desktop.window.resource-usage` | unassigned | legacy | 外部主题导入保护 token(进程类别色) | DS-8 提供适用数值;DS-9 按入口核对标准组件与呈现继承 | DS-9 核对实际消费者、局部 alias 与跨入口影响;保留现有保护合同,残余项登记理由、实际负责人及复查日期 |
| `desktop.window.review-artifact-confirm` | unassigned | legacy | — | DS-8 提供适用数值;DS-9 按入口核对标准组件与呈现继承 | DS-9 核对实际消费者、局部 alias 与跨入口影响;保留现有保护合同,残余项登记理由、实际负责人及复查日期 |
| `desktop.window.session-drag-preview` | unassigned | legacy | — | DS-8 提供适用数值;DS-9 按入口核对标准组件与呈现继承 | DS-9 核对实际消费者、局部 alias 与跨入口影响;保留现有保护合同,残余项登记理由、实际负责人及复查日期 |
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index 6690b4baac..2bcb594ba8 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -1,4 +1,57 @@
-# Mobile remote desktop
+# Remote desktop
+
+## Desktop viewer
+
+Desktop can open a same-account computer's remote desktop from its device card
+in Remote control settings, or the task-list machine menu's Remote desktop submenu.
+It opens a clean, independent window with native mouse/keyboard input and a small
+toolbar. Reopening the same target focuses its existing window. Full screen,
+view-only/control, display selection, sound, video settings and explicit text
+clipboard transfers are available. Resolution changes appear only for a capable
+host and affect its actual monitor. Ctrl+Alt+Esc releases keyboard focus;
+Cmd/Ctrl+W closes this viewer, including while it owns keyboard focus.
+
+The window reuses the existing resource-usage auxiliary-window controller and
+factory for hidden prewarming, two-phase readiness, hide/reuse and bounded crash
+recovery. Prewarming loads only the shell and never connects to or captures a
+computer. Closing/minimizing retires its lease, clears pixels and stops polling;
+ordinary focus loss releases held input while retaining viewing. A crashed or
+automatically restored viewer uses `resume`, preserving a host's explicit stop.
+An account boundary destroys the viewer windows. The host's single-viewer lease
+and explicit takeover rules apply equally to phone and Desktop viewers.
+
+No new server, media protocol or native input helper is introduced. `device-link`
+owns the shared viewer lease/signaling adapters; `maker-shared/remote-desktop-viewer`
+owns the browser media, input queue and geometry used by both clients. Desktop
+imports it as a static module without inline scripts or eval. The Mobile HTML
+embeds a generated source literal because Hermes does not preserve function
+source. After editing the common browser module, run:
+
+```sh
+node scripts/sync-remote-desktop-viewer.mjs
+```
+
+The source parity test prevents Mobile from shipping a stale copy. Mobile retains
+its touch UI, native keyboard, PiP and optional unlock integration. Desktop does
+not add password storage, virtual controls, screen rotation or PiP. Its dedicated
+preload exposes only fixed viewer/window operations; Main binds requests to the
+actual window, account generation, target and returned lease. Text clipboard
+contents stay in Main. `stop` never calls `closeLink` or resets the shared relay,
+so other tasks, file views and peers keep their existing connections.
+
+The local real-Chromium harness uses the production Desktop viewer with a
+synthetic canvas host, validates video, keyboard and same-lease media recovery,
+and saves Light/Dark screenshots in a unique system temporary directory:
+
+```sh
+node apps/desktop/scripts/remote-desktop-viewer-smoke.mjs http://localhost:<vite-port> /path/to/chrome
+```
+
+This harness does not establish physical Desktop-to-Desktop, cross-NAT, macOS
+keyboard/permission or packaged-build support. Those retain the platform and
+network verification requirements below.
+
+## Mobile viewer
The device detail page opens the real desktop of the selected computer. On the
computer, enable **Settings → Remote control → Allow remote desktop**, as well
diff --git a/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts b/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts
new file mode 100644
index 0000000000..3cc03331b7
--- /dev/null
+++ b/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts
@@ -0,0 +1,38 @@
+import { it, expect, vi } from 'vitest';
+import { RemoteDesktopViewerSession, type DesktopViewerRequest } from '../remoteDesktopViewerSession';
+import type { RemoteDesktopRequest } from '../remoteDesktop';
+
+const caps={version:1,enabled:true,canControl:true,automaticReconnect:true,connectionTakeover:true,displays:[{id:'screen'}]};
+function fixture(){
+ const request=vi.fn(async(r:RemoteDesktopRequest):Promise<unknown>=>r.op==='capabilities'?caps:r.op==='start'?{lease:'lease',display:{id:'screen'},controlling:false}:{controlling:true});
+ return {request,session:new RemoteDesktopViewerSession(request as DesktopViewerRequest)};
+}
+it('uses the same peer protocol for a normal start, explicit takeover and an older host',async()=>{
+ const f=fixture();await f.session.connect({isCurrent:()=>true,takeover:true});
+ expect(f.request.mock.calls[1][0]).toEqual({op:'start',displayId:'screen',takeover:true});
+ f.session.stop();f.request.mockResolvedValueOnce({...caps,automaticReconnect:false});
+ await expect(f.session.connect({isCurrent:()=>true,resume:true})).rejects.toThrow('CHANNEL_NOT_ALLOWED');
+});
+it('a heartbeat sent before a control transition cannot overwrite the confirmed result',async()=>{
+ const f=fixture();await f.session.connect({isCurrent:()=>true});
+ let resolve!:(value:unknown)=>void;
+ f.request.mockImplementationOnce(()=>new Promise(r=>{resolve=r;}));
+ const heartbeat=f.session.heartbeat();await f.session.control(true);resolve({controlling:false});
+ expect(await heartbeat).toEqual({controlling:true});
+});
+it('an uncertain release blocks takeover until a heartbeat reconciles and releases host input',async()=>{
+ const f=fixture();await f.session.connect({isCurrent:()=>true});await f.session.control(true);
+ f.request.mockRejectedValueOnce(new Error('INVOKE_TIMEOUT'));
+ await expect(f.session.control(false)).rejects.toThrow('INVOKE_TIMEOUT');
+ await expect(f.session.control(true)).rejects.toThrow('DESKTOP_INPUT_BUSY');
+ f.request.mockResolvedValueOnce({controlling:true}).mockResolvedValueOnce({controlling:false});
+ expect(await f.session.heartbeat()).toEqual({controlling:false});
+ expect(f.request.mock.calls.at(-1)?.[0]).toEqual({op:'control',lease:'lease',enabled:false});
+});
+it('stop cancels a pending start and cleans up the returned lease without reopening',async()=>{
+ const f=fixture();let finish!:(value:unknown)=>void;
+ f.request.mockResolvedValueOnce(caps).mockImplementationOnce(()=>new Promise(r=>{finish=r;}));
+ const connection=f.session.connect({isCurrent:()=>true});await Promise.resolve();f.session.stop();
+ finish({lease:'late'});await expect(connection).rejects.toThrow('DESKTOP_VIDEO_STOPPED');
+ expect(f.request.mock.calls.at(-1)?.[0]).toEqual({op:'stop',lease:'late'});
+});
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 33506f668c..293a3bface 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -16,6 +16,8 @@ export * from './attachmentOssRef.js';
export * from './contactsSyncProtocol.js';
export * from './remoteResources.js';
export * from './remoteDesktop.js';
+export * from './remoteDesktopViewerSession.js';
+export * from './remoteDesktopViewerMedia.js';
export * from './deviceIdentity.js';
export * from './remoteCredentials.js';
export * from './remoteDesktopIce.js';
diff --git a/packages/device-link/src/remoteDesktopViewerMedia.ts b/packages/device-link/src/remoteDesktopViewerMedia.ts
new file mode 100644
index 0000000000..8eee9028c2
--- /dev/null
+++ b/packages/device-link/src/remoteDesktopViewerMedia.ts
@@ -0,0 +1,145 @@
+import {
+ isDesktopAttemptId,
+ isDesktopIceCursor,
+ parseDesktopIceCandidates,
+ parseDesktopIceReply,
+} from "./remoteDesktopIce.js";
+import type {
+ RemoteDesktopCapabilities,
+ RemoteDesktopLease,
+ RemoteDesktopVideoSettings,
+} from "./remoteDesktop.js";
+import type { DesktopViewerRequest } from "./remoteDesktopViewerSession.js";
+import type { DesktopIceServer } from "./remoteDesktopIceConfig.js";
+
+/** Signaling adapter shared by both viewer shells. Media recovery retains the
+ * lease; only the browser runtime owns ICE retries and frame handoff.
+ */
+export class RemoteDesktopViewerMedia {
+ private attempt: string | null = null;
+ private generation = 0;
+ constructor(
+ private readonly deps: {
+ request: DesktopViewerRequest;
+ loadIce: (attemptId: string) => Promise<DesktopIceServer[]>;
+ send: (message: object) => void;
+ current: () => {
+ lease: RemoteDesktopLease;
+ caps: RemoteDesktopCapabilities;
+ settings: RemoteDesktopVideoSettings;
+ } | null;
+ onAttempt?: (attempt: string) => void;
+ onOfferStart?: (lease: RemoteDesktopLease) => void;
+ onOfferSettled?: (lease: RemoteDesktopLease) => void;
+ onOfferFailure?: () => void;
+ },
+ ) {}
+ reset(): void {
+ this.generation++;
+ this.attempt = null;
+ }
+ matches(attempt: unknown): boolean {
+ return attempt === this.attempt;
+ }
+ get attemptId(): string | undefined {
+ return this.attempt ?? undefined;
+ }
+ async handle(message: Record<string, unknown>): Promise<boolean> {
+ if (!["iceConfig", "offer", "ice"].includes(String(message.type)))
+ return false;
+ const current = this.deps.current();
+ if (
+ !current ||
+ message.epoch !== current.lease.lease ||
+ !isDesktopAttemptId(message.attemptId)
+ )
+ return true;
+ const epoch = this.generation;
+ const attempt = message.attemptId;
+ if (message.type !== "ice") {
+ this.attempt = attempt;
+ this.deps.onAttempt?.(attempt);
+ }
+ const valid = () =>
+ this.generation === epoch &&
+ this.attempt === attempt &&
+ this.deps.current()?.lease === current.lease;
+ const check = () => {
+ if (!valid()) throw new Error("DESKTOP_VIDEO_STOPPED");
+ };
+ const send = (value: object) => {
+ if (valid())
+ this.deps.send({
+ ...value,
+ epoch: current.lease.lease,
+ attemptId: attempt,
+ });
+ };
+ if (message.type === "iceConfig") {
+ try {
+ send({
+ type: "iceConfig",
+ iceServers: await this.deps.loadIce(attempt),
+ });
+ } catch (error) {
+ if (valid()) throw error;
+ }
+ } else if (message.type === "offer") {
+ if (typeof message.sdp !== "string" || message.sdp.length > 64_000)
+ return true;
+ this.deps.onOfferStart?.(current.lease);
+ try {
+ const answer = await this.deps.request<{ sdp: string }>(
+ {
+ op: "offer",
+ lease: current.lease.lease,
+ sdp: message.sdp,
+ ...(current.caps.trickleIce ? { attemptId: attempt } : {}),
+ cursorOverlay: current.caps.cursorOverlay === true,
+ ...(current.caps.videoSettings
+ ? { settings: current.settings }
+ : {}),
+ },
+ check,
+ );
+ send({ type: "answer", sdp: answer.sdp });
+ } catch (error) {
+ const permanent =
+ /DESKTOP_(AUDIO_UNAVAILABLE|SCREEN_PERMISSION_REQUIRED|DISABLED|STOPPED|LEASE_EXPIRED)/.test(
+ String(error),
+ );
+ send({ type: "fallback", retry: !permanent });
+ if (valid()) this.deps.onOfferFailure?.();
+ } finally {
+ this.deps.onOfferSettled?.(current.lease);
+ }
+ } else {
+ if (attempt !== this.attempt) return true;
+ if (
+ !current.caps.trickleIce ||
+ !isDesktopIceCursor(message.after) ||
+ !Number.isSafeInteger(message.exchangeId)
+ )
+ return true;
+ try {
+ const reply = parseDesktopIceReply(
+ await this.deps.request(
+ {
+ op: "ice",
+ lease: current.lease.lease,
+ attemptId: attempt,
+ after: message.after,
+ candidates: parseDesktopIceCandidates(message.candidates),
+ },
+ check,
+ ),
+ );
+ if (reply.attemptId === attempt)
+ send({ type: "ice", exchangeId: message.exchangeId, ...reply });
+ } catch {
+ send({ type: "ice", exchangeId: message.exchangeId, error: true });
+ }
+ }
+ return true;
+ }
+}
diff --git a/packages/device-link/src/remoteDesktopViewerSession.ts b/packages/device-link/src/remoteDesktopViewerSession.ts
new file mode 100644
index 0000000000..0e4d021de4
--- /dev/null
+++ b/packages/device-link/src/remoteDesktopViewerSession.ts
@@ -0,0 +1,154 @@
+import type {
+ RemoteDesktopCapabilities,
+ RemoteDesktopLease,
+ RemoteDesktopRequest,
+} from "./remoteDesktop.js";
+
+export type DesktopViewerRequest = <T>(
+ request: RemoteDesktopRequest,
+ beforeSend?: () => void,
+) => Promise<T>;
+
+/** Viewer-side lease ownership, shared by native Mobile and the Desktop window.
+ * A viewer never owns the shared Device Link: stop releases only its own lease.
+ */
+export class RemoteDesktopViewerSession {
+ private generation = 0;
+ private active: RemoteDesktopLease | null = null;
+ private controlPending: Promise<unknown> | null = null;
+ private controlGeneration = 0;
+ private releaseUnconfirmed = false;
+ constructor(private readonly request: DesktopViewerRequest) {}
+
+ get lease(): RemoteDesktopLease | null {
+ return this.active;
+ }
+
+ async connect(options: {
+ displayId?: string;
+ resume?: boolean;
+ takeover?: boolean;
+ isCurrent: () => boolean;
+ onCapabilities?: (caps: RemoteDesktopCapabilities) => void;
+ }): Promise<{ caps: RemoteDesktopCapabilities; lease: RemoteDesktopLease }> {
+ const generation = ++this.generation;
+ const check = () => {
+ if (generation !== this.generation || !options.isCurrent())
+ throw new Error("DESKTOP_VIDEO_STOPPED");
+ };
+ check();
+ const caps = await this.request<RemoteDesktopCapabilities>(
+ { op: "capabilities" },
+ check,
+ );
+ check();
+ if (caps?.version !== 1) throw new Error("CHANNEL_NOT_ALLOWED");
+ if (!caps.enabled) throw new Error("DESKTOP_DISABLED");
+ if (options.resume && !caps.automaticReconnect)
+ throw new Error("CHANNEL_NOT_ALLOWED");
+ options.onCapabilities?.(caps);
+ check();
+ const display =
+ caps.displays.find((d) => d.id === options.displayId) ?? caps.displays[0];
+ if (!display) throw new Error("DESKTOP_DISPLAY_MISSING");
+ const lease = await this.request<RemoteDesktopLease>(
+ {
+ op: "start",
+ displayId: display.id,
+ ...(options.takeover && caps.connectionTakeover
+ ? { takeover: true }
+ : options.resume
+ ? { resume: true }
+ : {}),
+ },
+ check,
+ );
+ if (generation !== this.generation || !options.isCurrent()) {
+ void this.request({ op: "stop", lease: lease.lease }).catch(() => {});
+ throw new Error("DESKTOP_VIDEO_STOPPED");
+ }
+ this.active = lease;
+ return { caps, lease };
+ }
+
+ async control(enabled: boolean): Promise<{ controlling: boolean }> {
+ const lease = this.active;
+ if (!lease) throw new Error("DESKTOP_LEASE_EXPIRED");
+ if (this.controlPending) throw new Error("DESKTOP_INPUT_BUSY");
+ if (enabled && this.releaseUnconfirmed)
+ throw new Error("DESKTOP_INPUT_BUSY");
+ this.controlGeneration++;
+ if (!enabled) this.releaseUnconfirmed = true;
+ const check = () => {
+ if (this.active !== lease) throw new Error("DESKTOP_LEASE_EXPIRED");
+ };
+ const operation = this.request<{ controlling: boolean }>(
+ { op: "control", lease: lease.lease, enabled },
+ check,
+ );
+ this.controlPending = operation;
+ try {
+ const result = await operation;
+ check();
+ lease.controlling = result.controlling === true;
+ if (!lease.controlling) this.releaseUnconfirmed = false;
+ return { controlling: lease.controlling };
+ } finally {
+ if (this.controlPending === operation) this.controlPending = null;
+ }
+ }
+
+ async heartbeat(): Promise<{ controlling: boolean }> {
+ const lease = this.active;
+ if (!lease) throw new Error("DESKTOP_LEASE_EXPIRED");
+ const pendingAtStart = this.controlPending;
+ const controlGeneration = this.controlGeneration;
+ const result = await this.request<{ controlling: boolean }>({
+ op: "heartbeat",
+ lease: lease.lease,
+ });
+ if (this.active !== lease) throw new Error("DESKTOP_LEASE_EXPIRED");
+ // A heartbeat sent before a control transition cannot acknowledge that transition.
+ if (
+ !pendingAtStart &&
+ !this.controlPending &&
+ controlGeneration === this.controlGeneration
+ ) {
+ lease.controlling = result.controlling === true;
+ if (!lease.controlling) this.releaseUnconfirmed = false;
+ else if (this.releaseUnconfirmed) {
+ await this.control(false);
+ }
+ }
+ return { controlling: lease.controlling };
+ }
+
+ stop(lockScreen = false): Promise<unknown> {
+ this.generation++;
+ const lease = this.active;
+ this.active = null;
+ this.controlPending = null;
+ this.controlGeneration++;
+ this.releaseUnconfirmed = false;
+ return lease
+ ? this.request({
+ op: "stop",
+ lease: lease.lease,
+ ...(lockScreen ? { lockScreen: true } : {}),
+ })
+ : Promise.resolve();
+ }
+}
+
+/** Only transient connection errors may restart a viewer. Explicit stop wins. */
+export function remoteDesktopFailureKey(code: string): string | null {
+ if (/ACCESS_REVOKED/.test(code)) return "accessRevoked";
+ if (/REMOTE_DISABLED/.test(code)) return "remoteDisabled";
+ if (/DESKTOP_BUSY/.test(code)) return "connectionBusy";
+ if (/CHANNEL_NOT_ALLOWED/.test(code)) return "upgrade";
+ if (/DESKTOP_DISABLED/.test(code)) return "disabled";
+ if (/PERMISSION|ACCESSIBILITY/.test(code)) return "permissionHint";
+ if (/DESKTOP_STOPPED|DESKTOP_AUTHENTICATION_REQUIRED/.test(code))
+ return "disconnected";
+ return null;
+}
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index a35b8a97ed..14013c2c56 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -77,7 +77,10 @@
"./codex-usage-buckets": "./src/codexUsageBuckets.ts",
"./botCollaboration": "./src/botCollaboration.ts",
"./botDirectMessage": "./src/botDirectMessage.ts",
- "./botDelegation": "./src/botDelegation.ts"
+ "./botDelegation": "./src/botDelegation.ts",
+ "./remote-desktop-viewer": "./src/remote-desktop/viewerRuntime.js",
+ "./remote-desktop-mobile": "./src/remote-desktop/mobileHtml.ts",
+ "./remote-desktop-scripts": "./src/remote-desktop/viewerScripts.ts"
},
"scripts": {
"build": "tsc --noEmit",
diff --git a/packages/maker-shared/src/__tests__/remoteDesktopViewerSource.test.ts b/packages/maker-shared/src/__tests__/remoteDesktopViewerSource.test.ts
new file mode 100644
index 0000000000..f69a4b6332
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/remoteDesktopViewerSource.test.ts
@@ -0,0 +1,9 @@
+import fs from 'node:fs';
+import { expect, it } from 'vitest';
+import { DESKTOP_VIEWER_SOURCE } from '../remote-desktop/viewerSource';
+
+it('Mobile embeds the exact viewer module imported by Desktop, without Hermes serialization',()=>{
+ const runtime=fs.readFileSync(new URL('../remote-desktop/viewerRuntime.js',import.meta.url),'utf8').replace(/\r\n/g,'\n');
+ expect(DESKTOP_VIEWER_SOURCE).toBe(runtime.replace('export function','function'));
+ expect(runtime).not.toMatch(/\beval\s*\(|new Function\s*\(|ReactNativeWebView/);
+});
diff --git a/packages/maker-shared/src/remote-desktop/mobileHtml.ts b/packages/maker-shared/src/remote-desktop/mobileHtml.ts
new file mode 100644
index 0000000000..0f2a5a320c
--- /dev/null
+++ b/packages/maker-shared/src/remote-desktop/mobileHtml.ts
@@ -0,0 +1,38 @@
+import { DESKTOP_VIEWER_SOURCE } from "./viewerSource";
+
+export function remoteDesktopViewerHtml(
+ surface: string,
+ foreground: string,
+ config: { net: unknown; iceServers: unknown; keyCodes: readonly string[] },
+): string {
+ // Only theme token colors enter markup. No device names, SDP, or remote HTML.
+ const color = (v: string) =>
+ /^#[0-9a-f]{3,8}$/i.test(v) ? v : "transparent";
+ return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; media-src blob:; connect-src 'none'"><style>
+ *{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:${color(surface)};touch-action:none;overscroll-behavior:none}#stage{position:absolute;inset:0;overflow:hidden;z-index:0}video,img{position:absolute;max-width:none;pointer-events:none;transform-origin:0 0}video{display:none;z-index:0}#cursor{position:absolute;z-index:3;width:18px;height:18px;border:2px solid ${color(foreground)};border-radius:50%;pointer-events:none;display:none;transform:translate(-50%,-50%)}
+ #cursor-image{position:absolute;inset:0;width:100%;height:100%}
+ #stage,#stage *{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-user-drag:none}
+ video,img{border:0;outline:0}#image{z-index:1}img:not([src]){visibility:hidden}
+ :root{--surface:${color(surface)};--foreground:${color(foreground)}}
+ #keyboard-input{position:absolute;left:0;bottom:0;width:1px;height:1px;opacity:.01;font-size:16px;pointer-events:none;border:0;padding:0;resize:none}
+ #mouse-buttons{position:absolute;inset:0;pointer-events:none;display:none;color:var(--foreground);opacity:.85}
+ #mouse-buttons button,#mouse-wheel{pointer-events:auto;touch-action:none;user-select:none;-webkit-user-select:none;color:inherit;background:color-mix(in srgb,var(--surface) 90%,var(--foreground));border:1px solid color-mix(in srgb,var(--foreground) 18%,transparent)}
+ .mouse-button{position:absolute;width:56px;height:56px;border-radius:9999px;padding:14px}
+ .mouse-button svg{width:100%;height:100%;pointer-events:none}
+ .mouse-button[aria-pressed="true"]{background:var(--foreground)!important;color:var(--surface)!important}
+ #mouse-left{left:calc(50% - 96px);bottom:16px}#mouse-right{left:calc(50% + 40px);bottom:16px}
+ #mouse-wheel{position:absolute;right:12px;bottom:80px;width:56px;height:120px;padding:12px 0;border-radius:9999px;display:flex;flex-direction:column;align-items:center;justify-content:space-between;font-size:20px}
+ #mouse-wheel:active{background:var(--foreground);color:var(--surface)}
+ #mouse-wheel>*{pointer-events:none}
+ #mouse-wheel-grip{width:20px;height:34px}
+ @media(max-height:400px){#mouse-wheel{bottom:12px}}
+ </style></head><body><div id="stage"><img id="image" alt=""><video id="video" autoplay muted playsinline></video><div id="cursor"><img id="cursor-image" alt=""></div></div>
+ <div id="mouse-buttons">
+ ${(["left", "right"] as const).map((button) => `<button type="button" id="mouse-${button}" class="mouse-button" aria-pressed="false"><svg viewBox="0 0 24 32" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="2" width="18" height="28" rx="9"/><path d="M12 2v12M3 14h18"/><path d="${button === "left" ? "M11 3C6 3 4 6 4 10v3h7Z" : "M13 3c5 0 7 3 7 7v3h-7Z"}" fill="currentColor" stroke="none"/></svg></button>`).join("")}
+ <button type="button" id="mouse-wheel"><span aria-hidden="true">▴</span><svg id="mouse-wheel-grip" viewBox="0 0 20 34" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="1" y="1" width="18" height="32" rx="8"/><path d="M3 10h14M2 17h16M3 24h14"/></svg><span aria-hidden="true">▾</span></button>
+ </div><textarea id="keyboard-input" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" aria-label="Keyboard"></textarea><script>
+ ${DESKTOP_VIEWER_SOURCE}
+ const viewer=mountRemoteDesktopViewer(document, message=>window.ReactNativeWebView.postMessage(JSON.stringify(message)),${JSON.stringify(config)});
+ const receive=e=>{try{viewer.receive(JSON.parse(e.data));}catch{}};window.addEventListener('message',receive);document.addEventListener('message',receive);
+ </script></body></html>`;
+}
diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.d.ts b/packages/maker-shared/src/remote-desktop/viewerRuntime.d.ts
new file mode 100644
index 0000000000..44b60b57f5
--- /dev/null
+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.d.ts
@@ -0,0 +1,6 @@
+/** Browser-only adapter. No React, Electron, credentials or device-link ownership. */
+export function mountRemoteDesktopViewer(
+ root: Document | HTMLElement,
+ post: (message: Record<string, unknown>) => void,
+ config: { net: object; iceServers: readonly object[]; keyCodes: readonly string[]; desktop?: boolean },
+): { receive(message: object): void; dispose(): void };
diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
new file mode 100644
index 0000000000..55ee4364c7
--- /dev/null
+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
@@ -0,0 +1,1682 @@
+/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */
+export function mountRemoteDesktopViewer(root, postMessage, config) {
+ const cleanups = [];
+ const listen = (target, type, fn, options) => {
+ target.addEventListener(type, fn, options);
+ cleanups.push(() => target.removeEventListener(type, fn, options));
+ };
+ const find = (id) =>
+ root.getElementById
+ ? root.getElementById(id)
+ : root.querySelector("#" + id);
+ const { net, iceServers } = config;
+ const validKeys = new Set(config.keyCodes);
+ const transform =
+ /* BEGIN TRANSFORM */
+ function desktopTransform(
+ vw,
+ vh,
+ dw,
+ dh,
+ zoom,
+ fx,
+ fy,
+ fillHeight = false,
+ ) {
+ const scale =
+ (fillHeight
+ ? vh / Math.max(1, dh)
+ : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *
+ Math.max(1, Math.min(5, zoom));
+ const width = dw * scale;
+ const height = dh * scale;
+ const x =
+ width <= vw
+ ? (vw - width) / 2
+ : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));
+ const y =
+ height <= vh
+ ? (vh - height) / 2
+ : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));
+ return { x, y, width, height, scale };
+ };
+ /* END TRANSFORM */ const networkStats =
+ /* BEGIN NETWORK_STATS */
+ function networkStats(stats, previous) {
+ const rows = [...stats.values()];
+ const video = rows.find(
+ (s) =>
+ s.type === "inbound-rtp" &&
+ (s.kind === "video" || s.mediaType === "video"),
+ );
+ const transport = rows.find(
+ (s) => s.type === "transport" && s.selectedCandidatePairId,
+ );
+ const pair = transport
+ ? stats.get(transport.selectedCandidatePairId)
+ : rows.find(
+ (s) =>
+ s.type === "candidate-pair" &&
+ s.state === "succeeded" &&
+ s.nominated,
+ );
+ const local = pair && stats.get(pair.localCandidateId),
+ remote = pair && stats.get(pair.remoteCandidateId);
+ const direct = ["host", "srflx", "prflx"];
+ const route =
+ local?.candidateType === "relay" || remote?.candidateType === "relay"
+ ? "relay"
+ : direct.includes(local?.candidateType) &&
+ direct.includes(remote?.candidateType)
+ ? "direct"
+ : "video";
+ const sample =
+ video &&
+ Number.isFinite(video.bytesReceived) &&
+ Number.isFinite(video.timestamp)
+ ? {
+ id: video.id,
+ path: pair?.id,
+ bytes: video.bytesReceived,
+ time: video.timestamp,
+ }
+ : null;
+ let bytesPerSecond = null;
+ if (
+ sample &&
+ previous &&
+ sample.id === previous.id &&
+ sample.path === previous.path &&
+ sample.time > previous.time &&
+ sample.bytes >= previous.bytes
+ )
+ bytesPerSecond =
+ ((sample.bytes - previous.bytes) * 1000) /
+ (sample.time - previous.time);
+ const latencyMs =
+ Number.isFinite(pair?.currentRoundTripTime) &&
+ pair.currentRoundTripTime >= 0
+ ? pair.currentRoundTripTime * 1000
+ : null;
+ return { transport: route, bytesPerSecond, latencyMs, sample };
+ };
+
+ /* END NETWORK_STATS */ const stage = find("stage"),
+ image = find("image"),
+ video = find("video"),
+ cursor = find("cursor");
+ let dw = 1920,
+ dh = 1080,
+ zoom = 1,
+ fx = 0.5,
+ fy = 0.5,
+ mode = "pointer",
+ control = false,
+ pc = null,
+ dc = null,
+ seq = 0,
+ generation = 0,
+ epoch = null,
+ gestureFrame = null;
+ let remoteCursor = null,
+ lastLocalMove = 0,
+ localCursorAwake = false;
+ let touchCursor = null,
+ touchCursorTimer = null,
+ touchCursorVisible = false;
+ const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
+ const cursorImage = find("cursor-image");
+ let pending = [],
+ sending = false,
+ cx = 0.5,
+ cy = 0.5,
+ drag = false,
+ start = null,
+ last = null,
+ multi = null,
+ hold = null,
+ moved = false;
+ const pointers = new Map();
+ const mouseButtons = find("mouse-buttons"),
+ wheel = find("mouse-wheel"),
+ wheelGrip = find("mouse-wheel-grip");
+ const keyboardInput = find("keyboard-input");
+ let keyboardEnabled = false,
+ composing = false;
+ const keyboardSentinel = "\u200b";
+ function resetKeyboard() {
+ keyboardInput.value = keyboardSentinel;
+ keyboardInput.setSelectionRange(1, 1);
+ }
+ function showKeyboard(enabled) {
+ keyboardEnabled = enabled && control;
+ if (!keyboardEnabled) {
+ composing = false;
+ resetKeyboard();
+ keyboardInput.blur();
+ return;
+ }
+ if (composing) return;
+ // Keep focus inside the native evaluateJavaScript call; WebKit can reject
+ // keyboard presentation after requestAnimationFrame loses user activation.
+ keyboardInput.blur();
+ resetKeyboard();
+ keyboardInput.focus({ preventScroll: true });
+ }
+ function keyboardKey(code) {
+ if (!keyboardEnabled || !control) return;
+ queue({ kind: "key", code, down: true });
+ queue({ kind: "key", code, down: false });
+ flush();
+ }
+ function commitKeyboard() {
+ if (!keyboardEnabled || !control || composing) return;
+ const text = keyboardInput.value.replace(keyboardSentinel, "");
+ if (text) {
+ for (let i = 0; i < text.length; i += 4096)
+ queue({ kind: "text", text: text.slice(i, i + 4096) });
+ flush();
+ }
+ resetKeyboard();
+ }
+ listen(keyboardInput, "compositionstart", () => {
+ composing = true;
+ });
+ listen(keyboardInput, "compositionend", () => {
+ composing = false;
+ commitKeyboard();
+ });
+ listen(keyboardInput, "input", (e) => {
+ if (!e.isComposing) commitKeyboard();
+ });
+ listen(keyboardInput, "beforeinput", (e) => {
+ if (composing || e.isComposing) return;
+ if (e.inputType === "deleteContentBackward") {
+ e.preventDefault();
+ keyboardKey("Backspace");
+ resetKeyboard();
+ } else if (
+ e.inputType === "insertLineBreak" ||
+ e.inputType === "insertParagraph"
+ ) {
+ e.preventDefault();
+ keyboardKey("Enter");
+ resetKeyboard();
+ }
+ });
+ const heldMouse = new Map();
+ let showMouseButtons = false,
+ wheelY = null;
+ function resetWheel() {
+ wheelY = null;
+ wheelGrip.style.transform = "translateY(0px)";
+ }
+ let statsTimer = null,
+ statsSample = null;
+ const post = (message) => postMessage({ ...message, epoch });
+ const clamp = (v) => Math.max(0, Math.min(1, v));
+ let fillHeight = false;
+ let panAnimation = null,
+ viewportRightInset = 0,
+ viewportLeftInset = 0,
+ viewportBottomInset = 0,
+ keyboardViewportInset = 0;
+ let cursorNeedsEntry = true,
+ manualViewMoved = false,
+ followRest = null;
+ // Insets guide centering and pan limits without clipping the full-screen
+ // video surface or adding an opaque strip beside the Dynamic Island.
+ const viewportLeft = () => (fillHeight ? viewportLeftInset : 0);
+ const viewportWidth = () =>
+ Math.max(
+ 1,
+ stage.clientWidth -
+ viewportLeft() -
+ (fillHeight ? viewportRightInset : 0),
+ );
+ const layout = () => {
+ const r = transform(
+ viewportWidth(),
+ stage.clientHeight,
+ dw,
+ dh,
+ zoom,
+ fx,
+ fy,
+ fillHeight,
+ );
+ return {
+ ...r,
+ x: viewportLeft() + viewportWidth() / 2 - fx * r.width,
+ y: stage.clientHeight / 2 - fy * r.height,
+ };
+ };
+ function panBounds(r) {
+ const vw = viewportWidth(),
+ vh = stage.clientHeight;
+ // Grow extra resting travel continuously from zero at fit to 180 screen
+ // points at maximum zoom. Never count the unused space of a fitting axis.
+ const clearance = (180 * (Math.max(1, Math.min(5, zoom)) - 1)) / 4;
+ const axis = (viewport, content) =>
+ content <= viewport
+ ? {
+ min: (viewport - content) / 2 - clearance,
+ max: (viewport - content) / 2 + clearance,
+ }
+ : { min: viewport - content - clearance, max: clearance };
+ const x = axis(vw, r.width),
+ y = axis(vh, r.height);
+ const bounds = {
+ minX: viewportLeft() + x.min,
+ maxX: viewportLeft() + x.max,
+ minY: y.min,
+ maxY: y.max,
+ };
+ // A camera position required to expose the cursor is a valid resting point,
+ // not elastic overshoot. Preserve it across the next pan/pinch handoff.
+ if (followRest) {
+ const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,
+ restY = vh / 2 - followRest.fy * r.height;
+ const weight =
+ followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;
+ bounds.minX += Math.min(0, restX - bounds.minX) * weight;
+ bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;
+ bounds.minY += Math.min(0, restY - bounds.minY) * weight;
+ bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;
+ }
+ return bounds;
+ }
+ const bounded = (v, min, max) => Math.max(min, Math.min(max, v));
+ // Convert displayed overshoot back to finger travel before the next delta,
+ // so reversing direction unwinds smoothly without an edge jump.
+ function rubber(v, min, max, inverse = false) {
+ const edge = bounded(v, min, max),
+ d = v - edge;
+ const reach = 40 + 10 * (Math.max(1, Math.min(5, zoom)) - 1);
+ return (
+ edge +
+ Math.sign(d) *
+ (inverse
+ ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))
+ : (reach * Math.abs(d)) / (reach + Math.abs(d)))
+ );
+ }
+ function place(x, y, r) {
+ fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;
+ fy = (stage.clientHeight / 2 - y) / r.height;
+ }
+ function cursorViewport() {
+ const hotX = remoteCursor?.hotX ?? 9,
+ hotY = remoteCursor?.hotY ?? 9;
+ const w = remoteCursor?.width ?? 18,
+ h = remoteCursor?.height ?? 18;
+ const left = viewportLeft(),
+ right = left + viewportWidth(),
+ bottom = Math.max(1, stage.clientHeight - viewportBottomInset);
+ // Keep the entire cursor, including its hotspot offset, clear of chrome.
+ const minX = Math.min(right - 1, left + 8 + hotX),
+ minY = Math.min(bottom - 1, 8 + hotY);
+ return {
+ minX,
+ maxX: Math.max(minX, right - 8 - (w - hotX)),
+ minY,
+ maxY: Math.max(minY, bottom - 8 - (h - hotY)),
+ };
+ }
+ function moveTouchpad(dx, dy) {
+ stopPanAnimation();
+ const r = layout(),
+ v = cursorViewport();
+ if (cursorNeedsEntry) {
+ // Re-enter at the nearest visible edge; do not pull a manually positioned
+ // desktop back to the old off-screen cursor before applying this movement.
+ cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);
+ cy = clamp(
+ (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,
+ );
+ cursorNeedsEntry = false;
+ }
+ cx = clamp(cx + dx / r.width);
+ cy = clamp(cy + dy / r.height);
+ const x = r.x + cx * r.width,
+ y = r.y + cy * r.height;
+ if (
+ zoom > 1 ||
+ r.width > viewportWidth() ||
+ r.height > stage.clientHeight - viewportBottomInset
+ ) {
+ place(
+ r.x + bounded(x, v.minX, v.maxX) - x,
+ r.y + bounded(y, v.minY, v.maxY) - y,
+ r,
+ );
+ followRest = { fx, fy, zoom };
+ }
+ manualViewMoved = false;
+ }
+ function stopPanAnimation() {
+ if (panAnimation !== null) cancelAnimationFrame(panAnimation);
+ panAnimation = null;
+ }
+ function settlePan() {
+ stopPanAnimation();
+ const r = layout(),
+ b = panBounds(r),
+ x = bounded(r.x, b.minX, b.maxX),
+ y = bounded(r.y, b.minY, b.maxY);
+ if (x === r.x && y === r.y) return;
+ if (reducedMotion.matches) {
+ place(x, y, r);
+ render();
+ return;
+ }
+ const started = performance.now();
+ const tick = (now) => {
+ const t = Math.min(1, (now - started) / 280),
+ ease = 1 - Math.pow(1 - t, 3);
+ place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);
+ render();
+ panAnimation = t < 1 ? requestAnimationFrame(tick) : null;
+ };
+ panAnimation = requestAnimationFrame(tick);
+ }
+ function render() {
+ const r = layout();
+ const touchFeedback = control && mode === "touch" && touchCursorVisible;
+ const cursorX = mode === "touch" && touchCursor ? touchCursor.x : cx;
+ const cursorY = mode === "touch" && touchCursor ? touchCursor.y : cy;
+ cursor.style.transition =
+ mode === "touch" && !touchFeedback && !reducedMotion.matches
+ ? "opacity 120ms ease-out"
+ : "none";
+ for (const el of [image, video]) {
+ el.style.width = r.width + "px";
+ el.style.height = r.height + "px";
+ el.style.left = r.x + "px";
+ el.style.top = r.y + "px";
+ }
+ if (remoteCursor) {
+ cursor.style.width = remoteCursor.width + "px";
+ cursor.style.height = remoteCursor.height + "px";
+ cursor.style.border = "0";
+ cursor.style.borderRadius = "0";
+ cursor.style.transform = "none";
+ cursor.style.left = r.x + cursorX * r.width - remoteCursor.hotX + "px";
+ cursor.style.top = r.y + cursorY * r.height - remoteCursor.hotY + "px";
+ cursor.style.display = "block";
+ cursor.style.opacity = (
+ mode === "touch"
+ ? touchFeedback
+ : remoteCursor.visible ||
+ (control && mode === "pointer" && localCursorAwake)
+ )
+ ? "1"
+ : "0";
+ } else {
+ cursor.style.opacity = (mode === "touch" ? !touchFeedback : false)
+ ? "0"
+ : "1";
+ cursor.style.width = "18px";
+ cursor.style.height = "18px";
+ cursor.style.border = "2px solid var(--foreground)";
+ cursor.style.borderRadius = "50%";
+ cursor.style.transform = "translate(-50%,-50%)";
+ cursor.style.left = r.x + cursorX * r.width + "px";
+ cursor.style.top = r.y + cursorY * r.height + "px";
+ cursor.style.display =
+ !config.desktop && control && (mode === "pointer" || mode === "touch") ? "block" : "none";
+ }
+ if (config.desktop) stage.style.cursor = control && remoteCursor?.visible ? "none" : "default";
+ }
+ // Literal source is required: Hermes function.toString() yields bytecode.
+ function validCursor(v) {
+ return (
+ !!v &&
+ typeof v === "object" &&
+ typeof v.visible === "boolean" &&
+ [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&
+ v.x >= 0 &&
+ v.x <= 1 &&
+ v.y >= 0 &&
+ v.y <= 1 &&
+ v.width > 0 &&
+ v.width <= 256 &&
+ v.height > 0 &&
+ v.height <= 256 &&
+ v.hotX >= 0 &&
+ v.hotX <= v.width &&
+ v.hotY >= 0 &&
+ v.hotY <= v.height &&
+ typeof v.png === "string" &&
+ v.png.length <= 65536 &&
+ /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png)
+ );
+ }
+ function receiveCursor(value) {
+ if (value === null) {
+ if (remoteCursor) {
+ remoteCursor = { ...remoteCursor, visible: false };
+ render();
+ }
+ return;
+ }
+ if (!validCursor(value)) return;
+ if (!remoteCursor || remoteCursor.png !== value.png)
+ cursorImage.src = "data:image/png;base64," + value.png;
+ // Keep delayed host coordinates from pulling the local touchpad backwards.
+ if (
+ !remoteCursor ||
+ !control ||
+ mode !== "pointer" ||
+ (!pointers.size && performance.now() - lastLocalMove > 200)
+ ) {
+ cx = value.x;
+ cy = value.y;
+ }
+ if (value.visible) localCursorAwake = false;
+ remoteCursor = value;
+ render();
+ }
+ function resetCursor() {
+ clearTimeout(touchCursorTimer);
+ touchCursorVisible = false;
+ touchCursor = null;
+ localCursorAwake = false;
+ remoteCursor = null;
+ cursorImage.removeAttribute("src");
+ render();
+ }
+ function queue(event) {
+ if (!control) return;
+ // Remote visibility can remain hidden after synthetic mouse movement. Wake
+ // the local touchpad cursor until the host reports a visible cursor again.
+ if (event.kind === "move" && mode === "pointer") localCursorAwake = true;
+ if (event.kind === "key" || event.kind === "text") {
+ localCursorAwake = false;
+ render();
+ }
+ if (event.kind === "move" || event.kind === "button")
+ lastLocalMove = performance.now();
+ const tail = pending[pending.length - 1];
+ if (event.kind === "move" && tail?.kind === "move")
+ pending[pending.length - 1] = event;
+ // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the
+ // accumulated distance so a delayed ACK cannot replay a large scroll backlog.
+ else if (event.kind === "scroll" && tail?.kind === "scroll") {
+ tail.dx = Math.max(-2000, Math.min(2000, tail.dx + event.dx));
+ tail.dy = Math.max(-2000, Math.min(2000, tail.dy + event.dy));
+ } else pending.push(event);
+ if (pending.length > 64) {
+ pending = [{ kind: "release" }];
+ control = false;
+ post({ type: "inputOverflow" });
+ }
+ }
+ function flush() {
+ if (!pending.length || sending) return;
+ const events = pending.splice(0, 64),
+ sequence = ++seq;
+ if (
+ pc?.connectionState === "connected" &&
+ dc &&
+ dc.readyState === "open" &&
+ dc.bufferedAmount < 16384
+ ) {
+ dc.send(JSON.stringify({ sequence, events }));
+ } else {
+ sending = true;
+ post({ type: "input", sequence, events });
+ }
+ }
+ const inputTimer = setInterval(() => {
+ // Hold displacement controls speed, even without further pointer moves.
+ // Skip missed ticks while awaiting ACK instead of building a scroll backlog.
+ if (wheelY?.moved && !sending) {
+ const offset = Math.max(-24, Math.min(24, wheelY.y - wheelY.start));
+ if (Math.abs(offset) > 4)
+ scrollMouse(Math.sign(offset) * (Math.abs(offset) - 4) * 1.5);
+ }
+ flush();
+ }, 33);
+ cleanups.push(() => clearInterval(inputTimer));
+ function release() {
+ clearTimeout(hold);
+ if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);
+ gestureFrame = null;
+ if (control) {
+ queue({ kind: "release" });
+ flush();
+ }
+ heldMouse.clear();
+ resetWheel();
+ updateMouseButtons();
+ drag = false;
+ pointers.clear();
+ start = null;
+ last = null;
+ multi = null;
+ }
+ function updateMouseButtons() {
+ mouseButtons.style.display = showMouseButtons && control ? "block" : "none";
+ for (const [name, button] of [
+ ["left", 0],
+ ["right", 2],
+ ])
+ find("mouse-" + name).setAttribute(
+ "aria-pressed",
+ String(heldMouse.has(button)),
+ );
+ }
+ for (const [name, button] of [
+ ["left", 0],
+ ["right", 2],
+ ]) {
+ const el = find("mouse-" + name);
+ listen(el, "pointerdown", (e) => {
+ e.preventDefault();
+ if (!control || !showMouseButtons || heldMouse.has(button)) return;
+ clearTimeout(hold);
+ el.setPointerCapture(e.pointerId);
+ heldMouse.set(button, e.pointerId);
+ queue({ kind: "button", button, down: true, x: cx, y: cy });
+ flush();
+ updateMouseButtons();
+ });
+ const up = (e) => {
+ e.preventDefault();
+ if (heldMouse.get(button) !== e.pointerId) return;
+ heldMouse.delete(button);
+ queue({ kind: "button", button, down: false, x: cx, y: cy });
+ flush();
+ updateMouseButtons();
+ };
+ listen(el, "pointerup", up);
+ listen(el, "pointercancel", up);
+ listen(el, "lostpointercapture", up);
+ listen(el, "click", (e) => {
+ if (e.detail === 0 && control && showMouseButtons) {
+ click(button);
+ flush();
+ }
+ });
+ }
+ const scrollMouse = (dy) => {
+ if (control && showMouseButtons && Number.isFinite(dy)) {
+ queue({ kind: "scroll", dx: 0, dy: Math.max(-2000, Math.min(2000, dy)) });
+ }
+ };
+ listen(wheel, "pointerdown", (e) => {
+ e.preventDefault();
+ if (!control || !showMouseButtons || wheelY) return;
+ wheel.setPointerCapture(e.pointerId);
+ wheelY = { id: e.pointerId, y: e.clientY, start: e.clientY, moved: false };
+ });
+ // A small dead zone preserves middle clicks; displacement drives the timer.
+ listen(wheel, "pointermove", (e) => {
+ if (!wheelY || wheelY.id !== e.pointerId) return;
+ e.preventDefault();
+ wheelGrip.style.transform =
+ "translateY(" +
+ Math.max(-24, Math.min(24, e.clientY - wheelY.start)) +
+ "px)";
+ wheelY.y = e.clientY;
+ if (Math.abs(e.clientY - wheelY.start) > 4) wheelY.moved = true;
+ });
+ listen(wheel, "pointerup", (e) => {
+ if (!wheelY || wheelY.id !== e.pointerId) return;
+ e.preventDefault();
+ if (!wheelY.moved && control && showMouseButtons) {
+ click(1);
+ flush();
+ }
+ resetWheel();
+ });
+ const cancelWheel = (e) => {
+ if (wheelY?.id === e.pointerId) resetWheel();
+ };
+ listen(wheel, "pointercancel", cancelWheel);
+ listen(wheel, "lostpointercapture", cancelWheel);
+ listen(wheel, "click", (e) => {
+ if (e.detail === 0 && control && showMouseButtons) {
+ click(1);
+ flush();
+ }
+ });
+ listen(wheel, "keydown", (e) => {
+ if (e.key === "ArrowUp" || e.key === "ArrowDown") {
+ e.preventDefault();
+ scrollMouse(e.key === "ArrowUp" ? -120 : 120);
+ }
+ });
+ function insideDesktop(p) {
+ const r = layout();
+ return (
+ p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height
+ );
+ }
+ function point(p) {
+ const r = layout();
+ return {
+ x: clamp((p.x - r.x) / r.width),
+ y: clamp((p.y - r.y) / r.height),
+ };
+ }
+ const desktopPoint = (e) => {
+ const bounds = stage.getBoundingClientRect();
+ return { x: e.clientX - bounds.left, y: e.clientY - bounds.top };
+ };
+ function mouse(e, down) {
+ if (!control || ![0, 1, 2].includes(e.button)) return;
+ const local = desktopPoint(e);
+ if (down && !insideDesktop(local)) return;
+ const p = point(local);
+ cx = p.x;
+ cy = p.y;
+ if (down) {
+ showKeyboard(true);
+ stage.setPointerCapture(e.pointerId);
+ heldMouse.set(e.button, e.pointerId);
+ } else if (!heldMouse.delete(e.button)) return;
+ queue({ kind: "button", button: e.button, down, x: cx, y: cy });
+ flush();
+ render();
+ }
+ function click(button = 0) {
+ if (control && mode === "touch") {
+ clearTimeout(touchCursorTimer);
+ touchCursor = { x: cx, y: cy };
+ touchCursorVisible = true;
+ render();
+ touchCursorTimer = setTimeout(() => {
+ touchCursorVisible = false;
+ render();
+ }, 450);
+ }
+ queue({ kind: "button", button, down: true, x: cx, y: cy });
+ queue({ kind: "button", button, down: false, x: cx, y: cy });
+ }
+ function pan(dx, dy) {
+ manualViewMoved = true;
+ cursorNeedsEntry = true;
+ stopPanAnimation();
+ const r = layout(),
+ b = panBounds(r);
+ place(
+ rubber(rubber(r.x, b.minX, b.maxX, true) + dx, b.minX, b.maxX),
+ rubber(rubber(r.y, b.minY, b.maxY, true) + dy, b.minY, b.maxY),
+ r,
+ );
+ render();
+ }
+ function pair() {
+ const [a, b] = [...pointers.values()];
+ return {
+ x: (a.x + b.x) / 2,
+ y: (a.y + b.y) / 2,
+ d: Math.hypot(a.x - b.x, a.y - b.y),
+ };
+ }
+ function movePair() {
+ gestureFrame = null;
+ if (pointers.size < 2 || !multi) return;
+ const next = pair(),
+ span = Math.abs(next.d - multi.d),
+ travel = Math.hypot(next.x - multi.x, next.y - multi.y);
+ if (multi.kind !== "pinch") {
+ const pinchSlop = Math.max(6, Math.min(12, multi.d * 0.04));
+ if (span >= pinchSlop && span > travel * 0.65) {
+ // A parallel scroll may deliver its two pointer updates in different
+ // frames. Confirm separation briefly before taking over as a pinch.
+ if (!multi.candidate)
+ multi.candidate = {
+ at: Date.now(),
+ d: next.d,
+ zoom,
+ anchor: point(next),
+ };
+ if (Date.now() - multi.candidate.at >= 40) {
+ if (multi.kind === "scroll") {
+ multi.d = multi.candidate.d;
+ multi.zoom = multi.candidate.zoom;
+ multi.anchor = multi.candidate.anchor;
+ }
+ multi.kind = "pinch";
+ multi.candidate = null;
+ } else {
+ gestureFrame = requestAnimationFrame(movePair);
+ return;
+ }
+ } else {
+ multi.candidate = null;
+ if (!multi.kind && travel > 8 && travel > span) multi.kind = "scroll";
+ }
+ }
+ if (multi.kind === "pinch") {
+ manualViewMoved = true;
+ cursorNeedsEntry = true;
+ zoom = Math.max(
+ 1,
+ Math.min(5, (multi.zoom * next.d) / Math.max(1, multi.d)),
+ );
+ const r = layout();
+ fx =
+ multi.anchor.x +
+ (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;
+ fy = multi.anchor.y + (stage.clientHeight / 2 - next.y) / r.height;
+ const moved = layout(),
+ b = panBounds(moved);
+ place(
+ rubber(moved.x, b.minX, b.maxX),
+ rubber(moved.y, b.minY, b.maxY),
+ moved,
+ );
+ } else if (multi.kind === "scroll") {
+ const dx = next.x - multi.lastX,
+ dy = next.y - multi.lastY;
+ if (control && mode !== "pan")
+ queue({
+ kind: "scroll",
+ dx: Math.max(-2000, Math.min(2000, -dx)),
+ dy: Math.max(-2000, Math.min(2000, -dy)),
+ });
+ else pan(dx, dy);
+ }
+ if (multi.kind) {
+ multi.lastX = next.x;
+ multi.lastY = next.y;
+ }
+ render();
+ }
+ listen(stage, "pointerdown", (e) => {
+ if (config.desktop) {
+ e.preventDefault();
+ mouse(e, true);
+ return;
+ }
+ e.preventDefault();
+ stopPanAnimation();
+ stage.setPointerCapture(e.pointerId);
+ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ if (pointers.size === 1) {
+ cursorNeedsEntry = true;
+ start = { x: e.clientX, y: e.clientY };
+ last = start;
+ moved = false;
+ hold = setTimeout(() => {
+ if (
+ control &&
+ mode !== "pan" &&
+ !moved &&
+ pointers.size === 1 &&
+ !heldMouse.size &&
+ (mode !== "touch" || insideDesktop(start))
+ ) {
+ if (mode === "touch") {
+ const p = point(start);
+ cx = p.x;
+ cy = p.y;
+ }
+ queue({ kind: "button", button: 0, down: true, x: cx, y: cy });
+ drag = true;
+ }
+ }, 400);
+ } else {
+ clearTimeout(hold);
+ if (drag) queue({ kind: "release" });
+ drag = false;
+ start = null;
+ const p = pair();
+ multi = {
+ ...p,
+ lastX: p.x,
+ lastY: p.y,
+ zoom,
+ anchor: point(p),
+ kind: null,
+ };
+ }
+ });
+ listen(stage, "pointermove", (e) => {
+ if (config.desktop) {
+ if (!control) return;
+ const local = desktopPoint(e);
+ if (!heldMouse.size && !insideDesktop(local)) return;
+ const p = point(local);
+ cx = p.x;
+ cy = p.y;
+ queue({ kind: "move", x: cx, y: cy });
+ render();
+ return;
+ }
+ if (!pointers.has(e.pointerId)) return;
+ e.preventDefault();
+ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ if (pointers.size >= 2) {
+ if (gestureFrame === null) gestureFrame = requestAnimationFrame(movePair);
+ return;
+ }
+ if (!start || !last) return;
+ const now = { x: e.clientX, y: e.clientY },
+ dx = now.x - last.x,
+ dy = now.y - last.y;
+ last = now;
+ if (Math.hypot(now.x - start.x, now.y - start.y) > 6) {
+ moved = true;
+ clearTimeout(hold);
+ }
+ if (
+ !control ||
+ mode === "pan" ||
+ (mode === "touch" && !drag && !heldMouse.size)
+ ) {
+ pan(dx, dy);
+ return;
+ }
+ if (mode === "pointer") {
+ moveTouchpad(dx, dy);
+ } else {
+ const p = point(now);
+ cx = p.x;
+ cy = p.y;
+ }
+ queue({ kind: "move", x: cx, y: cy });
+ render();
+ });
+ function up(e) {
+ if (config.desktop) {
+ mouse(e, false);
+ return;
+ }
+ if (!pointers.has(e.pointerId)) return;
+ clearTimeout(hold);
+ if (pointers.size >= 2 && multi) {
+ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
+ if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);
+ movePair();
+ if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);
+ gestureFrame = null;
+ }
+ pointers.delete(e.pointerId);
+ if (drag) {
+ queue({ kind: "button", button: 0, down: false, x: cx, y: cy });
+ drag = false;
+ } else if (
+ start &&
+ !moved &&
+ control &&
+ mode !== "pan" &&
+ !heldMouse.size &&
+ e.type === "pointerup" &&
+ (mode !== "touch" || insideDesktop({ x: e.clientX, y: e.clientY }))
+ ) {
+ if (mode === "touch") {
+ const p = point({ x: e.clientX, y: e.clientY });
+ cx = p.x;
+ cy = p.y;
+ }
+ click();
+ }
+ start = null;
+ last = null;
+ multi = null;
+ render();
+ if (!pointers.size && manualViewMoved) settlePan();
+ }
+ listen(stage, "pointerup", up);
+ listen(stage, "pointercancel", () => {
+ release();
+ settlePan();
+ });
+ listen(stage, "lostpointercapture", () => {
+ if (config.desktop && heldMouse.size) release();
+ });
+ if (config.desktop)
+ listen(
+ stage,
+ "wheel",
+ (e) => {
+ e.preventDefault();
+ if (!control) return;
+ const factor =
+ e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;
+ queue({
+ kind: "scroll",
+ dx: Math.max(-2000, Math.min(2000, e.deltaX * factor)),
+ dy: Math.max(-2000, Math.min(2000, e.deltaY * factor)),
+ });
+ flush();
+ },
+ { passive: false },
+ );
+ listen(config.desktop ? stage : document, "contextmenu", (e) =>
+ e.preventDefault(),
+ );
+ // Scope selection suppression to the desktop surface, preserving the hidden
+ // textarea's native keyboard/IME editing and programmatic selection.
+ listen(stage, "selectstart", (e) => e.preventDefault());
+ listen(stage, "dragstart", (e) => e.preventDefault());
+ const normalizedKey = (code) =>
+ /^(Shift|Control|Alt|Meta)Right$/.test(code)
+ ? code.replace(/Right$/, "Left")
+ : code;
+ const hardwareKeys = new Set();
+ listen(document, "keydown", (e) => {
+ if (config.desktop) {
+ if (e.ctrlKey && e.altKey && e.code === "Escape") {
+ e.preventDefault();
+ release();
+ showKeyboard(false);
+ post({ type: "releaseFocus" });
+ return;
+ }
+ if (
+ document.activeElement !== keyboardInput ||
+ e.isComposing ||
+ composing
+ )
+ return;
+ if ((e.metaKey || e.ctrlKey) && e.code === "KeyW") return; // always retain a local close shortcut
+ if (
+ !e.ctrlKey &&
+ !e.metaKey &&
+ !e.altKey &&
+ (e.key?.length === 1 || e.key === "Process" || e.key === "Dead")
+ )
+ return;
+ }
+ if (control && validKeys.has(normalizedKey(e.code))) {
+ e.preventDefault();
+ hardwareKeys.add(normalizedKey(e.code));
+ queue({ kind: "key", code: normalizedKey(e.code), down: true });
+ }
+ });
+ listen(document, "keyup", (e) => {
+ const code = normalizedKey(e.code);
+ if (config.desktop && !hardwareKeys.delete(code)) return;
+ if (control && validKeys.has(code)) {
+ e.preventDefault();
+ queue({ kind: "key", code, down: false });
+ }
+ });
+ if (config.desktop)
+ listen(keyboardInput, "blur", () => {
+ hardwareKeys.clear();
+ release();
+ });
+ listen(window, "blur", () => {
+ release();
+ settlePan();
+ });
+ const observer = new ResizeObserver(() => {
+ release();
+ settlePan();
+ render();
+ });
+ observer.observe(stage);
+ cleanups.push(
+ () => observer.disconnect(),
+ () => stopPanAnimation(),
+ () => clearTimeout(touchCursorTimer),
+ );
+ // Keep one bounded frame in this document only; never persist desktop pixels.
+ // Snapshot before detaching the track. A JPEG fallback already lives in image.
+ function retainFrame() {
+ if (
+ !videoPresented ||
+ video.style.display !== "block" ||
+ video.readyState < 2 ||
+ !video.videoWidth ||
+ !video.videoHeight
+ )
+ return;
+ const canvas = document.createElement("canvas");
+ try {
+ const scale = Math.min(
+ 1,
+ 1280 / Math.max(video.videoWidth, video.videoHeight),
+ );
+ canvas.width = Math.max(1, Math.round(video.videoWidth * scale));
+ canvas.height = Math.max(1, Math.round(video.videoHeight * scale));
+ const context = canvas.getContext("2d");
+ if (context) {
+ context.drawImage(video, 0, 0, canvas.width, canvas.height);
+ image.src = canvas.toDataURL("image/jpeg", 0.7);
+ }
+ } catch {
+ /* Keep the previous compatibility frame if WebKit cannot read video. */
+ } finally {
+ canvas.width = 0;
+ canvas.height = 0;
+ }
+ }
+ /* BEGIN RTC */
+
+ let trickleIce = false,
+ attemptId = null,
+ retries = 0,
+ exchangeId = 0;
+ let configPending = false;
+ let videoPresented = false,
+ videoFrameCallback = null,
+ videoPaintCallback = null;
+ function cancelVideoHandoff() {
+ if (videoFrameCallback !== null)
+ video.cancelVideoFrameCallback?.(videoFrameCallback);
+ if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);
+ videoFrameCallback = videoPaintCallback = null;
+ }
+ function revealVideo(g) {
+ post({ type: "videoFrameReady", attemptId });
+ // Keep the JPEG decoded and painted as a backing layer. Promote the video
+ // only after its first frame; removing the image exposes WebKit repaint gaps.
+ videoPaintCallback = requestAnimationFrame(() => {
+ if (g !== generation) return;
+ videoPaintCallback = requestAnimationFrame(() => {
+ if (g !== generation) return;
+ videoPaintCallback = null;
+ videoPresented = true;
+ video.style.zIndex = "2";
+ post({ type: "streaming", attemptId });
+ post({
+ type: "pipCapability",
+ supported: !!(
+ video.webkitSupportsPresentationMode?.("picture-in-picture") ||
+ document.pictureInPictureEnabled
+ ),
+ });
+ });
+ });
+ }
+ function waitForVideoFrame(g) {
+ if (g !== generation) return;
+ if (
+ video.readyState >= 2 &&
+ video.videoWidth > 0 &&
+ video.videoHeight > 0
+ ) {
+ revealVideo(g);
+ return;
+ }
+ videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));
+ }
+ let retryTimer = null,
+ deadlineTimer = null,
+ disconnectTimer = null,
+ stableTimer = null,
+ iceTimer = null,
+ gatherTimer = null,
+ gatherDone = null;
+ let localCandidates = [],
+ localAck = 0,
+ remoteAfter = 0,
+ icePending = null,
+ remoteSeen = new Set(),
+ exchangeUntil = 0,
+ remoteComplete = false;
+ function clearRtcTimers() {
+ for (const timer of [
+ retryTimer,
+ deadlineTimer,
+ disconnectTimer,
+ stableTimer,
+ iceTimer,
+ gatherTimer,
+ ])
+ clearTimeout(timer);
+ retryTimer =
+ deadlineTimer =
+ disconnectTimer =
+ stableTimer =
+ iceTimer =
+ gatherTimer =
+ null;
+ if (gatherDone) {
+ gatherDone();
+ gatherDone = null;
+ }
+ }
+ function closeRtc(preserveFrame = true) {
+ configPending = false;
+ if (preserveFrame) retainFrame();
+ generation++;
+ clearRtcTimers();
+ cancelVideoHandoff();
+ videoPresented = false;
+ localCandidates = [];
+ localAck = remoteAfter = 0;
+ icePending = null;
+ remoteSeen = new Set();
+ attemptId = null;
+ clearInterval(statsTimer);
+ statsTimer = null;
+ statsSample = null;
+ if (dc) dc.close();
+ if (pc) pc.close();
+ pc = null;
+ dc = null;
+ video.onplaying = null;
+ video.srcObject = null;
+ video.style.display = "none";
+ video.style.zIndex = "0";
+ image.style.display = "block";
+ if (!preserveFrame) image.removeAttribute("src");
+ }
+ function failRtc(reason, canRetry = true) {
+ const failedAttempt = attemptId;
+ release();
+ closeRtc();
+ post({ type: "fallback", attemptId: failedAttempt, reason });
+ if (canRetry && epoch && retries < net.retryMs.length) {
+ const delay = net.retryMs[retries++];
+ retryTimer = setTimeout(() => {
+ retryTimer = null;
+ if (epoch) connect();
+ }, delay);
+ }
+ }
+ function pollIce() {
+ if (
+ !pc ||
+ !trickleIce ||
+ !pc.remoteDescription ||
+ icePending ||
+ Date.now() >= exchangeUntil
+ )
+ return;
+ const candidates = localCandidates.slice(
+ localAck,
+ localAck + net.batchSize,
+ );
+ icePending = {
+ after: remoteAfter,
+ sent: candidates.length,
+ exchangeId: ++exchangeId,
+ };
+ post({
+ type: "ice",
+ attemptId,
+ candidates,
+ after: remoteAfter,
+ exchangeId,
+ });
+ iceTimer = setTimeout(() => {
+ icePending = null;
+ pollIce();
+ }, 4500);
+ }
+ async function receiveIce(message) {
+ if (
+ !pc ||
+ !icePending ||
+ message.attemptId !== attemptId ||
+ message.exchangeId !== icePending.exchangeId
+ )
+ return;
+ const rtc = pc,
+ g = generation,
+ batch = icePending;
+ clearTimeout(iceTimer);
+ try {
+ if (message.error) {
+ icePending = null;
+ iceTimer = setTimeout(pollIce, 1000);
+ return;
+ }
+ if (
+ !Array.isArray(message.candidates) ||
+ message.candidates.length > net.batchSize ||
+ message.next !== batch.after + message.candidates.length ||
+ message.next > net.maxCandidates
+ )
+ throw new Error();
+ for (const candidate of message.candidates) {
+ if (g !== generation) return;
+ const key = JSON.stringify(candidate);
+ if (remoteSeen.has(key)) continue;
+ if (remoteSeen.size >= net.maxCandidates) throw new Error();
+ await rtc.addIceCandidate(candidate);
+ if (g !== generation) return;
+ remoteSeen.add(key);
+ }
+ if (g !== generation) return;
+ localAck += batch.sent;
+ remoteAfter = message.next;
+ remoteComplete = message.complete === true;
+ icePending = null;
+ if (!(
+ remoteComplete &&
+ rtc.iceGatheringState === "complete" &&
+ localAck === localCandidates.length
+ ))
+ iceTimer = setTimeout(pollIce, net.pollMs);
+ } catch {
+ if (g === generation) failRtc("candidates");
+ }
+ }
+ async function receiveAnswer(message) {
+ if (!pc || message.attemptId !== attemptId) return;
+ const rtc = pc,
+ g = generation;
+ try {
+ await rtc.setRemoteDescription({ type: "answer", sdp: message.sdp });
+ if (g !== generation) return;
+ clearTimeout(deadlineTimer);
+ deadlineTimer = setTimeout(() => {
+ if (g === generation && rtc.connectionState !== "connected")
+ failRtc("connect-timeout");
+ }, net.connectMs);
+ exchangeUntil = Date.now() + net.exchangeMs;
+ pollIce();
+ } catch {
+ if (g === generation) failRtc("answer");
+ }
+ }
+ async function connect() {
+ closeRtc();
+ const g = generation;
+ attemptId = String(g);
+ if (!window.RTCPeerConnection) {
+ failRtc("unsupported", false);
+ return;
+ }
+ configPending = true;
+ deadlineTimer = setTimeout(() => {
+ if (g === generation && configPending) {
+ configPending = false;
+ void startRtc(g, iceServers);
+ }
+ }, 3500);
+ return post({ type: "iceConfig", attemptId });
+ }
+ async function receiveIceConfig(message) {
+ if (!epoch || !configPending || message.attemptId !== attemptId) return;
+ configPending = false;
+ clearTimeout(deadlineTimer);
+ deadlineTimer = null;
+ await startRtc(generation, message.iceServers);
+ }
+ async function startRtc(g, servers) {
+ try {
+ const rtc = new RTCPeerConnection({ iceServers: servers });
+ pc = rtc;
+ dc = rtc.createDataChannel("input-v1");
+ rtc.addTransceiver("video", { direction: "recvonly" });
+ rtc.addTransceiver("audio", { direction: "recvonly" });
+ rtc.onicecandidate = ({ candidate }) => {
+ if (g !== generation || !candidate?.candidate || !trickleIce) return;
+ if (localCandidates.length >= net.maxCandidates) {
+ failRtc("candidate-limit", false);
+ return;
+ }
+ localCandidates.push({
+ candidate: candidate.candidate,
+ sdpMid: candidate.sdpMid,
+ sdpMLineIndex: candidate.sdpMLineIndex,
+ ...(candidate.usernameFragment
+ ? { usernameFragment: candidate.usernameFragment }
+ : {}),
+ });
+ // Gathering continues after the offer; the serial exchange flushes late addresses.
+ };
+ dc.onmessage = (e) => {
+ try {
+ if (g !== generation || pc !== rtc) return;
+ if (typeof e.data !== "string" || e.data.length > 80000) return;
+ const message = JSON.parse(e.data);
+ if (message.type === "cursor") receiveCursor(message.cursor);
+ if (
+ (video.webkitPresentationMode === "picture-in-picture" ||
+ document.pictureInPictureElement === video) &&
+ message.type === "viewPing" &&
+ typeof message.challenge === "string" &&
+ message.challenge.length <= 64 &&
+ dc?.readyState === "open"
+ )
+ dc.send(message.challenge);
+ } catch {}
+ };
+ let readingStats = false;
+ statsTimer = setInterval(async () => {
+ if (readingStats || g !== generation) return;
+ readingStats = true;
+ try {
+ const stats = await rtc.getStats();
+ if (g !== generation || pc !== rtc) return;
+ const result = networkStats(stats, statsSample);
+ statsSample = result.sample;
+ post({
+ type: "network",
+ transport: result.transport,
+ bytesPerSecond: result.bytesPerSecond,
+ latencyMs: result.latencyMs,
+ });
+ } catch {
+ } finally {
+ readingStats = false;
+ }
+ }, 1000);
+ rtc.ontrack = (e) => {
+ if (g !== generation) return;
+ video.srcObject = e.streams[0] || new MediaStream([e.track]);
+ video.play().catch(() => {});
+ };
+ video.onplaying = () => {
+ if (
+ g !== generation ||
+ videoPresented ||
+ videoFrameCallback !== null ||
+ videoPaintCallback !== null
+ )
+ return;
+ video.style.display = "block";
+ render();
+ if (typeof video.requestVideoFrameCallback === "function") {
+ videoFrameCallback = video.requestVideoFrameCallback(() => {
+ if (g !== generation) return;
+ videoFrameCallback = null;
+ revealVideo(g);
+ });
+ } else waitForVideoFrame(g);
+ };
+ rtc.onconnectionstatechange = () => {
+ if (g !== generation) return;
+ if (["failed", "closed"].includes(rtc.connectionState)) {
+ failRtc("transport");
+ return;
+ }
+ if (rtc.connectionState === "disconnected") {
+ clearTimeout(stableTimer);
+ stableTimer = null;
+ if (!disconnectTimer) {
+ release();
+ post({ type: "reconnecting", attemptId });
+ disconnectTimer = setTimeout(() => {
+ if (g === generation) failRtc("disconnected");
+ }, net.disconnectedMs);
+ }
+ } else if (rtc.connectionState === "connected") {
+ clearTimeout(disconnectTimer);
+ disconnectTimer = null;
+ clearTimeout(deadlineTimer);
+ if (!stableTimer)
+ stableTimer = setTimeout(() => {
+ if (g === generation) retries = 0;
+ }, net.stableMs);
+ if (videoPresented) post({ type: "streaming", attemptId });
+ }
+ };
+ await rtc.setLocalDescription(await rtc.createOffer());
+ if (!trickleIce)
+ await new Promise((resolve) => {
+ if (rtc.iceGatheringState === "complete") return resolve();
+ gatherDone = resolve;
+ gatherTimer = setTimeout(resolve, net.legacyGatherMs);
+ rtc.onicegatheringstatechange = () => {
+ if (rtc.iceGatheringState === "complete") {
+ clearTimeout(gatherTimer);
+ resolve();
+ }
+ };
+ });
+ if (g !== generation) return;
+ post({ type: "offer", attemptId, sdp: rtc.localDescription.sdp });
+ deadlineTimer = setTimeout(() => {
+ if (g === generation) failRtc("answer-timeout");
+ }, net.answerMs);
+ } catch {
+ if (g === generation) failRtc("setup");
+ }
+ }
+
+ /* END RTC */
+ function reportPresentation() {
+ post({
+ type: "presentation",
+ active:
+ video.webkitPresentationMode === "picture-in-picture" ||
+ document.pictureInPictureElement === video,
+ });
+ }
+ listen(video, "webkitpresentationmodechanged", reportPresentation);
+ listen(video, "enterpictureinpicture", reportPresentation);
+ listen(video, "leavepictureinpicture", reportPresentation);
+ function receive(event) {
+ let message;
+ try {
+ message = JSON.parse(event.data);
+ } catch {
+ return;
+ }
+ switch (message.type) {
+ case "presentation":
+ try {
+ if (message.enabled) {
+ release();
+ showKeyboard(false);
+ if (video.webkitSupportsPresentationMode?.("picture-in-picture"))
+ video.webkitSetPresentationMode("picture-in-picture");
+ else if (video.requestPictureInPicture)
+ video
+ .requestPictureInPicture()
+ .catch(() => post({ type: "presentationFailed" }));
+ else post({ type: "presentationFailed" });
+ } else if (video.webkitSetPresentationMode)
+ video.webkitSetPresentationMode("inline");
+ else if (document.pictureInPictureElement)
+ document.exitPictureInPicture().catch(() => {});
+ } catch {
+ post({ type: "presentationFailed" });
+ }
+ break;
+ case "videoSettings":
+ video.muted = !message.audio;
+ retries = 0;
+ connect();
+ break;
+ case "keyboard":
+ showKeyboard(message.enabled === true);
+ break;
+ case "resume":
+ if (video.srcObject) video.play().catch(() => {});
+ break;
+ case "releaseInput":
+ release();
+ break;
+ case "theme":
+ if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {
+ document.body.style.background = message.surface;
+ document.documentElement.style.background = message.surface;
+ document.documentElement.style.setProperty(
+ "--surface",
+ message.surface,
+ );
+ }
+ if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {
+ cursor.style.borderColor = message.foreground;
+ document.documentElement.style.setProperty(
+ "--foreground",
+ message.foreground,
+ );
+ }
+ break;
+ case "mouseButtons":
+ if (Number.isFinite(message.bottomInset))
+ viewportBottomInset = Math.max(
+ 0,
+ Math.min(stage.clientHeight - 1, message.bottomInset),
+ );
+ if (Number.isFinite(message.leftInset)) {
+ const left = Math.max(
+ 0,
+ Math.min(stage.clientWidth - 1, message.leftInset),
+ );
+ if (left !== viewportLeftInset) {
+ viewportLeftInset = left;
+ settlePan();
+ render();
+ }
+ }
+ if (Number.isFinite(message.rightInset)) {
+ const inset = Math.max(
+ 0,
+ Math.min(stage.clientWidth - 1, message.rightInset),
+ );
+ if (inset !== viewportRightInset) {
+ viewportRightInset = inset;
+ settlePan();
+ render();
+ }
+ }
+ const keyboardInset =
+ fillHeight && message.keyboardOpen === true ? viewportBottomInset : 0;
+ if (keyboardInset !== keyboardViewportInset) {
+ const wasOpen = keyboardViewportInset > 0;
+ keyboardViewportInset = keyboardInset;
+ if (fillHeight && (keyboardInset > 0 || wasOpen)) {
+ stopPanAnimation();
+ const r = layout(),
+ v = cursorViewport();
+ place(
+ (v.minX + v.maxX) / 2 - cx * r.width,
+ (v.minY + v.maxY) / 2 - cy * r.height,
+ r,
+ );
+ followRest = { fx, fy, zoom };
+ cursorNeedsEntry = false;
+ manualViewMoved = false;
+ render();
+ }
+ }
+ if (!message.enabled) {
+ for (const button of heldMouse.keys())
+ queue({ kind: "button", button, down: false, x: cx, y: cy });
+ heldMouse.clear();
+ resetWheel();
+ flush();
+ }
+ for (const [edge, value] of [
+ ["bottom", message.bottomInset],
+ ["right", message.rightInset],
+ ])
+ if (Number.isFinite(value) && value >= 0 && value <= 4096)
+ mouseButtons.style[edge] = value + "px";
+ showMouseButtons = message.enabled === true;
+ for (const name of ["left", "right", "wheel"])
+ if (typeof message.labels?.[name] === "string")
+ find("mouse-" + name).setAttribute(
+ "aria-label",
+ message.labels[name],
+ );
+ updateMouseButtons();
+ break;
+ case "init":
+ followRest = null;
+ cursorNeedsEntry = true;
+ stopPanAnimation();
+ resetCursor();
+ control = false;
+ release();
+ pending = [];
+ sending = false;
+ seq = 0;
+ epoch = message.epoch;
+ dw = message.width;
+ dh = message.height;
+ fillHeight = message.fillHeight === true;
+ video.muted = !message.audio;
+ trickleIce = message.trickleIce === true;
+ retries = 0;
+ render();
+ connect();
+ break;
+ case "viewport":
+ fillHeight = message.fillHeight === true;
+ release();
+ render();
+ break;
+ case "answer":
+ if (message.epoch === epoch) void receiveAnswer(message);
+ break;
+ case "iceConfig":
+ if (message.epoch === epoch) void receiveIceConfig(message);
+ break;
+ case "ice":
+ if (message.epoch === epoch) void receiveIce(message);
+ break;
+ case "fallback":
+ if (message.epoch === epoch && message.attemptId === attemptId)
+ failRtc("host", message.retry !== false);
+ break;
+ case "frame": {
+ if ("cursor" in message) receiveCursor(message.cursor);
+ else resetCursor();
+ const frameEpoch = epoch;
+ image.onload = () => {
+ if (epoch === frameEpoch) post({ type: "framePresented" });
+ };
+ image.src = "data:image/jpeg;base64," + message.jpeg;
+ break;
+ }
+ case "control":
+ release();
+ control = message.enabled;
+ if (!control) showKeyboard(false);
+ pending = [];
+ updateMouseButtons();
+ render();
+ break;
+ case "mode":
+ release();
+ if (message.mode !== "pointer") followRest = null;
+ settlePan();
+ clearTimeout(touchCursorTimer);
+ touchCursorVisible = false;
+ mode = message.mode;
+ render();
+ break;
+ case "fit":
+ followRest = null;
+ cursorNeedsEntry = true;
+ manualViewMoved = false;
+ stopPanAnimation();
+ zoom = 1;
+ fx = 0.5;
+ fy = 0.5;
+ render();
+ break;
+ case "rightClick":
+ click(2);
+ break;
+ case "events":
+ for (const e of message.events) queue(e);
+ flush();
+ break;
+ case "ack":
+ if (message.epoch === epoch && message.sequence === seq)
+ sending = false;
+ break;
+ case "stop":
+ showKeyboard(false);
+ control = false;
+ release();
+ pending = [];
+ sending = false;
+ epoch = null;
+ closeRtc(message.preserveFrame === true);
+ updateMouseButtons();
+ render();
+ break;
+ }
+ }
+ render();
+ post({ type: "ready" });
+ return {
+ receive: (message) => receive({ data: JSON.stringify(message) }),
+ dispose: () => {
+ release();
+ epoch = null;
+ closeRtc(false);
+ for (const cleanup of cleanups) cleanup();
+ },
+ };
+}
diff --git a/packages/maker-shared/src/remote-desktop/viewerScripts.ts b/packages/maker-shared/src/remote-desktop/viewerScripts.ts
new file mode 100644
index 0000000000..281210dfd7
--- /dev/null
+++ b/packages/maker-shared/src/remote-desktop/viewerScripts.ts
@@ -0,0 +1,4 @@
+// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.
+export const DESKTOP_RTC_SCRIPT = "let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (!preserveFrame) image.removeAttribute(\"src\");\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n if (canRetry && epoch && retries < net.retryMs.length) {\n const delay = net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n }, 3500);\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }";
+export const DESKTOP_TRANSFORM_SCRIPT = "function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const scale =\n (fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *\n Math.max(1, Math.min(5, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale };\n }";
+export const DESKTOP_NETWORK_STATS_SCRIPT = "function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n }";
diff --git a/packages/maker-shared/src/remote-desktop/viewerSource.ts b/packages/maker-shared/src/remote-desktop/viewerSource.ts
new file mode 100644
index 0000000000..7d64985a57
--- /dev/null
+++ b/packages/maker-shared/src/remote-desktop/viewerSource.ts
@@ -0,0 +1,2 @@
+// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.
+export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const scale =\n (fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *\n Math.max(1, Math.min(5, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale };\n };\n /* END TRANSFORM */ const networkStats =\n /* BEGIN NETWORK_STATS */\n function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n };\n\n /* END NETWORK_STATS */ const stage = find(\"stage\"),\n image = find(\"image\"),\n video = find(\"video\"),\n cursor = find(\"cursor\");\n let dw = 1920,\n dh = 1080,\n zoom = 1,\n fx = 0.5,\n fy = 0.5,\n mode = \"pointer\",\n control = false,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n sending = false,\n cx = 0.5,\n cy = 0.5,\n drag = false,\n start = null,\n last = null,\n multi = null,\n hold = null,\n moved = false;\n const pointers = new Map();\n const mouseButtons = find(\"mouse-buttons\"),\n wheel = find(\"mouse-wheel\"),\n wheelGrip = find(\"mouse-wheel-grip\");\n const keyboardInput = find(\"keyboard-input\");\n let keyboardEnabled = false,\n composing = false;\n const keyboardSentinel = \"\\u200b\";\n function resetKeyboard() {\n keyboardInput.value = keyboardSentinel;\n keyboardInput.setSelectionRange(1, 1);\n }\n function showKeyboard(enabled) {\n keyboardEnabled = enabled && control;\n if (!keyboardEnabled) {\n composing = false;\n resetKeyboard();\n keyboardInput.blur();\n return;\n }\n if (composing) return;\n // Keep focus inside the native evaluateJavaScript call; WebKit can reject\n // keyboard presentation after requestAnimationFrame loses user activation.\n keyboardInput.blur();\n resetKeyboard();\n keyboardInput.focus({ preventScroll: true });\n }\n function keyboardKey(code) {\n if (!keyboardEnabled || !control) return;\n queue({ kind: \"key\", code, down: true });\n queue({ kind: \"key\", code, down: false });\n flush();\n }\n function commitKeyboard() {\n if (!keyboardEnabled || !control || composing) return;\n const text = keyboardInput.value.replace(keyboardSentinel, \"\");\n if (text) {\n for (let i = 0; i < text.length; i += 4096)\n queue({ kind: \"text\", text: text.slice(i, i + 4096) });\n flush();\n }\n resetKeyboard();\n }\n listen(keyboardInput, \"compositionstart\", () => {\n composing = true;\n });\n listen(keyboardInput, \"compositionend\", () => {\n composing = false;\n commitKeyboard();\n });\n listen(keyboardInput, \"input\", (e) => {\n if (!e.isComposing) commitKeyboard();\n });\n listen(keyboardInput, \"beforeinput\", (e) => {\n if (composing || e.isComposing) return;\n if (e.inputType === \"deleteContentBackward\") {\n e.preventDefault();\n keyboardKey(\"Backspace\");\n resetKeyboard();\n } else if (\n e.inputType === \"insertLineBreak\" ||\n e.inputType === \"insertParagraph\"\n ) {\n e.preventDefault();\n keyboardKey(\"Enter\");\n resetKeyboard();\n }\n });\n const heldMouse = new Map();\n let showMouseButtons = false,\n wheelY = null;\n function resetWheel() {\n wheelY = null;\n wheelGrip.style.transform = \"translateY(0px)\";\n }\n let statsTimer = null,\n statsSample = null;\n const post = (message) => postMessage({ ...message, epoch });\n const clamp = (v) => Math.max(0, Math.min(1, v));\n let fillHeight = false;\n let panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n keyboardViewportInset = 0;\n let cursorNeedsEntry = true,\n manualViewMoved = false,\n followRest = null;\n // Insets guide centering and pan limits without clipping the full-screen\n // video surface or adding an opaque strip beside the Dynamic Island.\n const viewportLeft = () => (fillHeight ? viewportLeftInset : 0);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n const layout = () => {\n const r = transform(\n viewportWidth(),\n stage.clientHeight,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight,\n );\n return {\n ...r,\n x: viewportLeft() + viewportWidth() / 2 - fx * r.width,\n y: stage.clientHeight / 2 - fy * r.height,\n };\n };\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = stage.clientHeight;\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (Math.max(1, Math.min(5, zoom)) - 1)) / 4;\n const axis = (viewport, content) =>\n content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min,\n maxY: y.max,\n };\n // A camera position required to expose the cursor is a valid resting point,\n // not elastic overshoot. Preserve it across the next pan/pinch handoff.\n if (followRest) {\n const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,\n restY = vh / 2 - followRest.fy * r.height;\n const weight =\n followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;\n bounds.minX += Math.min(0, restX - bounds.minX) * weight;\n bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;\n bounds.minY += Math.min(0, restY - bounds.minY) * weight;\n bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;\n }\n return bounds;\n }\n const bounded = (v, min, max) => Math.max(min, Math.min(max, v));\n // Convert displayed overshoot back to finger travel before the next delta,\n // so reversing direction unwinds smoothly without an edge jump.\n function rubber(v, min, max, inverse = false) {\n const edge = bounded(v, min, max),\n d = v - edge;\n const reach = 40 + 10 * (Math.max(1, Math.min(5, zoom)) - 1);\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (stage.clientHeight / 2 - y) / r.height;\n }\n function cursorViewport() {\n const hotX = remoteCursor?.hotX ?? 9,\n hotY = remoteCursor?.hotY ?? 9;\n const w = remoteCursor?.width ?? 18,\n h = remoteCursor?.height ?? 18;\n const left = viewportLeft(),\n right = left + viewportWidth(),\n bottom = Math.max(1, stage.clientHeight - viewportBottomInset);\n // Keep the entire cursor, including its hotspot offset, clear of chrome.\n const minX = Math.min(right - 1, left + 8 + hotX),\n minY = Math.min(bottom - 1, 8 + hotY);\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n const touchFeedback = control && mode === \"touch\" && touchCursorVisible;\n const cursorX = mode === \"touch\" && touchCursor ? touchCursor.x : cx;\n const cursorY = mode === \"touch\" && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n mode === \"touch\" && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n if (remoteCursor) {\n cursor.style.width = remoteCursor.width + \"px\";\n cursor.style.height = remoteCursor.height + \"px\";\n cursor.style.border = \"0\";\n cursor.style.borderRadius = \"0\";\n cursor.style.transform = \"none\";\n cursor.style.left = r.x + cursorX * r.width - remoteCursor.hotX + \"px\";\n cursor.style.top = r.y + cursorY * r.height - remoteCursor.hotY + \"px\";\n cursor.style.display = \"block\";\n cursor.style.opacity = (\n mode === \"touch\"\n ? touchFeedback\n : remoteCursor.visible ||\n (control && mode === \"pointer\" && localCursorAwake)\n )\n ? \"1\"\n : \"0\";\n } else {\n cursor.style.opacity = (mode === \"touch\" ? !touchFeedback : false)\n ? \"0\"\n : \"1\";\n cursor.style.width = \"18px\";\n cursor.style.height = \"18px\";\n cursor.style.border = \"2px solid var(--foreground)\";\n cursor.style.borderRadius = \"50%\";\n cursor.style.transform = \"translate(-50%,-50%)\";\n cursor.style.left = r.x + cursorX * r.width + \"px\";\n cursor.style.top = r.y + cursorY * r.height + \"px\";\n cursor.style.display =\n !config.desktop && control && (mode === \"pointer\" || mode === \"touch\") ? \"block\" : \"none\";\n }\n if (config.desktop) stage.style.cursor = control && remoteCursor?.visible ? \"none\" : \"default\";\n }\n // Literal source is required: Hermes function.toString() yields bytecode.\n function validCursor(v) {\n return (\n !!v &&\n typeof v === \"object\" &&\n typeof v.visible === \"boolean\" &&\n [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&\n v.x >= 0 &&\n v.x <= 1 &&\n v.y >= 0 &&\n v.y <= 1 &&\n v.width > 0 &&\n v.width <= 256 &&\n v.height > 0 &&\n v.height <= 256 &&\n v.hotX >= 0 &&\n v.hotX <= v.width &&\n v.hotY >= 0 &&\n v.hotY <= v.height &&\n typeof v.png === \"string\" &&\n v.png.length <= 65536 &&\n /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png)\n );\n }\n function receiveCursor(value) {\n if (value === null) {\n if (remoteCursor) {\n remoteCursor = { ...remoteCursor, visible: false };\n render();\n }\n return;\n }\n if (!validCursor(value)) return;\n if (!remoteCursor || remoteCursor.png !== value.png)\n cursorImage.src = \"data:image/png;base64,\" + value.png;\n // Keep delayed host coordinates from pulling the local touchpad backwards.\n if (\n !remoteCursor ||\n !control ||\n mode !== \"pointer\" ||\n (!pointers.size && performance.now() - lastLocalMove > 200)\n ) {\n cx = value.x;\n cy = value.y;\n }\n if (value.visible) localCursorAwake = false;\n remoteCursor = value;\n render();\n }\n function resetCursor() {\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n touchCursor = null;\n localCursorAwake = false;\n remoteCursor = null;\n cursorImage.removeAttribute(\"src\");\n render();\n }\n function queue(event) {\n if (!control) return;\n // Remote visibility can remain hidden after synthetic mouse movement. Wake\n // the local touchpad cursor until the host reports a visible cursor again.\n if (event.kind === \"move\" && mode === \"pointer\") localCursorAwake = true;\n if (event.kind === \"key\" || event.kind === \"text\") {\n localCursorAwake = false;\n render();\n }\n if (event.kind === \"move\" || event.kind === \"button\")\n lastLocalMove = performance.now();\n const tail = pending[pending.length - 1];\n if (event.kind === \"move\" && tail?.kind === \"move\")\n pending[pending.length - 1] = event;\n // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the\n // accumulated distance so a delayed ACK cannot replay a large scroll backlog.\n else if (event.kind === \"scroll\" && tail?.kind === \"scroll\") {\n tail.dx = Math.max(-2000, Math.min(2000, tail.dx + event.dx));\n tail.dy = Math.max(-2000, Math.min(2000, tail.dy + event.dy));\n } else pending.push(event);\n if (pending.length > 64) {\n pending = [{ kind: \"release\" }];\n control = false;\n post({ type: \"inputOverflow\" });\n }\n }\n function flush() {\n if (!pending.length || sending) return;\n const events = pending.splice(0, 64),\n sequence = ++seq;\n if (\n pc?.connectionState === \"connected\" &&\n dc &&\n dc.readyState === \"open\" &&\n dc.bufferedAmount < 16384\n ) {\n dc.send(JSON.stringify({ sequence, events }));\n } else {\n sending = true;\n post({ type: \"input\", sequence, events });\n }\n }\n const inputTimer = setInterval(() => {\n // Hold displacement controls speed, even without further pointer moves.\n // Skip missed ticks while awaiting ACK instead of building a scroll backlog.\n if (wheelY?.moved && !sending) {\n const offset = Math.max(-24, Math.min(24, wheelY.y - wheelY.start));\n if (Math.abs(offset) > 4)\n scrollMouse(Math.sign(offset) * (Math.abs(offset) - 4) * 1.5);\n }\n flush();\n }, 33);\n cleanups.push(() => clearInterval(inputTimer));\n function release() {\n clearTimeout(hold);\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n if (control) {\n queue({ kind: \"release\" });\n flush();\n }\n heldMouse.clear();\n resetWheel();\n updateMouseButtons();\n drag = false;\n pointers.clear();\n start = null;\n last = null;\n multi = null;\n }\n function updateMouseButtons() {\n mouseButtons.style.display = showMouseButtons && control ? \"block\" : \"none\";\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ])\n find(\"mouse-\" + name).setAttribute(\n \"aria-pressed\",\n String(heldMouse.has(button)),\n );\n }\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ]) {\n const el = find(\"mouse-\" + name);\n listen(el, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || heldMouse.has(button)) return;\n clearTimeout(hold);\n el.setPointerCapture(e.pointerId);\n heldMouse.set(button, e.pointerId);\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n flush();\n updateMouseButtons();\n });\n const up = (e) => {\n e.preventDefault();\n if (heldMouse.get(button) !== e.pointerId) return;\n heldMouse.delete(button);\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n flush();\n updateMouseButtons();\n };\n listen(el, \"pointerup\", up);\n listen(el, \"pointercancel\", up);\n listen(el, \"lostpointercapture\", up);\n listen(el, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(button);\n flush();\n }\n });\n }\n const scrollMouse = (dy) => {\n if (control && showMouseButtons && Number.isFinite(dy)) {\n queue({ kind: \"scroll\", dx: 0, dy: Math.max(-2000, Math.min(2000, dy)) });\n }\n };\n listen(wheel, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || wheelY) return;\n wheel.setPointerCapture(e.pointerId);\n wheelY = { id: e.pointerId, y: e.clientY, start: e.clientY, moved: false };\n });\n // A small dead zone preserves middle clicks; displacement drives the timer.\n listen(wheel, \"pointermove\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n wheelGrip.style.transform =\n \"translateY(\" +\n Math.max(-24, Math.min(24, e.clientY - wheelY.start)) +\n \"px)\";\n wheelY.y = e.clientY;\n if (Math.abs(e.clientY - wheelY.start) > 4) wheelY.moved = true;\n });\n listen(wheel, \"pointerup\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n if (!wheelY.moved && control && showMouseButtons) {\n click(1);\n flush();\n }\n resetWheel();\n });\n const cancelWheel = (e) => {\n if (wheelY?.id === e.pointerId) resetWheel();\n };\n listen(wheel, \"pointercancel\", cancelWheel);\n listen(wheel, \"lostpointercapture\", cancelWheel);\n listen(wheel, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(1);\n flush();\n }\n });\n listen(wheel, \"keydown\", (e) => {\n if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n e.preventDefault();\n scrollMouse(e.key === \"ArrowUp\" ? -120 : 120);\n }\n });\n function insideDesktop(p) {\n const r = layout();\n return (\n p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height\n );\n }\n function point(p) {\n const r = layout();\n return {\n x: clamp((p.x - r.x) / r.width),\n y: clamp((p.y - r.y) / r.height),\n };\n }\n const desktopPoint = (e) => {\n const bounds = stage.getBoundingClientRect();\n return { x: e.clientX - bounds.left, y: e.clientY - bounds.top };\n };\n function mouse(e, down) {\n if (!control || ![0, 1, 2].includes(e.button)) return;\n const local = desktopPoint(e);\n if (down && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n if (down) {\n showKeyboard(true);\n stage.setPointerCapture(e.pointerId);\n heldMouse.set(e.button, e.pointerId);\n } else if (!heldMouse.delete(e.button)) return;\n queue({ kind: \"button\", button: e.button, down, x: cx, y: cy });\n flush();\n render();\n }\n function click(button = 0) {\n if (control && mode === \"touch\") {\n clearTimeout(touchCursorTimer);\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n touchCursorTimer = setTimeout(() => {\n touchCursorVisible = false;\n render();\n }, 450);\n }\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n }\n function pan(dx, dy) {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r);\n place(\n rubber(rubber(r.x, b.minX, b.maxX, true) + dx, b.minX, b.maxX),\n rubber(rubber(r.y, b.minY, b.maxY, true) + dy, b.minY, b.maxY),\n r,\n );\n render();\n }\n function pair() {\n const [a, b] = [...pointers.values()];\n return {\n x: (a.x + b.x) / 2,\n y: (a.y + b.y) / 2,\n d: Math.hypot(a.x - b.x, a.y - b.y),\n };\n }\n function movePair() {\n gestureFrame = null;\n if (pointers.size < 2 || !multi) return;\n const next = pair(),\n span = Math.abs(next.d - multi.d),\n travel = Math.hypot(next.x - multi.x, next.y - multi.y);\n if (multi.kind !== \"pinch\") {\n const pinchSlop = Math.max(6, Math.min(12, multi.d * 0.04));\n if (span >= pinchSlop && span > travel * 0.65) {\n // A parallel scroll may deliver its two pointer updates in different\n // frames. Confirm separation briefly before taking over as a pinch.\n if (!multi.candidate)\n multi.candidate = {\n at: Date.now(),\n d: next.d,\n zoom,\n anchor: point(next),\n };\n if (Date.now() - multi.candidate.at >= 40) {\n if (multi.kind === \"scroll\") {\n multi.d = multi.candidate.d;\n multi.zoom = multi.candidate.zoom;\n multi.anchor = multi.candidate.anchor;\n }\n multi.kind = \"pinch\";\n multi.candidate = null;\n } else {\n gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n } else {\n multi.candidate = null;\n if (!multi.kind && travel > 8 && travel > span) multi.kind = \"scroll\";\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n zoom = Math.max(\n 1,\n Math.min(5, (multi.zoom * next.d) / Math.max(1, multi.d)),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy = multi.anchor.y + (stage.clientHeight / 2 - next.y) / r.height;\n const moved = layout(),\n b = panBounds(moved);\n place(\n rubber(moved.x, b.minX, b.maxX),\n rubber(moved.y, b.minY, b.maxY),\n moved,\n );\n } else if (multi.kind === \"scroll\") {\n const dx = next.x - multi.lastX,\n dy = next.y - multi.lastY;\n if (control && mode !== \"pan\")\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, -dx)),\n dy: Math.max(-2000, Math.min(2000, -dy)),\n });\n else pan(dx, dy);\n }\n if (multi.kind) {\n multi.lastX = next.x;\n multi.lastY = next.y;\n }\n render();\n }\n listen(stage, \"pointerdown\", (e) => {\n if (config.desktop) {\n e.preventDefault();\n mouse(e, true);\n return;\n }\n e.preventDefault();\n stopPanAnimation();\n stage.setPointerCapture(e.pointerId);\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size === 1) {\n cursorNeedsEntry = true;\n start = { x: e.clientX, y: e.clientY };\n last = start;\n moved = false;\n hold = setTimeout(() => {\n if (\n control &&\n mode !== \"pan\" &&\n !moved &&\n pointers.size === 1 &&\n !heldMouse.size &&\n (mode !== \"touch\" || insideDesktop(start))\n ) {\n if (mode === \"touch\") {\n const p = point(start);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"button\", button: 0, down: true, x: cx, y: cy });\n drag = true;\n }\n }, 400);\n } else {\n clearTimeout(hold);\n if (drag) queue({ kind: \"release\" });\n drag = false;\n start = null;\n const p = pair();\n multi = {\n ...p,\n lastX: p.x,\n lastY: p.y,\n zoom,\n anchor: point(p),\n kind: null,\n };\n }\n });\n listen(stage, \"pointermove\", (e) => {\n if (config.desktop) {\n if (!control) return;\n const local = desktopPoint(e);\n if (!heldMouse.size && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n e.preventDefault();\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size >= 2) {\n if (gestureFrame === null) gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n if (!start || !last) return;\n const now = { x: e.clientX, y: e.clientY },\n dx = now.x - last.x,\n dy = now.y - last.y;\n last = now;\n if (Math.hypot(now.x - start.x, now.y - start.y) > 6) {\n moved = true;\n clearTimeout(hold);\n }\n if (\n !control ||\n mode === \"pan\" ||\n (mode === \"touch\" && !drag && !heldMouse.size)\n ) {\n pan(dx, dy);\n return;\n }\n if (mode === \"pointer\") {\n moveTouchpad(dx, dy);\n } else {\n const p = point(now);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n });\n function up(e) {\n if (config.desktop) {\n mouse(e, false);\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n clearTimeout(hold);\n if (pointers.size >= 2 && multi) {\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n movePair();\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n }\n pointers.delete(e.pointerId);\n if (drag) {\n queue({ kind: \"button\", button: 0, down: false, x: cx, y: cy });\n drag = false;\n } else if (\n start &&\n !moved &&\n control &&\n mode !== \"pan\" &&\n !heldMouse.size &&\n e.type === \"pointerup\" &&\n (mode !== \"touch\" || insideDesktop({ x: e.clientX, y: e.clientY }))\n ) {\n if (mode === \"touch\") {\n const p = point({ x: e.clientX, y: e.clientY });\n cx = p.x;\n cy = p.y;\n }\n click();\n }\n start = null;\n last = null;\n multi = null;\n render();\n if (!pointers.size && manualViewMoved) settlePan();\n }\n listen(stage, \"pointerup\", up);\n listen(stage, \"pointercancel\", () => {\n release();\n settlePan();\n });\n listen(stage, \"lostpointercapture\", () => {\n if (config.desktop && heldMouse.size) release();\n });\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) return;\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, e.deltaX * factor)),\n dy: Math.max(-2000, Math.min(2000, e.deltaY * factor)),\n });\n flush();\n },\n { passive: false },\n );\n listen(config.desktop ? stage : document, \"contextmenu\", (e) =>\n e.preventDefault(),\n );\n // Scope selection suppression to the desktop surface, preserving the hidden\n // textarea's native keyboard/IME editing and programmatic selection.\n listen(stage, \"selectstart\", (e) => e.preventDefault());\n listen(stage, \"dragstart\", (e) => e.preventDefault());\n const normalizedKey = (code) =>\n /^(Shift|Control|Alt|Meta)Right$/.test(code)\n ? code.replace(/Right$/, \"Left\")\n : code;\n const hardwareKeys = new Set();\n listen(document, \"keydown\", (e) => {\n if (config.desktop) {\n if (e.ctrlKey && e.altKey && e.code === \"Escape\") {\n e.preventDefault();\n release();\n showKeyboard(false);\n post({ type: \"releaseFocus\" });\n return;\n }\n if (\n document.activeElement !== keyboardInput ||\n e.isComposing ||\n composing\n )\n return;\n if ((e.metaKey || e.ctrlKey) && e.code === \"KeyW\") return; // always retain a local close shortcut\n if (\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 || e.key === \"Process\" || e.key === \"Dead\")\n )\n return;\n }\n if (control && validKeys.has(normalizedKey(e.code))) {\n e.preventDefault();\n hardwareKeys.add(normalizedKey(e.code));\n queue({ kind: \"key\", code: normalizedKey(e.code), down: true });\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (config.desktop && !hardwareKeys.delete(code)) return;\n if (control && validKeys.has(code)) {\n e.preventDefault();\n queue({ kind: \"key\", code, down: false });\n }\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n hardwareKeys.clear();\n release();\n });\n listen(window, \"blur\", () => {\n release();\n settlePan();\n });\n const observer = new ResizeObserver(() => {\n release();\n settlePan();\n render();\n });\n observer.observe(stage);\n cleanups.push(\n () => observer.disconnect(),\n () => stopPanAnimation(),\n () => clearTimeout(touchCursorTimer),\n );\n // Keep one bounded frame in this document only; never persist desktop pixels.\n // Snapshot before detaching the track. A JPEG fallback already lives in image.\n function retainFrame() {\n if (\n !videoPresented ||\n video.style.display !== \"block\" ||\n video.readyState < 2 ||\n !video.videoWidth ||\n !video.videoHeight\n )\n return;\n const canvas = document.createElement(\"canvas\");\n try {\n const scale = Math.min(\n 1,\n 1280 / Math.max(video.videoWidth, video.videoHeight),\n );\n canvas.width = Math.max(1, Math.round(video.videoWidth * scale));\n canvas.height = Math.max(1, Math.round(video.videoHeight * scale));\n const context = canvas.getContext(\"2d\");\n if (context) {\n context.drawImage(video, 0, 0, canvas.width, canvas.height);\n image.src = canvas.toDataURL(\"image/jpeg\", 0.7);\n }\n } catch {\n /* Keep the previous compatibility frame if WebKit cannot read video. */\n } finally {\n canvas.width = 0;\n canvas.height = 0;\n }\n }\n /* BEGIN RTC */\n\n let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (!preserveFrame) image.removeAttribute(\"src\");\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n if (canRetry && epoch && retries < net.retryMs.length) {\n const delay = net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n }, 3500);\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n case \"presentation\":\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n video.muted = !message.audio;\n retries = 0;\n connect();\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = message.surface;\n document.documentElement.style.background = message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"mouseButtons\":\n if (Number.isFinite(message.bottomInset))\n viewportBottomInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.bottomInset),\n );\n if (Number.isFinite(message.leftInset)) {\n const left = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n if (left !== viewportLeftInset) {\n viewportLeftInset = left;\n settlePan();\n render();\n }\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n if (inset !== viewportRightInset) {\n viewportRightInset = inset;\n settlePan();\n render();\n }\n }\n const keyboardInset =\n fillHeight && message.keyboardOpen === true ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n place(\n (v.minX + v.maxX) / 2 - cx * r.width,\n (v.minY + v.maxY) / 2 - cy * r.height,\n r,\n );\n followRest = { fx, fy, zoom };\n cursorNeedsEntry = false;\n manualViewMoved = false;\n render();\n }\n }\n if (!message.enabled) {\n for (const button of heldMouse.keys())\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n heldMouse.clear();\n resetWheel();\n flush();\n }\n for (const [edge, value] of [\n [\"bottom\", message.bottomInset],\n [\"right\", message.rightInset],\n ])\n if (Number.isFinite(value) && value >= 0 && value <= 4096)\n mouseButtons.style[edge] = value + \"px\";\n showMouseButtons = message.enabled === true;\n for (const name of [\"left\", \"right\", \"wheel\"])\n if (typeof message.labels?.[name] === \"string\")\n find(\"mouse-\" + name).setAttribute(\n \"aria-label\",\n message.labels[name],\n );\n updateMouseButtons();\n break;\n case \"init\":\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n connect();\n break;\n case \"viewport\":\n fillHeight = message.fillHeight === true;\n release();\n render();\n break;\n case \"answer\":\n if (message.epoch === epoch) void receiveAnswer(message);\n break;\n case \"iceConfig\":\n if (message.epoch === epoch) void receiveIceConfig(message);\n break;\n case \"ice\":\n if (message.epoch === epoch) void receiveIce(message);\n break;\n case \"fallback\":\n if (message.epoch === epoch && message.attemptId === attemptId)\n failRtc(\"host\", message.retry !== false);\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) post({ type: \"framePresented\" });\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n updateMouseButtons();\n render();\n break;\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"fit\":\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n render();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";
diff --git a/scripts/__tests__/design-inventory.test.mjs b/scripts/__tests__/design-inventory.test.mjs
index 29b0b1035e..20d94a462e 100644
--- a/scripts/__tests__/design-inventory.test.mjs
+++ b/scripts/__tests__/design-inventory.test.mjs
@@ -58,7 +58,7 @@ test('DS-8: every desktop globals.css surface includes its generated token style
const { surfaces } = buildGeneratedSurfaces(ROOT);
const consumers = surfaces.filter(surface => surface.platform === 'desktop'
&& surface.styleSources.includes('apps/desktop/src/renderer/styles/globals.css'));
- assert.equal(consumers.length, 5);
+ assert.equal(consumers.length, 6);
for (const surface of consumers) {
assert.ok(surface.styleSources.includes('apps/desktop/src/renderer/styles/generated/tokens.css'), surface.id);
}
@@ -1016,6 +1016,7 @@ test('renderer 模块图入口双向核对: index.tsx 的参数→入口模块
const actualEntries = extractRendererEntries(fs.readFileSync(RENDERER_INDEX_PATH, 'utf8'));
// 与源码实况钉死:当前 3 个参数各自加载的入口模块。
assert.deepEqual(Object.fromEntries(actualEntries), {
+ remoteDesktopViewer: './remote-desktop-viewer-entry',
resourceUsageWindow: './resource-usage-entry',
sidebarWindow: './sidebar-window-entry',
ghostPanelWindow: './ghost-panel-window-entry',
diff --git a/scripts/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjs
index 20968c4d03..2a66941983 100644
--- a/scripts/shared/design-inventory.mjs
+++ b/scripts/shared/design-inventory.mjs
@@ -771,6 +771,23 @@ export function catalogSurfaces() {
routerPaths: [],
rendererEntryModules: { resourceUsageWindow: './resource-usage-entry' },
},
+ {
+ id: 'desktop.window.remote-desktop',
+ platform: 'desktop',
+ title: '远程桌面独立窗口',
+ productionEntry: '`?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx',
+ reachableComponents: ['RemoteDesktopViewerWindow'],
+ styleRoots: [
+ 'apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx',
+ 'apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx',
+ 'apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css',
+ 'apps/desktop/src/main/remote-desktop-viewer',
+ 'apps/desktop/src/renderer/styles/globals.css',
+ 'apps/desktop/src/renderer/styles/generated/tokens.css',
+ ],
+ routerPaths: [],
+ rendererEntryModules: { remoteDesktopViewer: './remote-desktop-viewer-entry' },
+ },
{
id: 'desktop.window.voice-overlay',
platform: 'desktop',
diff --git a/scripts/sync-remote-desktop-viewer.mjs b/scripts/sync-remote-desktop-viewer.mjs
new file mode 100644
index 0000000000..3c84ea1176
--- /dev/null
+++ b/scripts/sync-remote-desktop-viewer.mjs
@@ -0,0 +1,20 @@
+// Hermes does not retain function source. Generate its inline viewer from the
+// same static module that Electron imports, without runtime eval or new CSP rights.
+import fs from 'node:fs/promises';
+const root = new URL('../packages/maker-shared/src/remote-desktop/', import.meta.url);
+const source = (await fs.readFile(new URL('viewerRuntime.js', root), 'utf8')).replace(/\r\n/g, '\n');
+const result = '// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.\n' +
+ `export const DESKTOP_VIEWER_SOURCE = ${JSON.stringify(source.replace('export function', 'function'))};\n`;
+const target = new URL('viewerSource.ts', root);
+let scripts = '// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.\n';
+for (const name of ['RTC', 'TRANSFORM', 'NETWORK_STATS']) {
+ const match = source.match(new RegExp(`/\\* BEGIN ${name} \\*/([\\s\\S]*?)/\\* END ${name} \\*/`));
+ if (!match) throw new Error(`Missing shared viewer ${name} source`);
+ const body = name === 'RTC' ? match[1].trim() : match[1].trim().replace(/;$/, '');
+ scripts += `export const DESKTOP_${name}_SCRIPT = ${JSON.stringify(body)};\n`;
+}
+for (const [url, content] of [[target,result],[new URL('viewerScripts.ts',root),scripts]]) {
+ if (process.argv.includes('--check')) {
+ if ((await fs.readFile(url, 'utf8')).replace(/\r\n/g, '\n') !== content) throw new Error('Run node scripts/sync-remote-desktop-viewer.mjs');
+ } else await fs.writeFile(url, content);
+}