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。

fix(remote-desktop): confirm exit and use clipboard shortcuts

Lizica21b98957a1
diff --git a/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs b/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs
index 682a770741..ff1038f384 100644
--- a/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs
+++ b/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs
@@ -21,7 +21,9 @@ try {
await host.goto(origin.origin);
await host.setContent('<canvas width="1280" height="720"></canvas>');
const errors = [];
- viewer.on('pageerror', (e) => errors.push(e.message));
+ viewer.on('pageerror', (error) => {
+ errors.push(error.message);
+ });
const requests = [];
let controlling = false;
await viewer.exposeFunction('viewerRequest', async (request) => {
@@ -113,6 +115,8 @@ try {
generation: 1,
active: true,
};
+ window.clipboardActions = [];
+ window.confirmedCloses = [];
window.electronAPI = {
platform: controllerPlatform,
preferredSystemLocale: 'en',
@@ -145,9 +149,14 @@ try {
request: (_generation, request) => window.viewerRequest(request),
ice: async () => [],
inputFocus: async () => {},
- close: async () => {},
+ close: async (generation) => {
+ window.confirmedCloses.push(generation);
+ },
+ onCloseRequested: () => () => {},
fullscreen: async () => {},
- clipboard: async () => {},
+ clipboard: async (_generation, action) => {
+ window.clipboardActions.push(action);
+ },
},
};
}, controllerPlatform);
@@ -160,6 +169,7 @@ try {
await viewer.waitForFunction(() => document.querySelector('.remote-viewer-network') !== null);
const stage = await viewer.locator('#stage').boundingBox();
assert(stage);
+ assert.equal(await viewer.locator('#stage').evaluate((element) => element.style.cursor), 'none');
await viewer.mouse.move(stage.x + 400, stage.y + 300);
await host.waitForFunction(() => window.inputs.some((event) => event.kind === 'move'));
await viewer.mouse.down();
@@ -222,13 +232,41 @@ try {
),
'menu keyboard navigation never reaches the remote computer',
);
+ const checkExitDialog = async (theme) => {
+ const labels = await viewer.evaluate(async () => {
+ const catalog = (await import('/i18n/index.ts')).default;
+ return {
+ exit: catalog.t('remoteDesktop.disconnect'),
+ cancel: catalog.t('commonUi.confirmDialog.cancel'),
+ };
+ });
+ await viewer.getByRole('button', { name: labels.exit, exact: true }).click();
+ const dialog = viewer.getByRole('alertdialog');
+ await dialog.waitFor();
+ assert.deepEqual(await viewer.evaluate(() => window.confirmedCloses), []);
+ await viewer.screenshot({
+ animations: 'disabled',
+ path: path.join(artifacts, 'exit-' + theme + '.png'),
+ });
+ await dialog.getByRole('button', { name: labels.cancel, exact: true }).click();
+ await dialog.waitFor({ state: 'hidden' });
+ assert.deepEqual(await viewer.evaluate(() => window.confirmedCloses), []);
+ };
await viewer.screenshot({ animations: 'disabled', path: path.join(artifacts, 'light.png') });
+ await checkExitDialog('light');
+ await viewer.locator('#stage').click();
+ const modifier = controllerPlatform === 'darwin' ? 'Meta' : 'Control';
+ await viewer.keyboard.press(modifier + '+c');
+ await viewer.keyboard.press(modifier + '+v');
+ await viewer.waitForFunction(() => window.clipboardActions.length === 2);
+ assert.deepEqual(await viewer.evaluate(() => window.clipboardActions), ['copy', 'paste']);
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({ animations: 'disabled', path: path.join(artifacts, 'dark.png') });
+ await checkExitDialog('dark');
await host.evaluate(() => window.peer.close());
await viewer.waitForFunction(
() =>
@@ -285,8 +323,8 @@ try {
(await import('/i18n/index.ts')).default.t('remoteDesktop.releaseControl'),
);
await viewer.getByRole('button', { name: releaseLabel, exact: true }).click();
- const copyButton = settings.getByRole('button', { name: '复制远端文字', exact: true });
- assert(await copyButton.isDisabled(), 'view-only actions explain why control is required');
+ const desktopButton = settings.getByRole('button', { name: '桌面', exact: true });
+ assert(await desktopButton.isDisabled(), 'view-only actions explain why control is required');
await settings.getByText('当前仅查看,取得控制权后可使用剪贴板和桌面操作。').waitFor();
const takeLabel = await viewer.evaluate(async () =>
(await import('/i18n/index.ts')).default.t('remoteDesktop.takeControl'),
@@ -294,7 +332,7 @@ try {
await settings.getByRole('button', { name: takeLabel, exact: true }).click();
await viewer.waitForFunction(() => {
const button = [...document.querySelectorAll('aside button')].find(
- (item) => item.textContent === '复制远端文字',
+ (item) => item.textContent === '桌面',
);
return button && !button.disabled;
});
@@ -368,6 +406,8 @@ try {
video: true,
keyboard: true,
mouse: true,
+ clipboardShortcuts: true,
+ exitConfirmation: true,
controllerPlatform,
mediaRecovery: true,
chineseSettings: true,
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
index 62d2b99d41..449c717499 100644
--- a/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.ts
+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.ts
@@ -95,6 +95,42 @@ afterEach(() => {
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('routes native close and the close shortcut to confirmation without ending the lease', () => {
+ const sender: any = { id: 100 };
+ manager = new RemoteDesktopViewerWindows((value) => value === sender);
+ manager.register();
+ manager.open(sender, { deviceId: 'a', name: 'A' });
+ const win = fixture.windows[0];
+ call(REMOTE_VIEWER.READY, win);
+ call(REMOTE_VIEWER.PRESENTED, win);
+ const state = call(REMOTE_VIEWER.STATE, win);
+ const preventDefault = vi.fn();
+ win.emit('close', { preventDefault });
+ win.webContents.emit(
+ 'before-input-event',
+ { preventDefault },
+ {
+ type: 'keyDown',
+ code: 'KeyW',
+ control: true,
+ },
+ );
+ expect(preventDefault).toHaveBeenCalledTimes(2);
+ expect(win.webContents.send).toHaveBeenCalledWith(
+ REMOTE_VIEWER.CLOSE_REQUESTED,
+ state.generation,
+ );
+ expect(win.isVisible()).toBe(true);
+ expect(call(REMOTE_VIEWER.STATE, win).active).toBe(true);
+ call(REMOTE_VIEWER.CLOSE, win, state.generation - 1);
+ expect(win.isVisible()).toBe(true);
+ call(REMOTE_VIEWER.CLOSE, win, state.generation);
+ expect(win.isVisible()).toBe(false);
+ manager.open(sender, { deviceId: 'a', name: 'A' });
+ call(REMOTE_VIEWER.CLOSE, win, state.generation);
+ expect(call(REMOTE_VIEWER.STATE, win).active).toBe(true);
+ expect(win.isVisible()).toBe(true);
+});
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);
@@ -118,7 +154,7 @@ it('prewarms without network or focus, reuses the target window and cleans only
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);
+ call(REMOTE_VIEWER.CLOSE, a, aState.generation);
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']);
diff --git a/apps/desktop/src/main/remote-desktop-viewer/windows.ts b/apps/desktop/src/main/remote-desktop-viewer/windows.ts
index 83b361fb85..eeb49de5b7 100644
--- a/apps/desktop/src/main/remote-desktop-viewer/windows.ts
+++ b/apps/desktop/src/main/remote-desktop-viewer/windows.ts
@@ -78,6 +78,15 @@ export class RemoteDesktopViewerWindows {
}
this.entries.clear();
}
+ private requestClose(entry: Entry): void {
+ const win = entry.window;
+ if (!win || win.isDestroyed()) return;
+ if (!entry.connection.active) {
+ entry.controller.close(win.webContents);
+ return;
+ }
+ win.webContents.send(REMOTE_VIEWER.CLOSE_REQUESTED, entry.connection.generation);
+ }
private create(): Entry {
const connection = new RemoteViewerConnection({
owner: activeOwnerScopeKey,
@@ -120,6 +129,7 @@ export class RemoteDesktopViewerWindows {
activityChannel: REMOTE_VIEWER.ACTIVE,
activityPayload: () => connection.snapshot(),
localeChannel: REMOTE_VIEWER.LOCALE,
+ onCloseRequested: () => this.requestClose(entry),
resolveNativeTitle: () =>
[connection.target?.name, t('remoteDesktop.title')].filter(Boolean).join(' · '),
onActivityChanged: (win, active) => {
@@ -148,7 +158,7 @@ export class RemoteDesktopViewerWindows {
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);
+ this.requestClose(entry);
}
});
return win;
@@ -180,8 +190,10 @@ export class RemoteDesktopViewerWindows {
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.CLOSE, (event, generation) => {
+ const entry = this.entry(event);
+ if (generation !== entry.connection.generation) return;
+ entry.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);
diff --git a/apps/desktop/src/main/resource-usage-window/controller.ts b/apps/desktop/src/main/resource-usage-window/controller.ts
index 9aaf0f3aee..7c62ba93c2 100644
--- a/apps/desktop/src/main/resource-usage-window/controller.ts
+++ b/apps/desktop/src/main/resource-usage-window/controller.ts
@@ -40,6 +40,7 @@ export interface ResourceUsageWindowControllerDeps {
localeChannel?: string;
prewarmWork?: boolean;
onActivityChanged?: (window: BrowserWindow, active: boolean) => void;
+ onCloseRequested?: (window: BrowserWindow) => void;
isOpenSender: (sender: WebContents) => boolean;
/** 打开监视器的那扇应用窗;用于跟随显隐并在关闭监视器后恢复焦点。 */
getOwnerWindow?: (sender: WebContents) => ResourceUsageOwnerWindow | null;
@@ -242,7 +243,8 @@ export class ResourceUsageWindowController {
win.on('close', (event) => {
if (this.destroyingWindow || this.disposed) return;
event.preventDefault();
- this.hideWindow(win);
+ if (this.deps.onCloseRequested) this.deps.onCloseRequested(win);
+ else this.hideWindow(win);
});
win.on('closed', () => this.onClosed(win));
win.on('show', () => this.onNativeVisibilityChanged(win, true));
diff --git a/apps/desktop/src/preload/remoteDesktopViewerPreload.ts b/apps/desktop/src/preload/remoteDesktopViewerPreload.ts
index dccc208a44..073a73eed8 100644
--- a/apps/desktop/src/preload/remoteDesktopViewerPreload.ts
+++ b/apps/desktop/src/preload/remoteDesktopViewerPreload.ts
@@ -83,12 +83,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
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),
+ close: (generation) => ipcRenderer.invoke(REMOTE_VIEWER.CLOSE, generation),
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),
+ onCloseRequested: (cb) => onPayload(REMOTE_VIEWER.CLOSE_REQUESTED, cb),
inputFocus: (generation, focused) =>
ipcRenderer.invoke(REMOTE_VIEWER.INPUT_FOCUS, generation, focused),
} satisfies RemoteDesktopViewerApi,
diff --git a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx
index ac49648300..e6d318a059 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx
+++ b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Maximize2,
@@ -8,7 +8,6 @@ import {
Settings2,
LogOut,
Monitor,
- Clipboard,
Eye,
MousePointer2,
} from 'lucide-react';
@@ -20,6 +19,7 @@ import { DesktopViewerController, type ViewerSnapshot } from './viewerController
import { Select } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { FormField } from '@/components/ui/form-field';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
/** A clean, standalone remote desktop surface. No App, router, agent or task providers. */
export function RemoteDesktopViewerWindow() {
@@ -32,20 +32,26 @@ export function RemoteDesktopViewerWindow() {
const [settings, setSettings] = useState(false),
[selectOpen, setSelectOpen] = useState(false),
[notice, setNotice] = useState<string | null>(null),
- [clipboardBusy, setClipboardBusy] = useState(false);
+ [closeGeneration, setCloseGeneration] = useState<number | null>(null);
const [modes, setModes] = useState<RemoteDesktopDisplayMode[]>([]);
const generation = useRef(-1);
+ const requestClose = useCallback(() => {
+ controller.current?.releaseInput();
+ setSettings(false);
+ setSelectOpen(false);
+ setCloseGeneration(generation.current);
+ }, []);
useEffect(() => {
if (!root.current) return;
controller.current = new DesktopViewerController(api, root.current, setState);
const off = api.onActive((value) => {
+ if (value.generation !== generation.current || !value.active) setCloseGeneration(null);
generation.current = value.generation;
if (!value.active) {
setSettings(false);
setSelectOpen(false);
setNotice(null);
setModes([]);
- setClipboardBusy(false);
(document.activeElement as HTMLElement | null)?.blur();
}
});
@@ -54,6 +60,9 @@ export function RemoteDesktopViewerWindow() {
// connection lifetime independent of that presentation-only update.
void i18n.changeLanguage(value);
});
+ const closeRequested = api.onCloseRequested((value) => {
+ if (value === generation.current) requestClose();
+ });
const blur = () => {
controller.current?.releaseInput();
void api.inputFocus(generation.current, false).catch(() => {});
@@ -79,26 +88,13 @@ export function RemoteDesktopViewerWindow() {
return () => {
off();
locale();
+ closeRequested();
document.removeEventListener('focusin', focus);
window.removeEventListener('blur', blur);
controller.current?.dispose();
controller.current = null;
};
- }, [api]);
- 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);
- }
- };
+ }, [api, requestClose]);
const toggleSettings = () => {
controller.current?.releaseInput();
setSettings((value) => !value);
@@ -217,11 +213,11 @@ export function RemoteDesktopViewerWindow() {
variant="secondary"
className={action}
aria-label={t('remoteDesktop.disconnect')}
- onClick={() => void api.close()}
+ onClick={requestClose}
>
<LogOut size={16} />
</Button>
- {!isMac && <WindowControls onClose={() => api.close()} />}
+ {!isMac && <WindowControls onClose={requestClose} />}
{settings && (
<aside className="remote-viewer-settings" aria-label={t('remoteDesktop.viewer.settings')}>
<div className="flex items-center justify-between">
@@ -332,31 +328,6 @@ export function RemoteDesktopViewerWindow() {
</Button>
</div>
)}
- {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>
- <p>{t('remoteDesktop.viewer.clipboardHint')}</p>
- <Button
- variant="secondary"
- className={action}
- disabled={!state.controlling || state.controlPending || clipboardBusy}
- onClick={() => void clipboard('copy')}
- >
- {t('remoteDesktop.viewer.copy')}
- </Button>
- <Button
- variant="secondary"
- className={action}
- disabled={!state.controlling || state.controlPending || clipboardBusy}
- onClick={() => void clipboard('paste')}
- >
- {t('remoteDesktop.viewer.paste')}
- </Button>
- </div>
- )}
<Button
variant="secondary"
className={action}
@@ -384,6 +355,13 @@ export function RemoteDesktopViewerWindow() {
{t('remoteDesktop.allWindows')}
</Button>
<p>{t('remoteDesktop.viewer.inputHint')}</p>
+ {state?.caps?.clipboardText && (
+ <p>
+ {t('remoteDesktop.viewer.clipboardShortcutHint', {
+ modifier: isMac ? '⌘' : 'Ctrl',
+ })}
+ </p>
+ )}
{state?.caps?.displayModes && <p>{t('remoteDesktop.viewer.resolutionHint')}</p>}
{notice && <p role="status">{notice}</p>}
</aside>
@@ -458,7 +436,30 @@ export function RemoteDesktopViewerWindow() {
</div>
)}
{isFullscreen && network && <div className="remote-viewer-network-overlay">{network}</div>}
+ {state?.clipboardError && (
+ <div className="remote-viewer-notice" role="status">
+ {t('remoteDesktop.viewer.clipboardFailed')}
+ </div>
+ )}
</div>
+ <ConfirmDialog
+ presentation="standard"
+ open={closeGeneration !== null}
+ onOpenChange={(open) => {
+ if (!open) setCloseGeneration(null);
+ }}
+ title={t('remoteDesktop.viewer.confirmDisconnect')}
+ description={t('remoteDesktop.viewer.confirmDisconnectHint')}
+ confirmText={t('remoteDesktop.disconnect')}
+ onConfirm={() => {
+ if (closeGeneration === null || closeGeneration !== generation.current) return;
+ void api.close(closeGeneration).catch(() => {
+ if (closeGeneration !== generation.current) return;
+ setNotice(t('remoteDesktop.viewer.disconnectFailed'));
+ setSettings(true);
+ });
+ }}
+ />
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerControl.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerControl.test.ts
index 9cd8bfe3f2..23bad4eca5 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerControl.test.ts
+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerControl.test.ts
@@ -42,6 +42,7 @@ async function fixture(firstControl?: Promise<{ controlling: boolean }>) {
}),
onActive: () => () => {},
onLocale: () => () => {},
+ onCloseRequested: () => () => {},
ice: async () => [],
clipboard,
close: async () => {},
@@ -56,6 +57,7 @@ async function fixture(firstControl?: Promise<{ controlling: boolean }>) {
version: 1,
enabled: true,
canControl: true,
+ clipboardText: true,
automaticReconnect: true,
displays: [{ id: 'one', name: 'Display', width: 1280, height: 720 }],
};
@@ -87,6 +89,53 @@ const inputEnabled = () =>
runtime.receive.mock.calls.filter(([message]) => message.type === 'control').at(-1)?.[0]
.enabled ?? false;
+it('orders quick copy/paste shortcuts and reports transfer failure without reconnecting', async () => {
+ const current = await fixture();
+ present();
+ const gate = deferred<void>();
+ current.clipboard.mockImplementationOnce(() => gate.promise);
+ runtime.post?.({ type: 'clipboard', action: 'copy', epoch: 'lease' });
+ runtime.post?.({ type: 'clipboard', action: 'paste', epoch: 'lease' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(current.clipboard).toHaveBeenCalledExactlyOnceWith(1, 'copy');
+ gate.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(current.clipboard).toHaveBeenLastCalledWith(1, 'paste');
+ current.clipboard.mockRejectedValueOnce(new Error('CLIPBOARD_UNAVAILABLE'));
+ runtime.post?.({ type: 'clipboard', action: 'copy', epoch: 'lease' });
+ runtime.post?.({ type: 'clipboard', action: 'paste', epoch: 'lease' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(current.clipboard).toHaveBeenCalledTimes(3);
+ expect(snapshot).toMatchObject({
+ clipboardError: true,
+ controlling: true,
+ ready: true,
+ error: null,
+ });
+ runtime.post?.({ type: 'clipboard', action: 'copy', epoch: 'lease' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(snapshot.clipboardError).toBe(false);
+ expect(current.clipboard).toHaveBeenCalledTimes(4);
+});
+
+it('drops queued clipboard work after control is released and ignores stale shortcut epochs', async () => {
+ const current = await fixture();
+ present();
+ const gate = deferred<void>();
+ current.clipboard.mockImplementationOnce(() => gate.promise);
+ runtime.post?.({ type: 'clipboard', action: 'copy', epoch: 'old-lease' });
+ runtime.post?.({ type: 'clipboard', action: 'invalid', epoch: 'lease' });
+ expect(current.clipboard).not.toHaveBeenCalled();
+ runtime.post?.({ type: 'clipboard', action: 'copy', epoch: 'lease' });
+ runtime.post?.({ type: 'clipboard', action: 'paste', epoch: 'lease' });
+ await vi.advanceTimersByTimeAsync(0);
+ await controller.setControl(false);
+ await controller.setControl(true);
+ gate.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(current.clipboard).toHaveBeenCalledExactlyOnceWith(1, 'copy');
+});
+
it.each([true, false])(
'keeps actions and real input aligned when control finishes before video: %s',
async (controlFirst) => {
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
index d8874840e9..e4d013209c 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts
+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts
@@ -4,50 +4,257 @@ import { mountRemoteDesktopViewer } from '@cindy/maker-shared/remote-desktop-vie
import { DESKTOP_KEY_CODES, REMOTE_DESKTOP_NETWORK } from '@cindy/device-link';
let viewer: ReturnType<typeof mountRemoteDesktopViewer>;
-let messages: Record<string,unknown>[];
+let messages: Record<string, unknown>[];
let stage: HTMLElement;
-beforeEach(()=>{
+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});
+ 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});
+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('scopes cursor hiding to the remote picture regardless of window focus or cursor metadata', () => {
+ expect(stage.style.cursor).toBe('none');
+ viewer.receive({ type: 'frame', jpeg: 'frame' });
+ expect(stage.style.cursor).toBe('none');
+ pointer('pointerleave');
+ expect(getComputedStyle(document.body).cursor).not.toBe('none');
+ expect(getComputedStyle(document.getElementById('mouse-left')!).cursor).not.toBe('none');
+ pointer('pointerenter');
+ expect(stage.style.cursor).toBe('none');
+ window.dispatchEvent(new Event('blur'));
+ expect(stage.style.cursor).toBe('none');
+ window.dispatchEvent(new Event('focus'));
+ expect(stage.style.cursor).toBe('none');
+ viewer.receive({ type: 'control', enabled: false });
+ expect(stage.style.cursor).toBe('default');
+ viewer.receive({ type: 'control', enabled: true });
+ viewer.receive({ type: 'stop' });
+ expect(stage.style.cursor).toBe('default');
+});
+it.each(['control', 'meta'])(
+ 'bridges %s clipboard shortcuts once without forwarding or inserting them',
+ (modifier) => {
+ viewer.receive({
+ type: 'init',
+ epoch: 'lease',
+ width: 1000,
+ height: 600,
+ clipboardShortcuts: true,
+ clipboardModifier: modifier,
+ });
+ viewer.receive({ type: 'control', enabled: true });
+ pointer('pointerdown');
+ pointer('pointerup');
+ messages = [];
+ const input = document.getElementById('keyboard-input')!;
+ const modifiers = { ctrlKey: modifier === 'control', metaKey: modifier === 'meta' };
+ const modifierCode = modifier === 'meta' ? 'MetaLeft' : 'ControlLeft';
+ for (const code of ['KeyC', 'KeyV']) {
+ input.dispatchEvent(
+ new KeyboardEvent('keydown', { code: modifierCode, ...modifiers, bubbles: true }),
+ );
+ const event = new KeyboardEvent('keydown', {
+ code,
+ ...modifiers,
+ bubbles: true,
+ cancelable: true,
+ });
+ input.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(true);
+ input.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ code,
+ ...modifiers,
+ repeat: true,
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ input.dispatchEvent(
+ new KeyboardEvent('keyup', { code, ...modifiers, bubbles: true, cancelable: true }),
+ );
+ input.dispatchEvent(new KeyboardEvent('keyup', { code: modifierCode, bubbles: true }));
+ }
+ vi.advanceTimersByTime(34);
+ expect(messages.filter((message) => message.type === 'clipboard')).toEqual([
+ { type: 'clipboard', action: 'copy', epoch: 'lease' },
+ { type: 'clipboard', action: 'paste', epoch: 'lease' },
+ ]);
+ expect(events().filter((event) => event.kind === 'key' || event.kind === 'text')).toEqual([]);
+ },
+);
+it('does not bridge clipboard in local controls, composition, view-only mode or unsupported hosts', () => {
+ const shortcut = () =>
+ document.activeElement!.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ code: 'KeyV',
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ pointer('pointerdown');
+ pointer('pointerup');
+ shortcut();
+ expect(messages.some((message) => message.type === 'clipboard')).toBe(false);
+ viewer.receive({
+ type: 'init',
+ epoch: 'lease',
+ width: 1000,
+ height: 600,
+ clipboardShortcuts: true,
+ });
+ viewer.receive({ type: 'control', enabled: true });
+ const button = document.createElement('button');
+ document.body.append(button);
+ button.focus();
+ shortcut();
+ pointer('pointerdown');
+ pointer('pointerup');
+ const input = document.getElementById('keyboard-input')!;
+ input.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
+ shortcut();
+ input.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));
+ viewer.receive({ type: 'control', enabled: false });
+ shortcut();
+ expect(messages.some((message) => message.type === 'clipboard')).toBe(false);
+});
+it.each(['key', 'button', 'scroll'])(
+ 'preserves the deferred modifier for ordinary %s input',
+ (kind) => {
+ viewer.receive({
+ type: 'init',
+ epoch: 'lease',
+ width: 1000,
+ height: 600,
+ clipboardShortcuts: true,
+ });
+ viewer.receive({ type: 'control', enabled: true });
+ pointer('pointerdown');
+ pointer('pointerup');
+ messages = [];
+ const input = document.getElementById('keyboard-input')!;
+ input.dispatchEvent(
+ new KeyboardEvent('keydown', { code: 'ControlLeft', ctrlKey: true, bubbles: true }),
+ );
+ if (kind === 'key') {
+ input.dispatchEvent(
+ new KeyboardEvent('keydown', { code: 'KeyA', ctrlKey: true, bubbles: true }),
+ );
+ input.dispatchEvent(
+ new KeyboardEvent('keyup', { code: 'KeyA', ctrlKey: true, bubbles: true }),
+ );
+ } else if (kind === 'button') {
+ pointer('pointerdown');
+ pointer('pointerup');
+ } else {
+ stage.dispatchEvent(
+ new WheelEvent('wheel', { deltaY: 32, ctrlKey: true, bubbles: true, cancelable: true }),
+ );
+ }
+ input.dispatchEvent(new KeyboardEvent('keyup', { code: 'ControlLeft', bubbles: true }));
+ vi.advanceTimersByTime(34);
+ expect(events()[0]).toEqual({ kind: 'key', code: 'ControlLeft', down: true });
+ expect(events().at(-1)).toEqual({ kind: 'key', code: 'ControlLeft', down: false });
+ expect(events().some((event) => event.kind === kind)).toBe(true);
+ expect(events().some((event) => event.kind === 'release')).toBe(false);
+ },
+);
+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: 0.5, y: 0.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});
+ 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: 0.5, y: 0.5 });
+ expect(events()).toContainEqual({ kind: 'button', button: 2, down: false, x: 0.5, y: 0.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('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([]);
+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/__tests__/viewerTransport.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerTransport.test.ts
index c9dbcc404c..2cfd6762de 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerTransport.test.ts
+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerTransport.test.ts
@@ -24,6 +24,7 @@ beforeEach(async () => {
}),
onActive: () => () => {},
onLocale: () => () => {},
+ onCloseRequested: () => () => {},
ice: async () => [],
clipboard: async () => {},
close: async () => {},
diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx
index 1fb76f25af..12478e1b86 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx
+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx
@@ -33,6 +33,61 @@ afterEach(() => {
vi.clearAllMocks();
});
+it('confirms toolbar and native exits, keeps cancellation connected, and discards stale confirmations', async () => {
+ await i18n.changeLanguage('zh-CN');
+ const close = vi.fn(async () => {});
+ let closeRequested!: (generation: number) => void;
+ let active!: (state: { generation: number; active: boolean }) => void;
+ Object.assign(window, {
+ electronAPI: {
+ remoteDesktopViewer: {
+ onActive: (listener: typeof active) => {
+ active = listener;
+ return () => {};
+ },
+ onLocale: () => () => {},
+ onCloseRequested: (listener: typeof closeRequested) => {
+ closeRequested = listener;
+ return () => {};
+ },
+ state: async () => ({ generation: 1 }),
+ rendererReady: async () => {},
+ presentationReady: async () => {},
+ inputFocus: async () => {},
+ close,
+ },
+ },
+ });
+ render(<RemoteDesktopViewerWindow />);
+ await act(async () => {});
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('remoteDesktop.disconnect') }));
+ expect(close).not.toHaveBeenCalled();
+ expect(lifecycle.releaseInput).toHaveBeenCalled();
+ const dialog = within(screen.getByRole('alertdialog'));
+ const cancel = dialog.getByRole('button', { name: i18n.t('commonUi.confirmDialog.cancel') });
+ expect(document.activeElement).toBe(cancel);
+ fireEvent.click(cancel);
+ expect(close).not.toHaveBeenCalled();
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ act(() => {
+ closeRequested(1);
+ closeRequested(1);
+ });
+ expect(screen.getAllByRole('alertdialog')).toHaveLength(1);
+ fireEvent.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', {
+ name: i18n.t('remoteDesktop.disconnect'),
+ }),
+ );
+ expect(close).toHaveBeenCalledExactlyOnceWith(1);
+ act(() => closeRequested(1));
+ act(() => active({ generation: 2, active: false }));
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ act(() => closeRequested(1));
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ expect(close).toHaveBeenCalledOnce();
+});
+
it('explains view-only actions and enables the same actions when control is confirmed', async () => {
await i18n.changeLanguage('zh-CN');
Object.assign(window, {
@@ -40,6 +95,7 @@ it('explains view-only actions and enables the same actions when control is conf
remoteDesktopViewer: {
onActive: () => () => {},
onLocale: () => () => {},
+ onCloseRequested: () => () => {},
state: async () => ({ generation: 1 }),
rendererReady: async () => {},
presentationReady: async () => {},
@@ -72,17 +128,21 @@ it('explains view-only actions and enables the same actions when control is conf
fireEvent.click(screen.getByRole('button', { name: '操作' }));
const panel = within(screen.getByRole('complementary', { name: '操作' }));
expect(panel.getByText(i18n.t('remoteDesktop.viewer.controlRequired'))).toBeDefined();
- const copy = panel.getByRole('button', {
- name: i18n.t('remoteDesktop.viewer.copy'),
+ expect(panel.queryByText('文字剪贴板')).toBeNull();
+ expect(
+ panel.getByText(i18n.t('remoteDesktop.viewer.clipboardShortcutHint', { modifier: '⌘' })),
+ ).toBeDefined();
+ const desktop = panel.getByRole('button', {
+ name: i18n.t('remoteDesktop.showDesktop'),
}) as HTMLButtonElement;
- expect(copy.disabled).toBe(true);
+ expect(desktop.disabled).toBe(true);
fireEvent.click(panel.getByRole('button', { name: i18n.t('remoteDesktop.takeControl') }));
expect(lifecycle.setControl).toHaveBeenCalledWith(true);
await act(async () => lifecycle.update?.({ ...state, controlPending: true }));
expect(panel.getByText(i18n.t('remoteDesktop.viewer.controlPending'))).toBeDefined();
- expect(copy.disabled).toBe(true);
+ expect(desktop.disabled).toBe(true);
await act(async () => lifecycle.update?.({ ...state, controlling: true }));
- expect(copy.disabled).toBe(false);
+ expect(desktop.disabled).toBe(false);
expect(panel.queryByText(i18n.t('remoteDesktop.viewer.controlRequired'))).toBeNull();
});
@@ -97,6 +157,7 @@ it.each([
remoteDesktopViewer: {
onActive: () => () => {},
onLocale: () => () => {},
+ onCloseRequested: () => () => {},
state: async () => ({ generation: 1 }),
rendererReady: async () => {},
presentationReady: async () => {},
@@ -132,6 +193,7 @@ it('updates translated controls without ending or recreating the viewer connecti
electronAPI: {
remoteDesktopViewer: {
onActive: () => () => {},
+ onCloseRequested: () => () => {},
onLocale: (listener: (locale: string) => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
diff --git a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts b/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts
index e608a918a1..3d3405c3fb 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts
+++ b/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts
@@ -23,6 +23,7 @@ export interface ViewerSnapshot {
target: RemoteViewerState['target'];
status: string;
error: string | null;
+ clipboardError?: boolean;
controlling: boolean;
controlPending: boolean;
caps: RemoteDesktopCapabilities | null;
@@ -61,6 +62,9 @@ export class DesktopViewerController {
private frameBusy: string | null = null;
private heartbeatBusy: string | null = null;
private streaming = false;
+ private clipboardQueue: Promise<void> = Promise.resolve();
+ private clipboardQueued = 0;
+ private clipboardRevision = 0;
private session: RemoteDesktopViewerSession;
private media: RemoteDesktopViewerMedia;
private runtime: ReturnType<typeof mountRemoteDesktopViewer>;
@@ -143,6 +147,8 @@ export class DesktopViewerController {
}
private cancel(preserveFrame = false): void {
this.epoch++;
+ this.clipboardQueue = Promise.resolve();
+ this.clipboardQueued = 0;
this.opening = false;
this.streaming = false;
this.media.reset();
@@ -155,6 +161,7 @@ export class DesktopViewerController {
ready: false,
transport: '',
latency: null,
+ clipboardError: false,
});
}
private async connect(takeover = false): Promise<void> {
@@ -186,6 +193,11 @@ export class DesktopViewerController {
fillHeight: false,
trickleIce: caps.trickleIce === true,
audio: caps.systemAudio && this.state.settings.audio,
+ clipboardShortcuts: caps.clipboardText === true,
+ clipboardModifier:
+ typeof window !== 'undefined' && window.electronAPI?.platform === 'darwin'
+ ? 'meta'
+ : 'control',
});
this.runtime.receive({ type: 'mode', mode: 'pointer' });
if (caps.canControl && this.wantsControl) await this.setControl(true);
@@ -245,6 +257,7 @@ export class DesktopViewerController {
!this.state.controlPending &&
this.session.lease?.controlling === true;
if (controlling === this.state.controlling) return;
+ this.clipboardRevision++;
this.publish({ controlling });
this.runtime.receive({ type: 'control', enabled: controlling });
}
@@ -285,8 +298,30 @@ export class DesktopViewerController {
}
async clipboard(action: 'copy' | 'paste'): Promise<void> {
if (!this.state.controlling) throw new Error('DESKTOP_VIEW_ONLY');
+ if (this.clipboardQueued >= 8) throw new Error('CLIPBOARD_BUSY');
+ const epoch = this.epoch;
+ const generation = this.scope.generation;
+ const revision = this.clipboardRevision;
+ if (this.clipboardQueued === 0) this.clipboardQueue = Promise.resolve();
+ this.clipboardQueued++;
this.releaseInput();
- await this.api.clipboard(this.scope.generation, action);
+ this.publish({ clipboardError: false });
+ const transfer = this.clipboardQueue.then(async () => {
+ if (
+ epoch !== this.epoch ||
+ revision !== this.clipboardRevision ||
+ this.disposed ||
+ !this.state.controlling
+ )
+ throw new Error('DESKTOP_STOPPED');
+ await this.api.clipboard(generation, action);
+ });
+ this.clipboardQueue = transfer;
+ try {
+ await transfer;
+ } finally {
+ if (epoch === this.epoch) this.clipboardQueued--;
+ }
}
async permissionGuide(): Promise<void> {
await this.request({ op: 'permissions', action: 'guide' });
@@ -367,6 +402,19 @@ export class DesktopViewerController {
return;
}
switch (message.type) {
+ case 'clipboard': {
+ if (
+ !this.state.controlling ||
+ !this.state.caps?.clipboardText ||
+ (message.action !== 'copy' && message.action !== 'paste')
+ )
+ break;
+ const epoch = this.epoch;
+ void this.clipboard(message.action).catch(() => {
+ if (epoch === this.epoch && !this.disposed) this.publish({ clipboardError: true });
+ });
+ break;
+ }
case 'streaming':
this.streaming = true;
this.publish({ transport: 'video', latency: null });
diff --git a/apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css b/apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css
index 6baf5b4b58..368ae34e17 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css
+++ b/apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css
@@ -130,6 +130,21 @@
font-size: var(--text-12);
white-space: nowrap;
}
+.remote-viewer-notice {
+ position: absolute;
+ bottom: var(--space-4);
+ left: 50%;
+ transform: translateX(-50%);
+ max-width: calc(100% - 32px);
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-xl);
+ padding: var(--space-3) var(--space-4);
+ background: var(--surface);
+ color: var(--text-primary);
+ font-size: var(--text-13);
+ pointer-events: none;
+ z-index: 4;
+}
.remote-viewer-latency {
color: var(--text-secondary);
font-variant-numeric: tabular-nums;
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 19578262a1..707e8641cc 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -82,16 +82,15 @@
"balanced": "Balanced",
"clear": "Clear",
"resolution": "Computer resolution",
- "clipboard": "Text clipboard",
- "copy": "Copy remote text",
- "paste": "Paste to remote",
- "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.",
"controlPending": "Requesting control…",
"controlRequired": "View only. Take control to use the clipboard and desktop actions.",
- "clipboardHint": "Text only. Copy selected text from the remote computer, or paste this computer's clipboard into the active remote field.",
+ "confirmDisconnect": "Disconnect from this computer?",
+ "confirmDisconnectHint": "The remote desktop connection will end. Apps on the computer will keep running.",
+ "disconnectFailed": "Could not disconnect. Try again.",
+ "clipboardShortcutHint": "Use {{modifier}}+C / {{modifier}}+V in the picture to copy and paste text between computers. Images and files are not supported yet.",
"resolutionHint": "Resolution changes affect the actual remote monitor."
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e6c5a2770e..a4c5358818 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -82,16 +82,15 @@
"balanced": "バランス",
"clear": "高画質",
"resolution": "コンピュータの解像度",
- "clipboard": "テキストクリップボード",
- "copy": "リモートのテキストをコピー",
- "paste": "リモートに貼り付け",
- "clipboardDone": "テキストを転送しました",
"clipboardFailed": "テキストを転送できません。操作権限を確認し、16,384 文字以内にしてください。",
"settingsFailed": "表示設定を変更できませんでした。",
"inputHint": "画面をクリックして入力します。Ctrl+Alt+Esc でキーボードのフォーカスを解除し、Cmd/Ctrl+W でこのウィンドウを閉じます。",
"controlPending": "操作権限を取得中…",
"controlRequired": "表示のみです。クリップボードとデスクトップ操作を使うには操作権限を取得してください。",
- "clipboardHint": "テキストのみ転送します。リモートで選択したテキストをコピーするか、このコンピュータのクリップボードをリモートの入力欄に貼り付けます。",
+ "confirmDisconnect": "このコンピュータとの接続を切断しますか?",
+ "confirmDisconnectHint": "リモートデスクトップ接続を終了します。コンピュータ上のアプリは動作を続けます。",
+ "disconnectFailed": "切断できませんでした。もう一度お試しください。",
+ "clipboardShortcutHint": "画面内で {{modifier}}+C / {{modifier}}+V を使うと、コンピュータ間でテキストをコピーして貼り付けられます。画像とファイルにはまだ対応していません。",
"resolutionHint": "解像度の変更はリモートの実際のモニターに反映されます。"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 01789d6a56..33b52c9710 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -82,16 +82,15 @@
"balanced": "균형",
"clear": "선명",
"resolution": "컴퓨터 해상도",
- "clipboard": "텍스트 클립보드",
- "copy": "원격 텍스트 복사",
- "paste": "원격으로 붙여넣기",
- "clipboardDone": "텍스트를 전송했습니다",
"clipboardFailed": "텍스트를 전송할 수 없습니다. 제어 권한을 확인하고 내용을 16,384자 이내로 줄이세요.",
"settingsFailed": "디스플레이 설정을 변경할 수 없습니다.",
"inputHint": "화면을 클릭하여 입력하세요. Ctrl+Alt+Esc로 키보드 포커스를 해제하고 Cmd/Ctrl+W로 이 창을 닫습니다.",
"controlPending": "제어 권한을 가져오는 중…",
"controlRequired": "보기 전용입니다. 클립보드와 데스크톱 작업을 사용하려면 제어 권한을 가져오세요.",
- "clipboardHint": "텍스트만 전송합니다. 원격 컴퓨터에서 선택한 텍스트를 복사하거나 이 컴퓨터의 클립보드를 원격 입력란에 붙여넣습니다.",
+ "confirmDisconnect": "이 컴퓨터와의 연결을 끊을까요?",
+ "confirmDisconnectHint": "원격 데스크톱 연결이 종료됩니다. 컴퓨터의 앱은 계속 실행됩니다.",
+ "disconnectFailed": "연결을 끊지 못했습니다. 다시 시도하세요.",
+ "clipboardShortcutHint": "화면 안에서 {{modifier}}+C / {{modifier}}+V로 컴퓨터 간에 텍스트를 복사하고 붙여넣으세요. 이미지와 파일은 아직 지원하지 않습니다.",
"resolutionHint": "해상도를 변경하면 원격 컴퓨터의 실제 모니터에 적용됩니다."
}
},
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 fe85418872..a053d4a4c5 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -82,16 +82,15 @@
"balanced": "均衡",
"clear": "清晰",
"resolution": "电脑分辨率",
- "clipboard": "文字剪贴板",
- "copy": "复制远端文字",
- "paste": "粘贴到远端",
- "clipboardDone": "文字已传输",
"clipboardFailed": "文字传输失败,请确认已取得控制权,且内容不超过 16,384 字符。",
"settingsFailed": "未能修改显示设置。",
"inputHint": "点击画面即可输入。Ctrl+Alt+Esc 释放键盘焦点;Cmd/Ctrl+W 关闭这个窗口。",
"controlPending": "正在取得控制权…",
"controlRequired": "当前仅查看,取得控制权后可使用剪贴板和桌面操作。",
- "clipboardHint": "仅传输文字:复制远端选中的文字到本机,或将本机剪贴板粘贴到远端当前输入框。",
+ "confirmDisconnect": "断开与这台电脑的连接?",
+ "confirmDisconnectHint": "将结束远程桌面连接,电脑上的应用仍会继续运行。",
+ "disconnectFailed": "未能断开连接,请重试。",
+ "clipboardShortcutHint": "在画面内使用 {{modifier}}+C / {{modifier}}+V,即可在两台电脑之间复制粘贴文字。暂不支持图片和文件。",
"resolutionHint": "分辨率修改会影响远端的实际显示器。"
}
},
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 31d0db4e5c..616da90b22 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -82,16 +82,15 @@
"balanced": "均衡",
"clear": "清晰",
"resolution": "電腦解析度",
- "clipboard": "文字剪貼簿",
- "copy": "複製遠端文字",
- "paste": "貼到遠端",
- "clipboardDone": "文字已傳輸",
"clipboardFailed": "文字傳輸失敗,請確認已取得控制權,且內容不超過 16,384 字元。",
"settingsFailed": "無法修改顯示設定。",
"inputHint": "點擊畫面即可輸入。Ctrl+Alt+Esc 釋放鍵盤焦點;Cmd/Ctrl+W 關閉這個視窗。",
"controlPending": "正在取得控制權…",
"controlRequired": "目前僅供檢視,取得控制權後可使用剪貼簿和桌面操作。",
- "clipboardHint": "僅傳輸文字:將遠端選取的文字複製到本機,或將本機剪貼簿貼到遠端目前的輸入框。",
+ "confirmDisconnect": "中斷與這台電腦的連線?",
+ "confirmDisconnectHint": "將結束遠端桌面連線,電腦上的應用程式仍會繼續執行。",
+ "disconnectFailed": "無法中斷連線,請重試。",
+ "clipboardShortcutHint": "在畫面內使用 {{modifier}}+C / {{modifier}}+V,即可在兩台電腦之間複製貼上文字。暫不支援圖片和檔案。",
"resolutionHint": "解析度修改會影響遠端的實際顯示器。"
}
},
diff --git a/apps/desktop/src/shared/remoteDesktopViewer.ts b/apps/desktop/src/shared/remoteDesktopViewer.ts
index 6e9acd46b9..8f838c784d 100644
--- a/apps/desktop/src/shared/remoteDesktopViewer.ts
+++ b/apps/desktop/src/shared/remoteDesktopViewer.ts
@@ -7,6 +7,7 @@ export const REMOTE_VIEWER = {
ICE: 'remote-desktop-viewer:ice',
CLIPBOARD: 'remote-desktop-viewer:clipboard',
CLOSE: 'remote-desktop-viewer:close',
+ CLOSE_REQUESTED: 'remote-desktop-viewer:close-requested',
READY: 'remote-desktop-viewer:ready',
PRESENTED: 'remote-desktop-viewer:presented',
ACTIVE: 'remote-desktop-viewer:active',
@@ -36,11 +37,12 @@ export interface RemoteDesktopViewerApi {
): Promise<unknown>;
ice(generation: number, mediaAttempt: string): Promise<DesktopIceServer[]>;
clipboard(generation: number, action: 'copy' | 'paste'): Promise<void>;
- close(): Promise<void>;
+ close(generation: number): Promise<void>;
fullscreen(): Promise<void>;
rendererReady(): Promise<void>;
presentationReady(): Promise<void>;
onActive(listener: (state: RemoteViewerState) => void): () => void;
onLocale(listener: (locale: string) => void): () => void;
+ onCloseRequested(listener: (generation: number) => void): () => void;
inputFocus(generation: number, focused: boolean): Promise<void>;
}
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 193718864e..766cca311c 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -44,7 +44,7 @@
| `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 | Button, FormField, RemoteDesktopViewerWindow, Select | 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/components/ui/button.tsx, apps/desktop/src/renderer/components/ui/form-field.tsx, apps/desktop/src/renderer/components/ui/select.tsx, 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 | 79 | 48 | 20 |
+| `desktop.window.remote-desktop` | desktop | 远程桌面独立窗口 | `?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx | Button, ConfirmDialog, FormField, RemoteDesktopViewerWindow, Select | 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/components/ui/button.tsx, apps/desktop/src/renderer/components/ui/confirm-dialog.tsx, apps/desktop/src/renderer/components/ui/form-field.tsx, apps/desktop/src/renderer/components/ui/select.tsx, 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 | 97 | 48 | 26 |
| `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 |
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index d70adc61bb..662035c0fa 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -6,10 +6,25 @@ 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
+view-only/control, display selection, sound, video settings and text
+clipboard shortcuts 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.
+Cmd/Ctrl+W requests closing this viewer, including while it owns keyboard focus.
+The toolbar exit, native window close and close shortcut share a confirmation
+dialog; cancelling keeps the connection and control lease. Confirmation belongs
+to the current window generation and cannot close a later connection.
+
+While controlling, the local cursor is hidden inside the remote picture even
+when Windows embeds its cursor in the video rather than sending cursor metadata.
+Cursor hiding is scoped to the remote picture, not the system or window focus:
+moving outside it immediately restores the local cursor even if the viewer keeps
+focus. Local toolbar controls and dialogs retain their cursor. View-only mode
+also restores the local cursor inside the picture.
+With the picture focused, Cmd+C/V on macOS or Ctrl+C/V on Windows copies selected
+remote text to the local clipboard or pastes local text remotely. Transfers use
+the existing authorized Main bridge, are ordered and user-triggered, and report
+failure without reconnecting. There is no background clipboard monitoring or
+automatic context-menu synchronization; images, files and cut are not bridged.
The window reuses the existing resource-usage auxiliary-window controller and
factory for hidden prewarming, two-phase readiness, hide/reuse and bounded crash
diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
index 55ee4364c7..bdcb624efa 100644
--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.js
+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
@@ -112,6 +112,9 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
fy = 0.5,
mode = "pointer",
control = false,
+ clipboardShortcuts = false,
+ clipboardModifier = "control",
+ deferredClipboardModifier = null,
pc = null,
dc = null,
seq = 0,
@@ -157,6 +160,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
return;
}
if (composing) return;
+ if (config.desktop && document.activeElement === keyboardInput) return;
// Keep focus inside the native evaluateJavaScript call; WebKit can reject
// keyboard presentation after requestAnimationFrame loses user activation.
keyboardInput.blur();
@@ -426,7 +430,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
cursor.style.display =
!config.desktop && control && (mode === "pointer" || mode === "touch") ? "block" : "none";
}
- if (config.desktop) stage.style.cursor = control && remoteCursor?.visible ? "none" : "default";
+ if (config.desktop) stage.style.cursor = control ? "none" : "default";
}
// Literal source is required: Hermes function.toString() yields bytecode.
function validCursor(v) {
@@ -488,6 +492,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
}
function queue(event) {
if (!control) return;
+ if (config.desktop && (event.kind === "button" || event.kind === "scroll"))
+ flushClipboardModifier();
// 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;
@@ -540,6 +546,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
}, 33);
cleanups.push(() => clearInterval(inputTimer));
function release() {
+ deferredClipboardModifier = null;
clearTimeout(hold);
if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);
gestureFrame = null;
@@ -960,6 +967,13 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
? code.replace(/Right$/, "Left")
: code;
const hardwareKeys = new Set();
+ function flushClipboardModifier() {
+ if (!deferredClipboardModifier) return;
+ const code = deferredClipboardModifier;
+ deferredClipboardModifier = null;
+ hardwareKeys.add(code);
+ queue({ kind: "key", code, down: true });
+ }
listen(document, "keydown", (e) => {
if (config.desktop) {
if (e.ctrlKey && e.altKey && e.code === "Escape") {
@@ -976,6 +990,32 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
)
return;
if ((e.metaKey || e.ctrlKey) && e.code === "KeyW") return; // always retain a local close shortcut
+ if (
+ control &&
+ clipboardShortcuts &&
+ normalizedKey(e.code) === (clipboardModifier === "meta" ? "MetaLeft" : "ControlLeft")
+ ) {
+ e.preventDefault();
+ if (!hardwareKeys.has(normalizedKey(e.code)))
+ deferredClipboardModifier = normalizedKey(e.code);
+ return;
+ }
+ if (
+ control &&
+ clipboardShortcuts &&
+ (clipboardModifier === "meta" ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey) &&
+ !e.altKey &&
+ !e.shiftKey &&
+ (e.code === "KeyC" || e.code === "KeyV")
+ ) {
+ e.preventDefault();
+ if (!e.repeat) {
+ release();
+ hardwareKeys.clear();
+ post({ type: "clipboard", action: e.code === "KeyC" ? "copy" : "paste" });
+ }
+ return;
+ }
if (
!e.ctrlKey &&
!e.metaKey &&
@@ -986,12 +1026,16 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
}
if (control && validKeys.has(normalizedKey(e.code))) {
e.preventDefault();
+ flushClipboardModifier();
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 && control && deferredClipboardModifier === code) {
+ flushClipboardModifier();
+ }
if (config.desktop && !hardwareKeys.delete(code)) return;
if (control && validKeys.has(code)) {
e.preventDefault();
@@ -1580,6 +1624,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
sending = false;
seq = 0;
epoch = message.epoch;
+ clipboardShortcuts = config.desktop && message.clipboardShortcuts === true;
+ clipboardModifier = message.clipboardModifier === "meta" ? "meta" : "control";
dw = message.width;
dh = message.height;
fillHeight = message.fillHeight === true;
diff --git a/packages/maker-shared/src/remote-desktop/viewerSource.ts b/packages/maker-shared/src/remote-desktop/viewerSource.ts
index 7d64985a57..919d08adbb 100644
--- a/packages/maker-shared/src/remote-desktop/viewerSource.ts
+++ b/packages/maker-shared/src/remote-desktop/viewerSource.ts
@@ -1,2 +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";
+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 clipboardShortcuts = false,\n clipboardModifier = \"control\",\n deferredClipboardModifier = null,\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 if (config.desktop && document.activeElement === keyboardInput) 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 ? \"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 if (config.desktop && (event.kind === \"button\" || event.kind === \"scroll\"))\n flushClipboardModifier();\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 deferredClipboardModifier = null;\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 function flushClipboardModifier() {\n if (!deferredClipboardModifier) return;\n const code = deferredClipboardModifier;\n deferredClipboardModifier = null;\n hardwareKeys.add(code);\n queue({ kind: \"key\", code, down: true });\n }\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 control &&\n clipboardShortcuts &&\n normalizedKey(e.code) === (clipboardModifier === \"meta\" ? \"MetaLeft\" : \"ControlLeft\")\n ) {\n e.preventDefault();\n if (!hardwareKeys.has(normalizedKey(e.code)))\n deferredClipboardModifier = normalizedKey(e.code);\n return;\n }\n if (\n control &&\n clipboardShortcuts &&\n (clipboardModifier === \"meta\" ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey) &&\n !e.altKey &&\n !e.shiftKey &&\n (e.code === \"KeyC\" || e.code === \"KeyV\")\n ) {\n e.preventDefault();\n if (!e.repeat) {\n release();\n hardwareKeys.clear();\n post({ type: \"clipboard\", action: e.code === \"KeyC\" ? \"copy\" : \"paste\" });\n }\n return;\n }\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 flushClipboardModifier();\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 && control && deferredClipboardModifier === code) {\n flushClipboardModifier();\n }\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 clipboardShortcuts = config.desktop && message.clipboardShortcuts === true;\n clipboardModifier = message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\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/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjs
index bca013bbc7..aeb8c4ace3 100644
--- a/scripts/shared/design-inventory.mjs
+++ b/scripts/shared/design-inventory.mjs
@@ -776,10 +776,11 @@ export function catalogSurfaces() {
platform: 'desktop',
title: '远程桌面独立窗口',
productionEntry: '`?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx',
- reachableComponents: ['RemoteDesktopViewerWindow', 'Select', 'Button', 'FormField'],
+ reachableComponents: ['RemoteDesktopViewerWindow', 'Select', 'Button', 'FormField', 'ConfirmDialog'],
styleRoots: [
'apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx',
'apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx',
+ 'apps/desktop/src/renderer/components/ui/confirm-dialog.tsx',
'apps/desktop/src/renderer/components/ui/select.tsx',
'apps/desktop/src/renderer/components/ui/button.tsx',
'apps/desktop/src/renderer/components/ui/form-field.tsx',