Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(remote-desktop): 手机记住桌面分辨率,切换分辨率不重建视频 (#5393)
Dash09de40925373
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.tsindex 39a48dc355..5f7c47c50b 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts@@ -1,3 +1,4 @@+import type { RemoteDesktopDisplay } from '@cindy/device-link';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import {DESKTOP_AUDIO_RETRY_MS,@@ -688,6 +689,62 @@ it.each(['darwin', 'win32'])(},);+it('holds native video across a display change and resumes it on the new display', async () => {+ vi.stubGlobal('process', { ...process, platform: 'darwin' });+ expect((await h.deps.capabilities()).liveDisplaySwitch).toBe(true);+ // No video yet: nothing to hold.+ expect(h.deps.pauseVideo!()).toBe(false);+ const pending = h.deps.offer(+ { lease: h.lease, display: { id: '1' } },+ 'sdp',+ undefined,+ false,+ 'attempt',+ );+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());+ await flush();+ h.handlers.get(DESKTOP_LOCAL.REPLY)(event(), h.owner.send.mock.calls[0][1].id, 'answer');+ await pending;+ const owner = h.owner;+ const frame = h.handlers.get(DESKTOP_LOCAL.NATIVE_FRAME);+ const reply = h.handlers.get(DESKTOP_LOCAL.REPLY);+ const swap = async (display: RemoteDesktopDisplay, kept: unknown) => {+ const result = h.deps.resumeVideo!(display);+ await flush();+ const command = owner.send.mock.calls.at(-1)[1];+ expect(command).toMatchObject({ op: 'display-swap', lease: h.lease });+ reply(event(), command.id, kept);+ return result;+ };+ expect(h.deps.pauseVideo!()).toBe(true);+ // The capture page pauses its no-frame timeout for a slow display change.+ expect(owner.send.mock.calls.at(-1)[1]).toMatchObject({ op: 'display-hold', lease: h.lease });+ h.nativeFrame.mockClear();+ // Frames of the old geometry never reach the held stream.+ await expect(frame(event(), h.lease)).resolves.toBeNull();+ expect(h.nativeFrame).not.toHaveBeenCalled();+ h.nativeStop.mockClear();+ await expect(swap({ id: '5', name: 'Viewer', width: 900, height: 1600 }, true)).resolves.toBe(+ true,+ );+ // Same capture process and peer; only the source follows the new display.+ expect(h.owner).toBe(owner);+ expect(owner.dead).toBe(false);+ expect(h.nativeStop).toHaveBeenCalled();+ await frame(event(), h.lease);+ expect(h.nativeFrame).toHaveBeenLastCalledWith('5', false, undefined);+ // Browser capture (or an ended stream) cannot follow: not reported as kept.+ expect(h.deps.pauseVideo!()).toBe(true);+ await expect(swap({ id: '1', name: 'Main', width: 1920, height: 1080 }, false)).resolves.toBe(+ false,+ );+ // A stopped stream cannot be resumed and is not reported as kept.+ h.deps.stopVideo();+ await expect(+ h.deps.resumeVideo!({ id: '1', name: 'Main', width: 1920, height: 1080 }),+ ).resolves.toBe(false);+});+it('does not advertise or select Windows overlays without a ready native service', async () => {vi.stubGlobal('process', { ...process, platform: 'win32' });const { readWindowsDesktopSupport } = await import('../windowsHost');diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.tsindex 71a98b6170..65fcbca986 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts@@ -1344,3 +1344,68 @@ it('joins duplicate privacy initialization and invalidates it on control loss',ready();await errors;});++describe('live display switch', () => {+ function modes(h: ReturnType<typeof harness>) {+ h.deps.displayModes = vi.fn(async () => [+ { id: '1', width: 1920, height: 1080, current: true },+ { id: '2', width: 3840, height: 2160, current: false },+ ]);+ h.deps.resolution = vi.fn(async () => {});+ }+ it.each([+ ['kept', true, true, true],+ ['not requested', false, true, true],+ ['capture cannot pause', true, false, true],+ ['capture gone after the change', true, true, false],+ ] as const)(+ 'holds video across a temporary resolution only when %s allows it',+ async (_name, keepVideo, canPause, canResume) => {+ const h = harness();+ modes(h);+ h.deps.pauseVideo = vi.fn(() => canPause);+ h.deps.resumeVideo = vi.fn(async () => canResume);+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ vi.mocked(h.deps.stopVideo).mockClear();+ const result = (await h.controller.request('phone', {+ op: 'resolution',+ lease,+ modeId: '2',+ temporary: true,+ ...(keepVideo ? { keepVideo: true } : {}),+ })) as RemoteDesktopLease;+ const kept = keepVideo && canPause && canResume;+ expect(result).toMatchObject({ lease, controlling: false });+ expect(result.display).toMatchObject({ id: '1', width: 3840, height: 2160 });+ expect(result.videoKept).toBe(kept ? true : undefined);+ expect(h.deps.stopVideo).toHaveBeenCalledTimes(kept ? 0 : 1);+ if (keepVideo && canPause) expect(h.deps.resumeVideo).toHaveBeenCalledWith(result.display);+ else expect(h.deps.resumeVideo).not.toHaveBeenCalled();+ expect(h.controller.state).not.toBeNull();+ },+ );+ it('ends the session as before when a kept display change fails', async () => {+ const h = harness();+ modes(h);+ h.deps.resolution = vi.fn(async () => {+ throw new Error('DESKTOP_DISPLAY_MODE_FAILED');+ });+ h.deps.pauseVideo = vi.fn(() => true);+ h.deps.resumeVideo = vi.fn(async () => true);+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ await expect(+ h.controller.request('phone', {+ op: 'resolution',+ lease,+ modeId: '2',+ temporary: true,+ keepVideo: true,+ }),+ ).rejects.toThrow('DESKTOP_DISPLAY_MODE_FAILED');+ expect(h.deps.resumeVideo).not.toHaveBeenCalled();+ expect(h.deps.stopVideo).toHaveBeenCalled();+ expect(h.controller.state).toBeNull();+ });+});diff --git a/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplay.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplay.test.tsindex 4752983fa8..1368dd3ddb 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplay.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplay.test.ts@@ -507,3 +507,35 @@ it('acknowledges requested dimensions separately from actual host geometry', asyexpect(f.deps.startInput).toHaveBeenLastCalledWith('2');f.host.stop('phone');});++describe('viewer-sized desktop with live video', () => {+ it.each(['viewerDisplay', 'restoreViewerDisplay'] as const)(+ '%s keeps the stream on the changed display when requested',+ async (op) => {+ const f = fixture();+ f.deps.pauseVideo = vi.fn(() => true);+ f.deps.resumeVideo = vi.fn(async () => true);+ const { lease } = await f.start();+ if (op === 'restoreViewerDisplay') {+ await f.host.request('phone', { op: 'viewerDisplay', lease, width: 900, height: 1600 });+ await f.host.request('phone', { op: 'control', lease, enabled: true });+ }+ vi.mocked(f.deps.stopVideo).mockClear();+ vi.mocked(f.deps.resumeVideo!).mockClear();+ const result = (await f.host.request('phone', {+ op,+ lease,+ width: 900,+ height: 1600,+ keepVideo: true,+ })) as RemoteDesktopLease;+ expect(result.videoKept).toBe(true);+ expect(f.deps.stopVideo).not.toHaveBeenCalled();+ expect(f.deps.resumeVideo).toHaveBeenCalledWith(+ op === 'viewerDisplay'+ ? { id: '2', name: 'Viewer', width: 900, height: 1600 }+ : { id: '1', name: 'Main', width: 1920, height: 1080 },+ );+ },+ );+});diff --git a/apps/desktop/src/main/remote-desktop/controller.ts b/apps/desktop/src/main/remote-desktop/controller.tsindex d884da3444..b04fa91b2e 100644--- a/apps/desktop/src/main/remote-desktop/controller.ts+++ b/apps/desktop/src/main/remote-desktop/controller.ts@@ -13,6 +13,7 @@ import {type RemoteDesktopVideoSettings,type RemoteDesktopDisplayMode,type RemoteDesktopCapabilities,+ type RemoteDesktopDisplay,type RemoteDesktopLease,type RemoteDesktopPermissions,type RemoteDesktopIceRequest,@@ -53,6 +54,16 @@ export interface DesktopControllerDeps {stopInput(): void;releaseInput?(): Promise<void>;stopVideo(): void;+ /**+ * Hold the current video stream across a display change instead of stopping+ * it. Returns false when the active capture cannot follow a display change.+ */+ pauseVideo?(): boolean;+ /**+ * Point a held video stream at the changed display. True only when the+ * capture confirms a live stream follows it (e.g. not browser capture).+ */+ resumeVideo?(display: RemoteDesktopDisplay): Promise<boolean>;lockScreen?(isCurrent: () => boolean, signal: AbortSignal): Promise<void>;offer(lease: RemoteDesktopLease,@@ -265,10 +276,23 @@ export class RemoteDesktopController {this.deps.changed();return restoring;}+ /** A display change keeps the viewer's video only when it asked and capture can follow. */+ private holdVideo(keepVideo: boolean | undefined): boolean {+ if (keepVideo && this.deps.pauseVideo?.()) return true;+ this.deps.stopVideo();+ return false;+ }+ /** A held stream that cannot follow the new display is stopped like before. */+ private async resumeVideo(display: RemoteDesktopDisplay): Promise<boolean> {+ if (await this.deps.resumeVideo?.(display).catch(() => false)) return true;+ this.deps.stopVideo();+ return false;+ }private async temporaryResolution(peer: string,active: NonNullable<RemoteDesktopController['active']>,modeId: string,+ keepVideo?: boolean,): Promise<RemoteDesktopLease> {if (!active.controlling) throw new Error('DESKTOP_VIEW_ONLY');if (!this.deps.resolution || !this.deps.displayModes)@@ -286,7 +310,7 @@ export class RemoteDesktopController {this.displayChanging = true;try {this.deps.stopInput();- this.deps.stopVideo();+ const videoKept = this.holdVideo(keepVideo);await this.clearSafety();requireCurrent();await this.deps.releaseInput?.();@@ -317,17 +341,25 @@ export class RemoteDesktopController {);await this.resolutionWrite;requireCurrent();- active.display = {+ const display = {id: active.sourceDisplayId,name: active.display.name,width: selected.width,height: selected.height,};+ const resumed = videoKept && (await this.resumeVideo(display));+ requireCurrent();+ active.display = display;this.viewerGeometryManaged = true;active.controlling = false;this.controlGeneration++;this.deps.changed();- return { lease: active.lease, display: active.display, controlling: false };+ return {+ lease: active.lease,+ display: active.display,+ controlling: false,+ ...(resumed ? { videoKept: true } : {}),+ };} catch (error) {if (this.active === active) this.stop(peer);throw error;@@ -652,7 +684,7 @@ export class RemoteDesktopController {try {// Wait for held keys/buttons to be released in the old coordinate space.this.deps.stopInput();- this.deps.stopVideo();+ const videoKept = this.holdVideo(request.keepVideo);// Safety effects belong to the old capture/control session, even though// resizing retains its lease. Invalidate pending enables before waiting.await this.clearSafety();@@ -701,6 +733,8 @@ export class RemoteDesktopController {}}if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');+ const resumed = videoKept && (await this.resumeVideo(display));+ if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');this.viewerGeometryManaged = true;active.display = display;active.controlling = false;@@ -710,6 +744,7 @@ export class RemoteDesktopController {lease: active.lease,display,controlling: false,+ ...(resumed ? { videoKept: true } : {}),...(request.op === 'viewerDisplay'? {viewerDisplayRequest: { width: request.width, height: request.height },@@ -880,7 +915,8 @@ export class RemoteDesktopController {return modes;}case 'resolution': {- if (request.temporary) return this.temporaryResolution(peer, active, request.modeId);+ if (request.temporary)+ return this.temporaryResolution(peer, active, request.modeId, request.keepVideo);if (!active.controlling) throw new Error('DESKTOP_VIEW_ONLY');if (!this.deps.resolution) throw new Error('DESKTOP_DISPLAY_MODES_UNAVAILABLE');if (this.inputStarting || this.clipboardPending || this.locking || this.starting)diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.tsindex ad7a329ac6..2ec38b8f15 100644--- a/apps/desktop/src/main/remote-desktop/index.ts+++ b/apps/desktop/src/main/remote-desktop/index.ts@@ -24,6 +24,7 @@ import {isRemoteDesktopChannelRequest,type RemoteDesktopIceRequest,type RemoteDesktopIceReply,+ type RemoteDesktopDisplay,type RemoteDesktopLease,type RemoteDesktopVideoSettings,} from '@cindy/device-link';@@ -214,7 +215,7 @@ let preparingOffer = false;let videoAttempt: string | undefined;let pending: {id: string;- op: 'offer' | 'ice' | 'frame';+ op: 'offer' | 'ice' | 'frame' | 'display-swap';resolve(result: DesktopHostReply): void;reject(error: Error): void;timer: ReturnType<typeof setTimeout>;@@ -223,7 +224,38 @@ let pending: {// failure: release control and keep the lease, capture and media running.const input = new DesktopInputHost(() => remoteDesktop.releaseControl());const clipboardCounter = new ClipboardCounter(resolveDesktopInputBinary);+// A display change holds native capture instead of stopping it: frames pause+// until the changed display is known, then the same stream follows it. The+// capture page also pauses its no-frame timeout, since the change may be slow.+let videoPaused = false;+function pauseVideo(): boolean {+ if (!videoLease || !nativeDisplay || !host || host.isDestroyed()) return false;+ videoPaused = true;+ host.send(DESKTOP_LOCAL.COMMAND, {+ id: randomUUID(),+ op: 'display-hold',+ lease: videoLease,+ } satisfies DesktopHostCommand);+ return true;+}+/** True only when the capture page confirms a live native stream now follows `display`. */+async function resumeVideo(display: RemoteDesktopDisplay): Promise<boolean> {+ if (!videoPaused || !videoLease || !host || host.isDestroyed()) return false;+ const lease = videoLease;+ nativeDisplay = display.id;+ // Helpers bind their capture geometry at start; the next frame restarts them.+ nativeCapture.stop();+ hyprlandCapture.stop();+ videoPaused = false;+ try {+ const kept = await requestHost({ id: randomUUID(), op: 'display-swap', lease }, 2000);+ return kept === true && videoLease === lease;+ } catch {+ return false;+ }+}function stopVideo(): void {+ videoPaused = false;offerGeneration++;portalReady = null;portalGrant = false;@@ -407,7 +439,7 @@ async function offer(/** One bounded command to the existing capture owner; never reset the shared device link. */function requestHost(- command: DesktopHostCommand & { op: 'offer' | 'ice' | 'frame' },+ command: DesktopHostCommand & { op: 'offer' | 'ice' | 'frame' | 'display-swap' },timeoutMs: number,): Promise<DesktopHostReply> {const currentHost = host;@@ -559,6 +591,11 @@ export const remoteDesktop: RemoteDesktopController = new RemoteDesktopControlleviewerDisplay,viewerDisplayRestore: viewerDisplay,channelRequests: true,+ // Native canvas capture can follow a display change without a new offer.+ liveDisplaySwitch:+ process.platform === 'darwin' ||+ (process.platform === 'win32' && windowsAvailable) ||+ Boolean(enabled && nativeWayland()),displayModes: process.platform === 'darwin' || Boolean(linuxDisplays?.length),enabled,canControl:@@ -737,6 +774,8 @@ export const remoteDesktop: RemoteDesktopController = new RemoteDesktopControlle},stopInput: () => input.stop(),releaseInput: () => input.release(),+ pauseVideo,+ resumeVideo,...(process.platform === 'darwin' || supportsLinuxLock()? {lockScreen: async (isCurrent: () => boolean, signal: AbortSignal) => {@@ -893,6 +932,8 @@ export function registerRemoteDesktopIpc(!remoteDesktop.hasLease(lease))throwIpcError('PERMISSION_DENIED', 'Invalid desktop capture lease');+ // Frames from the previous display geometry must not reach the held stream.+ if (videoPaused) return null;const generation = offerGeneration;const jpeg = await (nativeWayland()@@ -1105,6 +1146,7 @@ export function registerRemoteDesktopIpc(/^[A-Za-z0-9+/]+={0,2}$/.test(sdp))))request.resolve(sdp);+ else if (request.op === 'display-swap' && typeof sdp === 'boolean') request.resolve(sdp);else if (request.op === 'ice') {const result = parseDesktopIceReply(sdp);if (result.attemptId !== videoAttempt) throw new Error('DESKTOP_VIDEO_STOPPED');diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/captureAudioRecovery.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/captureAudioRecovery.test.tsindex 33d0748e65..0bb2a02f23 100644--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/captureAudioRecovery.test.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/captureAudioRecovery.test.ts@@ -32,10 +32,14 @@ function setup() {vi.useFakeTimers();const video = media(false);const nativeStop = vi.fn();+ const hold = vi.fn();+ const resume = vi.fn(() => true);vi.mocked(nativeCaptureStream).mockResolvedValue({stream: video,stop: nativeStop,clear: vi.fn(),+ hold,+ resume,} as any);const capture = vi.fn().mockRejectedValue(new Error('NotAllowedError'));vi.stubGlobal('navigator', { mediaDevices: { getDisplayMedia: capture } });@@ -136,6 +140,10 @@ function setup() {api,video,nativeStop,+ hold,+ resume,+ pause: (lease = 'lease') => command({ id: 'hold', op: 'display-hold', lease }),+ swap: (lease = 'lease') => command({ id: 'swap', op: 'display-swap', lease }),peers,capture,reply,@@ -544,3 +552,52 @@ it('answers control requests while input batches fill their own bound', async ()batch(9);expect(h.api.stop).toHaveBeenCalled();});++it('follows a display swap on the same peer without restarting capture', async () => {+ const h = setup();+ h.offer(false);+ await flush();+ const [peer] = h.peers;+ h.pause('other-lease');+ h.swap('other-lease');+ expect(h.hold).not.toHaveBeenCalled();+ expect(h.resume).not.toHaveBeenCalled();+ expect(h.reply).toHaveBeenLastCalledWith('swap', false);+ h.pause();+ expect(h.hold).toHaveBeenCalledOnce();+ h.swap();+ await flush();+ expect(h.resume).toHaveBeenCalledOnce();+ expect(h.reply).toHaveBeenLastCalledWith('swap', true);+ expect(h.peers).toHaveLength(1);+ expect(peer.close).not.toHaveBeenCalled();+ expect(h.nativeStop).not.toHaveBeenCalled();+ expect(h.api.stop).not.toHaveBeenCalled();+});++it('reports a browser-captured stream as not kept, so the video is rebuilt', async () => {+ const h = setup();+ // No cursor overlay: the browser capture succeeds and native is never used.+ h.capture.mockResolvedValueOnce(media(false));+ const nativeStarts = vi.mocked(nativeCaptureStream).mock.calls.length;+ h.offer(false, false);+ await flush();+ expect(h.reply).toHaveBeenCalledWith('offer', 'answer');+ expect(vi.mocked(nativeCaptureStream).mock.calls).toHaveLength(nativeStarts);+ h.pause();+ h.swap();+ await flush();+ expect(h.hold).not.toHaveBeenCalled();+ expect(h.reply).toHaveBeenLastCalledWith('swap', false);+});++it('reports a native stream that already ended as not kept', async () => {+ const h = setup();+ h.offer(false);+ await flush();+ h.resume.mockReturnValueOnce(false);+ h.pause();+ h.swap();+ await flush();+ expect(h.reply).toHaveBeenLastCalledWith('swap', false);+});diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/nativeCaptureStream.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/nativeCaptureStream.test.tsindex e0b03a1b8c..ad490754d6 100644--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/nativeCaptureStream.test.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/nativeCaptureStream.test.ts@@ -8,14 +8,19 @@ afterEach(() => {});function setup() {vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });- const track = { stop: vi.fn() };+ const track = {+ readyState: 'live',+ stop: vi.fn(() => {+ track.readyState = 'ended';+ }),+ };const drawImage = vi.fn();const bitmap = { width: 1600, height: 1000, close: vi.fn() };const canvas = {width: 0,height: 0,getContext: () => ({ drawImage, clearRect: vi.fn() }),- captureStream: vi.fn(() => ({ getTracks: () => [track] })),+ captureStream: vi.fn(() => ({ getTracks: () => [track], getVideoTracks: () => [track] })),};vi.spyOn(document, 'createElement').mockImplementation((() => canvas) as unknown as typeof document.createElement,@@ -117,3 +122,67 @@ it('reports still after a quiet second and moving again on a large change', asynexpect(onMotion).toHaveBeenLastCalledWith(true);owner.stop();});+it('resumes after a display swap by dropping the old frame but keeping the stream and picture', async () => {+ const h = setup();+ const clearRect = vi.fn();+ h.canvas.getContext = () => ({ drawImage: h.drawImage, clearRect });+ const owner = await nativeCaptureStream(+ async () => 'anBlZw==',+ () => true,+ vi.fn(),+ );+ let finish!: (value: ImageBitmap) => void;+ vi.mocked(createImageBitmap).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ await vi.advanceTimersByTimeAsync(67);+ expect(owner.resume()).toBe(true);+ finish(h.bitmap);+ await vi.advanceTimersByTimeAsync(0);+ // Only the initial frame was drawn; the stale one is dropped, not cleared.+ expect(h.drawImage).toHaveBeenCalledOnce();+ expect(clearRect).not.toHaveBeenCalled();+ expect(h.track.stop).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(67);+ expect(h.drawImage).toHaveBeenCalledTimes(2);+ owner.stop();+});+it('keeps a held stream through a display change slower than the no-frame limit', async () => {+ const h = setup();+ let frames = true;+ const failed = vi.fn();+ const owner = await nativeCaptureStream(+ async () => (frames ? 'anBlZw==' : null),+ () => true,+ failed,+ );+ owner.hold();+ frames = false;+ // Creating a virtual display can take up to 8 seconds.+ await vi.advanceTimersByTimeAsync(8000);+ expect(failed).not.toHaveBeenCalled();+ expect(h.track.stop).not.toHaveBeenCalled();+ expect(owner.resume()).toBe(true);+ frames = true;+ await vi.advanceTimersByTimeAsync(67);+ expect(h.drawImage).toHaveBeenCalledTimes(2);+ owner.stop();+});+it('still ends an unheld stream after five seconds without frames and refuses to resume', async () => {+ const h = setup();+ let frames = true;+ const failed = vi.fn();+ const owner = await nativeCaptureStream(+ async () => (frames ? 'anBlZw==' : null),+ () => true,+ failed,+ );+ frames = false;+ await vi.advanceTimersByTimeAsync(5200);+ expect(failed).toHaveBeenCalledOnce();+ expect(h.track.stop).toHaveBeenCalled();+ expect(owner.resume()).toBe(false);+});diff --git a/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts b/apps/desktop/src/renderer/features/remote-desktop/captureHost.tsindex ab47911d9a..480d0ca095 100644--- a/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts@@ -156,6 +156,17 @@ export function startDesktopCaptureHost(api: DesktopCaptureApi): () => void {}return;}+ if (command.op === 'display-hold') {+ if (command.lease === activeLease) native?.hold();+ return;+ }+ if (command.op === 'display-swap') {+ // Only a live native stream follows the new display; browser capture+ // stays on the old one, so the main process rebuilds the video instead.+ const kept = command.lease === activeLease && native?.resume() === true;+ void api.reply(command.id, kept).catch(() => {});+ return;+ }stop();if (command.op !== 'offer' ||diff --git a/apps/desktop/src/renderer/features/remote-desktop/nativeCaptureStream.ts b/apps/desktop/src/renderer/features/remote-desktop/nativeCaptureStream.tsindex 954813ad0f..b7941e012a 100644--- a/apps/desktop/src/renderer/features/remote-desktop/nativeCaptureStream.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/nativeCaptureStream.ts@@ -10,7 +10,13 @@ export async function nativeCaptureStream(cursor: (value: RemoteDesktopCursor | null) => void = () => {},fps = 15,onMotion?: (moving: boolean) => void,-): Promise<{ stream: MediaStream; stop(): void; clear(): void }> {+): Promise<{+ stream: MediaStream;+ stop(): void;+ clear(): void;+ hold(): void;+ resume(): boolean;+}> {const canvas = document.createElement('canvas');const context = canvas.getContext('2d');if (!context) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');@@ -41,6 +47,8 @@ export async function nativeCaptureStream(let timer: ReturnType<typeof setTimeout> | null = null;let epoch = 0;let lastFrame = performance.now();+ // A display change yields no frames for a while; it must not end the stream.+ let held = false;const draw = async () => {const current = epoch;const frame = await read();@@ -84,7 +92,8 @@ export async function nativeCaptureStream(const started = performance.now();try {await draw();- if (performance.now() - lastFrame > 5000) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');+ if (!held && performance.now() - lastFrame > 5000)+ throw new Error('DESKTOP_VIDEO_UNAVAILABLE');if (!stopped && alive())timer = setTimeout(() => void pull(),@@ -104,5 +113,17 @@ export async function nativeCaptureStream(epoch++;context.clearRect(0, 0, canvas.width, canvas.height);},+ hold: () => {+ held = true;+ },+ // Drop frames already requested for the previous display; keep the picture.+ // False when the stream already ended, so the caller rebuilds instead.+ resume: () => {+ if (stopped || stream.getVideoTracks()[0]?.readyState !== 'live') return false;+ held = false;+ epoch++;+ lastFrame = performance.now();+ return true;+ },};}diff --git a/apps/desktop/src/shared/remoteDesktop.ts b/apps/desktop/src/shared/remoteDesktop.tsindex 62ac74bc79..7e98bfd352 100644--- a/apps/desktop/src/shared/remoteDesktop.ts+++ b/apps/desktop/src/shared/remoteDesktop.ts@@ -31,7 +31,15 @@ export const DESKTOP_LOCAL = {export interface DesktopHostCommand {iceServers?: DesktopIceServer[];id: string;- op: 'offer' | 'stop' | 'capture-reset' | 'ice' | 'prepare' | 'frame';+ op:+ | 'offer'+ | 'stop'+ | 'capture-reset'+ | 'display-hold'+ | 'display-swap'+ | 'ice'+ | 'prepare'+ | 'frame';/** Local-only: retain the system-selected Wayland stream for this lease. */portalCapture?: boolean;attemptId?: string;@@ -56,6 +64,8 @@ export interface DesktopLocalState {}export type DesktopHostReply =| string+ /** display-swap: true only when native capture kept a live stream. */+ | boolean| RemoteDesktopIceReply| {error:diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsxindex 63a63897dd..6ad8102765 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx@@ -100,7 +100,7 @@ export function RemoteDesktopControls({notice: string | null;onChange(settings: Partial<RemoteDesktopVideoSettings>): void;readModes(): Promise<RemoteDesktopDisplayMode[]>;- onResolution(id: string): Promise<void>;+ onResolution(mode: RemoteDesktopDisplayMode): Promise<void>;};}) {const { t } = useTranslation();diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsxindex 8e4be2037c..fd0a77259a 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx@@ -50,7 +50,7 @@ type Props = {onFitDisplay?(): void;onChange(settings: Partial<RemoteDesktopVideoSettings>): void;readModes(): Promise<RemoteDesktopDisplayMode[]>;- onResolution(id: string): Promise<void>;+ onResolution(mode: RemoteDesktopDisplayMode): Promise<void>;};connected: boolean;controlling: boolean;@@ -177,7 +177,7 @@ export function RemoteDesktopDisplaySettings({if (!mode || mode.current || !controlling || video.busy || !connected)return;void video- .onResolution(id)+ .onResolution(mode).then(() => setExpanded(false)).catch(() => {});};diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsxindex ec0d79db3b..8209933819 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx@@ -123,6 +123,11 @@ import { RemoteDesktopBackButton } from "./RemoteDesktopBackButton";import { RemoteDesktopWindows } from "./RemoteDesktopWindows";import { RemoteDesktopNetworkStatus } from "./RemoteDesktopNetworkStatus";import type { DesktopNetworkStats } from "./networkStats";+import {+ findRememberedMode,+ readRememberedResolution,+ rememberResolution,+} from "./resolutionMemory";import {RemoteDesktopControls,RemoteDesktopDisconnect,@@ -256,6 +261,28 @@ export function RemoteDesktopSession({);const securityRef = useRef(security);securityRef.current = security;+ // Display changes stop host input, so they wait for the unlock attempt.+ const unlockAttempt = useRef<Promise<void>>(Promise.resolve());+ // A remembered fitted size waiting for this lease's viewport measurement.+ const rememberedFit = useRef<{ lease: string; edge: number } | null>(null);+ // The computer's own system mode for a lease, read before this phone changes+ // it. Choosing it again forgets the remembered resolution.+ const hostMode = useRef<{ lease: string; modeId?: string } | null>(null);+ const noteHostMode = (lease: string, modes: RemoteDesktopDisplayMode[]) => {+ if (hostMode.current?.lease !== lease)+ hostMode.current = {+ lease,+ modeId: modes.find((mode) => mode.current)?.id,+ };+ };+ // Assigned each render below; `connect` runs it before the first video offer.+ const applyRememberedDisplay = useRef(+ async (+ _lease: RemoteDesktopLease,+ _caps: RemoteDesktopCapabilities,+ _isCurrent: () => boolean,+ ) => false,+ );const [lockOnExit, setLockOnExit, lockOnExitLoaded] =useLockOnExitPreference(deviceId);const exitLock = useRef(false);@@ -354,6 +381,10 @@ export function RemoteDesktopSession({height: number;} | null>(null);const [viewerViewport, setViewerViewport] = useState({ width: 0, height: 0 });+ const viewerViewportRef = useRef(viewerViewport);+ viewerViewportRef.current = viewerViewport;+ const windowSizeRef = useRef(windowSize);+ windowSizeRef.current = windowSize;const viewportGeneration = useRef(0);const matchesViewer = (display: { width: number; height: number },@@ -631,31 +662,39 @@ export function RemoteDesktopSession({);const authRef = useRef(auth);authRef.current = auth;+ const loadIceServers = (attemptId: string) =>+ resolveDesktopIceServers(+ () =>+ authRef.current.apiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {+ baseUrl: DEVICE_LINK_API_BASE_URL,+ timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,+ cache: "no-store",+ }),+ (result) =>+ mobileDebugLog("info", "device-link", "remote desktop ICE config", {+ revision: RTC_DIAGNOSTIC_REVISION,+ attempt: attemptId.slice(0, 8),+ ...result,+ }),+ );+ // An ICE lookup started alongside a display change or a connection, so the+ // next media attempt does not wait for the server after it. One-shot.+ const icePrefetch = useRef<{+ at: number;+ servers: ReturnType<typeof resolveDesktopIceServers>;+ } | null>(null);const viewerMedia = useMemo(() =>new RemoteDesktopViewerMedia({request,send,- loadIce: (attemptId) =>- resolveDesktopIceServers(- () =>- authRef.current.apiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {- baseUrl: DEVICE_LINK_API_BASE_URL,- timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,- cache: "no-store",- }),- (result) =>- mobileDebugLog(- "info",- "device-link",- "remote desktop ICE config",- {- revision: RTC_DIAGNOSTIC_REVISION,- attempt: attemptId.slice(0, 8),- ...result,- },- ),- ),+ loadIce: (attemptId) => {+ const prefetched = icePrefetch.current;+ icePrefetch.current = null;+ return prefetched && Date.now() - prefetched.at < 30_000+ ? prefetched.servers+ : loadIceServers(attemptId);+ },current: () => {const lease = active.current,caps = capsRef.current?.value;@@ -806,6 +845,7 @@ export function RemoteDesktopSession({finishBackgroundTransition.current = null;const previous = active.current;abandonChannelRequests();+ icePrefetch.current = null;setExitLockPending(Boolean(previous && exiting && exitLock.current));active.current = null;pendingVideoSettings.current = null;@@ -1091,21 +1131,28 @@ export function RemoteDesktopSession({const firstFrame = new Promise<boolean>((resolve) => {unlockFrame.current = resolve;});- void securityRef.current.maybeUnlock(async () => {- if (- !(await firstFrame) ||- current !== generation.current ||- !focusedRef.current ||- !recovery.current.enabled- )- throw new Error("CREDENTIAL_CANCELLED");- });+ unlockAttempt.current = securityRef.current.maybeUnlock(+ async () => {+ if (+ !(await firstFrame) ||+ current !== generation.current ||+ !focusedRef.current ||+ !recovery.current.enabled+ )+ throw new Error("CREDENTIAL_CANCELLED");+ },+ );}},});const display = next.display;recovery.current.displayId = display.id;mark("capture-started");+ // Overlaps control and the remembered display; video needs it next.+ icePrefetch.current = {+ at: Date.now(),+ servers: loadIceServers("connect"),+ };active.current = next;receiveWindow.current = {since: Date.now(),@@ -1133,12 +1180,24 @@ export function RemoteDesktopSession({}if (current !== generation.current) return;}+ // Switch to the remembered display before the viewer asks for video,+ // so the first frame already has the chosen size.+ if (+ await applyRememberedDisplay.current(+ next,+ result,+ () => current === generation.current && active.current === next,+ )+ ) {+ if (current !== generation.current) return;+ setLease({ ...next });+ }send({type: "init",trickleIce: result.trickleIce === true,epoch: next.lease,- width: display.width,- height: display.height,+ width: next.display.width,+ height: next.display.height,fillHeight: landscape,audio:result.systemAudio &&@@ -1737,8 +1796,32 @@ export function RemoteDesktopSession({if (typeof message.width === "number" &&typeof message.height === "number"- )- void fitViewerDisplay(message.width, message.height);+ ) {+ const pending = rememberedFit.current;+ rememberedFit.current = null;+ const base = viewerDisplaySize(message.width, message.height);+ // Reapply the remembered fitted size at this phone's current ratio.+ const remembered =+ pending?.lease === current.lease && pending.edge && base+ ? fittedDisplayModes(base, base).find(+ (mode) => Math.max(mode.width, mode.height) === pending.edge,+ )+ : undefined;+ if (remembered) {+ // An exact size skips the viewport bookkeeping of a plain fit;+ // record this measurement so restore still recognizes the fit.+ const viewport = { width: message.width, height: message.height };+ setViewerViewport(viewport);+ void fitViewerDisplay(+ remembered.width,+ remembered.height,+ true,+ undefined,+ viewport,+ true,+ );+ } else void fitViewerDisplay(message.width, message.height);+ }break;case "reconnecting":if (message.attemptId === mediaAttempt.current)@@ -2450,6 +2533,7 @@ export function RemoteDesktopSession({op: "displayModes",lease: current.lease,});+ noteHostMode(current.lease, modes);// CoreGraphics modes keep their own orientation when Electron's display// geometry is rotated. Compare modes in the enumeration's coordinate space.const reference = modes.find((mode) => mode.current) ?? { width, height };@@ -2457,35 +2541,24 @@ export function RemoteDesktopSession({matchesViewer(mode, reference.width, reference.height),);};- const changeResolution = async (modeId: string) => {+ // The settings list was just read from the host; reusing its entry saves a+ // round trip. The host still rejects a mode that no longer exists.+ const changeResolution = async (mode: RemoteDesktopDisplayMode) => {const current = active.current;if (!current?.controlling || settingInFlight.current) return;if (- caps?.resolutionRestore ||- (caps?.viewerDisplay && caps.viewerDisplayRestore)+ (caps?.resolutionRestore ||+ (caps?.viewerDisplay && caps.viewerDisplayRestore)) &&+ (caps?.resolutionRestore ||+ [mode.width, mode.height].every((size) => size >= 320 && size <= 2560))) {- try {- const modes = await readResolutionModes();- if (active.current !== current) return;- const mode = modes.find((item) => item.id === modeId);- if (!mode) throw new Error("DESKTOP_DISPLAY_MODE_MISSING");- if (- caps?.resolutionRestore ||- [mode.width, mode.height].every((size) => size >= 320 && size <= 2560)- ) {- await fitViewerDisplay(- mode.width,- mode.height,- true,- !fittedDisplay && caps?.resolutionRestore ? mode.id : undefined,- );- return;- }- } catch {- if (active.current === current)- setSettingNotice(t("remoteDesktop.settingFailed"));- return;- }+ await fitViewerDisplay(+ mode.width,+ mode.height,+ true,+ !fittedDisplay && caps?.resolutionRestore ? mode.id : undefined,+ );+ return;}setSettingNotice(t("remoteDesktop.settingUnsupported"));};@@ -2494,6 +2567,8 @@ export function RemoteDesktopSession({height: number,exactResolution = false,modeId?: string,+ viewport?: { width: number; height: number },+ remembered = false,) => {const current = active.current;if (@@ -2523,8 +2598,11 @@ export function RemoteDesktopSession({setSettingNotice(null);const sourceDisplayId = recovery.current.displayId || current.display.id;send({ type: "control", enabled: false });+ // A host that can follow display changes keeps the running stream; only a+ // response without `videoKept` falls back to rebuilding it.+ const keepVideo = caps?.liveDisplaySwitch === true;try {- viewerMedia.reset();+ if (!keepVideo) viewerMedia.reset();const restore = Boolean(!exactResolution &&fittedDisplay &&@@ -2532,39 +2610,89 @@ export function RemoteDesktopSession({matchesViewer(fittedDisplay, width, height),);const requestGeneration = viewportGeneration.current;- const next = await viewerSession.current.fitDisplay(+ if (!keepVideo)+ icePrefetch.current = {+ at: Date.now(),+ servers: loadIceServers("display"),+ };+ const { videoKept, ...next } = await viewerSession.current.fitDisplay(size.width,size.height,restore,modeId,+ keepVideo,);if (active.current !== current) return;// Reconnect the physical source display after the temporary mirror ends.recovery.current.displayId = sourceDisplayId;+ // The next connection reapplies this choice; restoring or choosing the+ // computer's own mode again forgets it.+ const fittedTo =+ viewport ??+ (exactResolution ? viewerViewportRef.current : { width, height });+ const ownMode =+ hostMode.current?.lease === current.lease &&+ hostMode.current.modeId === modeId;+ void rememberResolution(+ deviceId,+ sourceDisplayId,+ restore || (modeId && ownMode)+ ? null+ : modeId+ ? { kind: "mode", modeId, width, height }+ : fittedTo.width > 0 && fittedTo.height > 0+ ? {+ // The requested size, not the host's logical one: a HiDPI+ // host may answer with a smaller mode of the same ratio,+ // which must not shrink the request on every reconnect.+ kind: "fit",+ width: size.width,+ height: size.height,+ viewport: { ...fittedTo },+ window: {+ width: Math.round(windowSizeRef.current.width),+ height: Math.round(windowSizeRef.current.height),+ },+ }+ : null,+ );if (!exactResolution && viewportGeneration.current === requestGeneration)setViewerViewport({ width, height });+ // Fitted sizes are offered around the plain fit of the viewport.+ const fittedBase = viewport+ ? viewerDisplaySize(viewport.width, viewport.height)+ : null;setFittedDisplay((previous) =>modeId || restore? null- : exactResolution && previous- ? previous+ : exactResolution && (previous ?? fittedBase)+ ? (previous ?? fittedBase): { width: next.display.width, height: next.display.height },);setLease({ ...next });- streaming.current = false;- abandonChannelRequests();- setCanPip(false);- send({- type: "videoSettings",+ const geometry = {width: next.display.width,height: next.display.height,restore: restore || Boolean(modeId),- audio: Boolean(caps?.systemAudio && videoSettingsRef.current.audio),- });+ };+ if (videoKept) send({ type: "displayGeometry", ...geometry });+ else {+ if (keepVideo) viewerMedia.reset();+ streaming.current = false;+ abandonChannelRequests();+ setCanPip(false);+ send({+ type: "videoSettings",+ ...geometry,+ audio: Boolean(caps?.systemAudio && videoSettingsRef.current.audio),+ });+ }const control = await viewerSession.current.control(true);if (active.current === current)applyConfirmedControl(current, control.controlling);} catch (cause) {+ // A reconnect must not retry a remembered choice that just failed.+ if (remembered) rememberedDisplayGaveUp.current = true;if (active.current === current) {setSettingNotice(t("remoteDesktop.settingFailed"));if ((cause as { code?: string })?.code === "INVOKE_TIMEOUT")@@ -2576,6 +2704,169 @@ export function RemoteDesktopSession({setSettingBusy(false);}};+ // The host restores its own mode when a viewer leaves. Reapply this phone's+ // last choice once per lease: before the first video offer when possible,+ // otherwise after control and the first frame are ready.+ const rememberedResolutionLease = useRef<string | null>(null);+ // One early failure (for example a locked computer refusing the change)+ // leaves later connections in this screen to the after-frame path.+ const earlyDisplayFailed = useRef(false);+ // A remembered change that failed once and rebuilt the connection is not+ // retried in this screen, so a persistent failure cannot loop reconnects.+ const rememberedDisplayGaveUp = useRef(false);+ // The early change is optional: a failure keeps the connection going and the+ // after-frame path retries. Once the display change was sent, the host ends+ // the lease on any failure except a refusal before touching the display;+ // a lost reply leaves the geometry unknown, as for a manual change.+ const earlyDisplayFailureEndsConnection = (+ cause: unknown,+ displayChangeSent: boolean,+ ) => {+ const code = remoteDesktopErrorCode(cause);+ if (code === "DESKTOP_LEASE_EXPIRED" || code === "DESKTOP_STOPPED")+ return true;+ return (+ displayChangeSent &&+ code !== "DESKTOP_VIEW_ONLY" &&+ code !== "DESKTOP_DISPLAY_BUSY" &&+ code !== "DESKTOP_INPUT_BUSY"+ );+ };+ applyRememberedDisplay.current = async (current, hostCaps, isCurrent) => {+ if (+ earlyDisplayFailed.current ||+ rememberedDisplayGaveUp.current ||+ !hostCaps.canControl ||+ !wantsControl.current+ )+ return false;+ const remembered = await readRememberedResolution(+ deviceId,+ current.display.id,+ );+ if (!remembered || !isCurrent()) return false;+ const fit = remembered.kind === "fit";+ if (fit ? !hostCaps.viewerDisplay : !hostCaps.resolutionRestore)+ return false;+ // The viewer cannot measure its picture area before video, so reuse the+ // fitted size only in the same app window. Rotation, folding, split view+ // or a resize changes it; the after-frame path then measures this view.+ if (+ fit &&+ (remembered.window?.width !== Math.round(windowSize.width) ||+ remembered.window?.height !== Math.round(windowSize.height))+ )+ return false;+ let displayChangeSent = false;+ try {+ let modeId: string | undefined;+ if (!fit) {+ const modes = await request<RemoteDesktopDisplayMode[]>({+ op: "displayModes",+ lease: current.lease,+ });+ if (!isCurrent()) return false;+ noteHostMode(current.lease, modes);+ const mode = findRememberedMode(modes, remembered);+ if (!mode) return false;+ rememberedResolutionLease.current = current.lease;+ if (mode.current) return false;+ modeId = mode.id;+ }+ const control = await viewerSession.current.control(true);+ if (!isCurrent() || !control.controlling) return false;+ displayChangeSent = true;+ await viewerSession.current.fitDisplay(+ remembered.width,+ remembered.height,+ false,+ modeId,+ );+ if (!isCurrent()) return false;+ rememberedResolutionLease.current = current.lease;+ if (fit) {+ // Same bookkeeping as fitting by hand, so restore is offered.+ setFittedDisplay(+ viewerDisplaySize(+ remembered.viewport.width,+ remembered.viewport.height,+ ) ?? { width: current.display.width, height: current.display.height },+ );+ setViewerViewport(remembered.viewport);+ }+ return true;+ } catch (cause) {+ earlyDisplayFailed.current = true;+ // Let the after-frame path reapply the choice for this lease.+ if (rememberedResolutionLease.current === current.lease)+ rememberedResolutionLease.current = null;+ if (+ isCurrent() &&+ earlyDisplayFailureEndsConnection(cause, displayChangeSent)+ ) {+ rememberedDisplayGaveUp.current = true;+ throw cause;+ }+ return false;+ }+ };+ useEffect(() => {+ const current = active.current;+ if (+ !current?.controlling ||+ !controlReady ||+ !frameReady ||+ !(caps?.resolutionRestore || caps?.viewerDisplay) ||+ fittedDisplay ||+ rememberedDisplayGaveUp.current ||+ rememberedResolutionLease.current === current.lease+ )+ return;+ rememberedResolutionLease.current = current.lease;+ const displayId = recovery.current.displayId || current.display.id;+ const { id, width, height } = current.display;+ // A display change the user made meanwhile wins over the remembered one.+ const unchanged = () =>+ active.current === current &&+ current.display.id === id &&+ current.display.width === width &&+ current.display.height === height;+ void (async () => {+ const remembered = await readRememberedResolution(deviceId, displayId);+ if (!remembered) return;+ await unlockAttempt.current;+ if (!unchanged()) return;+ if (remembered.kind === "fit") {+ // Same path as the button: measure this phone now, then fit.+ if (!caps?.viewerDisplay) return;+ rememberedFit.current = {+ lease: current.lease,+ edge: Math.max(remembered.width, remembered.height),+ };+ send({ type: "measureViewport" });+ return;+ }+ if (!caps?.resolutionRestore) return;+ const mode = findRememberedMode(await readResolutionModes(), remembered);+ if (!mode || mode.current || !unchanged()) return;+ await fitViewerDisplay(+ mode.width,+ mode.height,+ true,+ mode.id,+ undefined,+ true,+ );+ })().catch(() => {});+ }, [+ controlReady,+ frameReady,+ lease?.lease,+ lease?.controlling,+ caps?.resolutionRestore,+ caps?.viewerDisplay,+ fittedDisplay,+ ]);const shortcut = (keys: string[]) =>send({type: "events",diff --git a/apps/mobile/src/remote-desktop/__tests__/resolutionMemory.test.ts b/apps/mobile/src/remote-desktop/__tests__/resolutionMemory.test.tsnew file mode 100644index 0000000000..a5c79adfff--- /dev/null+++ b/apps/mobile/src/remote-desktop/__tests__/resolutionMemory.test.ts@@ -0,0 +1,115 @@+import AsyncStorage from "@react-native-async-storage/async-storage";+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ findRememberedMode,+ readRememberedResolution,+ rememberResolution,+} from "../resolutionMemory";++// Node >= 25 replaces jsdom's localStorage (AsyncStorage's web fallback) with a+// method-less stub, so keep storage in memory like the other mobile tests.+const storage = vi.hoisted(() => {+ const items = new Map<string, string>();+ return {+ items,+ getItem: async (key: string) => items.get(key) ?? null,+ setItem: async (key: string, value: string) => {+ items.set(key, value);+ },+ removeItem: async (key: string) => {+ items.delete(key);+ },+ getAllKeys: async () => [...items.keys()],+ multiRemove: async (keys: readonly string[]) => {+ keys.forEach((key) => items.delete(key));+ },+ clear: async () => items.clear(),+ };+});+vi.mock("@react-native-async-storage/async-storage", () => ({+ default: storage,+}));++const key = "cindy.mobile.remote-desktop.resolution.v1.computer.display";+const modes = [+ { id: "a", width: 1920, height: 1080, current: true },+ { id: "b", width: 2560, height: 1440, current: false },+ { id: "c", width: 2560, height: 1440, current: false },+];++describe("remote desktop resolution memory", () => {+ beforeEach(() => {+ storage.items.clear();+ });++ it("stores the choice per computer and monitor", async () => {+ const mode = {+ kind: "mode" as const,+ modeId: "b",+ width: 2560,+ height: 1440,+ };+ await rememberResolution("computer", "display", mode);+ expect(await readRememberedResolution("computer", "display")).toEqual(mode);+ expect(await readRememberedResolution("computer", "other")).toBeNull();+ expect(await readRememberedResolution("other", "display")).toBeNull();+ });++ it("remembers the fitted size with its viewport and forgets on restore", async () => {+ const fit = {+ kind: "fit" as const,+ width: 658,+ height: 1280,+ viewport: { width: 390, height: 760 },+ };+ await rememberResolution("computer", "display", fit);+ expect(await readRememberedResolution("computer", "display")).toEqual(fit);+ await rememberResolution("computer", "display", null);+ expect(await readRememberedResolution("computer", "display")).toBeNull();+ });++ it("keeps the app window of a fit and drops an invalid one", async () => {+ const fit = {+ kind: "fit" as const,+ width: 658,+ height: 1280,+ viewport: { width: 390, height: 760 },+ };+ const window = { width: 390, height: 844 };+ await rememberResolution("computer", "display", { ...fit, window });+ expect(await readRememberedResolution("computer", "display")).toEqual({+ ...fit,+ window,+ });+ await AsyncStorage.setItem(+ key,+ JSON.stringify({ ...fit, window: { width: "390", height: 844 } }),+ );+ expect(await readRememberedResolution("computer", "display")).toEqual(fit);+ });++ it("ignores malformed stored values", async () => {+ await AsyncStorage.setItem(+ key,+ '{"kind":"mode","modeId":"b","width":"2560","height":1440}',+ );+ expect(await readRememberedResolution("computer", "display")).toBeNull();+ await AsyncStorage.setItem(key, '{"kind":"fit","width":658,"height":1280}');+ expect(await readRememberedResolution("computer", "display")).toBeNull();+ await AsyncStorage.setItem(key, "not json");+ expect(await readRememberedResolution("computer", "display")).toBeNull();+ });++ it("matches the same mode id, then falls back to the same size", () => {+ expect(+ findRememberedMode(modes, { modeId: "c", width: 2560, height: 1440 })?.id,+ ).toBe("c");+ expect(+ findRememberedMode(modes, { modeId: "gone", width: 2560, height: 1440 })+ ?.id,+ ).toBe("b");+ expect(+ findRememberedMode(modes, { modeId: "a", width: 3840, height: 2160 }),+ ).toBeUndefined();+ });+});diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex 9603988219..91409e23d7 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -18,6 +18,29 @@ import { AppState } from "react-native";import { goBackGuarded } from "@/utils/backGuard";import AsyncStorage from "@react-native-async-storage/async-storage";+// Node >= 25 replaces jsdom's localStorage (AsyncStorage's web fallback) with a+// method-less stub, so keep storage in memory like the other mobile tests.+const storage = vi.hoisted(() => {+ const items = new Map<string, string>();+ return {+ items,+ getItem: async (key: string) => items.get(key) ?? null,+ setItem: async (key: string, value: string) => {+ items.set(key, value);+ },+ removeItem: async (key: string) => {+ items.delete(key);+ },+ getAllKeys: async () => [...items.keys()],+ multiRemove: async (keys: readonly string[]) => {+ keys.forEach((key) => items.delete(key));+ },+ clear: async () => items.clear(),+ };+});+vi.mock("@react-native-async-storage/async-storage", () => ({+ default: storage,+}));vi.mock('expo-blur', async () => ({ BlurView: (await import('react-native')).View }));vi.mock("react-native-reanimated", async () => {@@ -373,12 +396,7 @@ const visibleInputHint = () =>const button = (key: string) =>host.querySelector<HTMLButtonElement>(`[aria-label="remoteDesktop.${key}"]`)!;beforeEach(async () => {- await AsyncStorage.removeItem(- "cindy.mobile.remote-desktop.show-mouse-buttons.v1",- ).catch(() => undefined);- await AsyncStorage.removeItem("cindy.mobile.remote-desktop.audio.v1").catch(- () => undefined,- );+ storage.items.clear();(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;vi.clearAllMocks();fixture.beginBackgroundTransition.mockImplementation(@@ -1721,7 +1739,7 @@ describe("remote desktop controls", () => {});it("fetches ICE configuration only through native auth and sends sanitized short-term credentials", async () => {- await connect();+ // The lookup starts with the session, before the viewer asks for it.const iceServers = [{urls: ["turn:relay.example.test:3478"],@@ -1734,6 +1752,7 @@ describe("remote desktop controls", () => {expiresAt: new Date(Date.now() + 3600_000).toISOString(),secret: "must-not-cross-bridge",});+ await connect();await act(async () => {fixture.message!({nativeEvent: {@@ -1764,7 +1783,6 @@ describe("remote desktop controls", () => {});it("drops a late ICE config response after the screen exits", async () => {- await connect();let finish!: (value: unknown) => void;fixture.apiFetch.mockImplementationOnce(() =>@@ -1772,6 +1790,7 @@ describe("remote desktop controls", () => {finish = resolve;}),);+ await connect();await act(async () => {fixture.message!({nativeEvent: {@@ -1920,7 +1939,11 @@ describe("remote desktop controls", () => {expect(mode).toBeDefined();expect(host.textContent).toContain("1920 × 1080");expect(host.textContent).not.toContain("1024 × 768");+ const before = requests().length;await act(async () => mode.click());+ // The listed entry is used as is: no second query before switching+ // (the list refreshes afterwards to mark the new current mode).+ expect(requests()[before]).toMatchObject({ op: "resolution" });expect(requests()).toContainEqual({op: "resolution",lease: "lease",@@ -1941,6 +1964,666 @@ describe("remote desktop controls", () => {},);+ it.each([+ ["host kept the stream", true, true],+ ["host could not keep it", true, false],+ ["host lacks the capability", false, false],+ ])(+ "switches system resolution when the %s",+ async (_name, capability, kept) => {+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ resolutionRestore: true,+ videoSettings: true,+ displayModes: true,+ ...(capability ? { liveDisplaySwitch: true } : {}),+ };+ if (request.op === "displayModes")+ return [+ { id: "current", width: 1920, height: 1080, current: true },+ { id: "4k", width: 3840, height: 2160, current: false },+ ];+ if (request.op === "resolution")+ return {+ lease: "lease",+ display: { id: "display", width: 3840, height: 2160 },+ controlling: false,+ ...(kept ? { videoKept: true } : {}),+ };+ return original(...args);+ });+ await connect();+ act(() => button("operations").click());+ await act(async () => button("displaySettings").click());+ act(() => button("resolution").click());+ fixture.post.mockClear();+ await act(async () =>+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((item) => item.textContent === "3840 × 2160")!+ .click(),+ );+ expect(+ requests().filter((request) => request.op === "resolution"),+ ).toEqual([+ {+ op: "resolution",+ lease: "lease",+ modeId: "4k",+ temporary: true,+ ...(capability ? { keepVideo: true } : {}),+ },+ ]);+ const types = sent().map((message) => message.type);+ if (kept) {+ // Same stream: the viewer only re-lays out the desktop.+ expect(sent()).toContainEqual({+ type: "displayGeometry",+ width: 3840,+ height: 2160,+ restore: true,+ });+ expect(types).not.toContain("videoSettings");+ } else {+ expect(types).toContain("videoSettings");+ expect(types).not.toContain("displayGeometry");+ }+ // Control is taken back either way.+ expect(+ requests().filter((r) => r.op === "control" && r.enabled),+ ).toHaveLength(2);+ },+ );++ it("looks up ICE servers while the display changes and reuses them for the new video", async () => {+ const original = fixture.invoke.getMockImplementation()!;+ let finishDisplay!: () => void;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ viewerDisplay: true,+ viewerDisplayRestore: true,+ videoSettings: true,+ };+ if (request.op === "viewerDisplay") {+ await new Promise<void>((resolve) => {+ finishDisplay = resolve;+ });+ return {+ lease: "lease",+ controlling: false,+ display: { ...display, id: "virtual", width: 986, height: 1920 },+ };+ }+ return original(...args);+ });+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ fixture.apiFetch.mockClear();+ await act(async () =>+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "viewportSize",+ epoch: "lease",+ width: 390,+ height: 760,+ }),+ },+ }),+ );+ // Started together with the display change, not after it.+ expect(fixture.apiFetch).toHaveBeenCalledTimes(1);+ await act(async () => finishDisplay());+ await act(async () =>+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "iceConfig",+ epoch: "lease",+ attemptId: "2",+ }),+ },+ }),+ );+ expect(fixture.apiFetch).toHaveBeenCalledTimes(1);+ expect(+ sent()+ .filter((m) => m.type === "iceConfig")+ .at(-1),+ ).toMatchObject({+ attemptId: "2",+ });+ });++ it("restores the remembered system resolution on the next connection", async () => {+ // The host restores its own mode whenever the viewer leaves.+ let hostMode = "current";+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ resolutionRestore: true,+ videoSettings: true,+ displayModes: true,+ };+ if (request.op === "displayModes")+ return [+ {+ id: "current",+ width: 1920,+ height: 1080,+ current: hostMode === "current",+ },+ { id: "4k", width: 3840, height: 2160, current: hostMode === "4k" },+ ];+ if (request.op === "resolution") {+ hostMode = request.modeId;+ return {+ lease: "lease",+ display: { id: "display", width: 3840, height: 2160 },+ controlling: false,+ };+ }+ if (request.op === "stop") hostMode = "current";+ return original(...args);+ });+ const resolutionRequests = () =>+ requests().filter((request) => request.op === "resolution");+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(resolutionRequests()).toEqual([]);+ act(() => button("operations").click());+ await act(async () => button("displaySettings").click());+ act(() => button("resolution").click());+ const mode = Array.from(+ host.querySelectorAll<HTMLButtonElement>("button"),+ ).find((item) => item.textContent === "3840 × 2160")!;+ await act(async () => mode.click());+ expect(resolutionRequests()).toHaveLength(1);++ await act(async () => root.unmount());+ expect(hostMode).toBe("current");+ fixture.invoke.mockClear();+ fixture.post.mockClear();+ root = createRoot(host);+ act(() => root.render(<RemoteDesktopScreen />));+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(resolutionRequests()).toEqual([+ { op: "resolution", lease: "lease", modeId: "4k", temporary: true },+ ]);+ // Switched before the viewer asked for video: no restart at the new size.+ expect(sent().find((message) => message.type === "init")).toMatchObject({+ width: 3840,+ height: 2160,+ });+ expect(+ sent().filter((message) => message.type === "videoSettings"),+ ).toEqual([]);++ // Already at the remembered mode: reconnecting leaves the host alone.+ await act(async () => root.unmount());+ hostMode = "4k";+ fixture.invoke.mockClear();+ root = createRoot(host);+ act(() => root.render(<RemoteDesktopScreen />));+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(resolutionRequests()).toEqual([]);+ });++ it("forgets the remembered resolution when the computer's own mode is chosen again", async () => {+ await AsyncStorage.setItem(+ "cindy.mobile.remote-desktop.resolution.v1.computer.display",+ JSON.stringify({ kind: "mode", modeId: "4k", width: 3840, height: 2160 }),+ );+ let hostMode = "current";+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ resolutionRestore: true,+ videoSettings: true,+ displayModes: true,+ };+ if (request.op === "displayModes")+ return [+ {+ id: "current",+ width: 1920,+ height: 1080,+ current: hostMode === "current",+ },+ { id: "4k", width: 3840, height: 2160, current: hostMode === "4k" },+ ];+ if (request.op === "resolution") {+ hostMode = request.modeId;+ const size =+ request.modeId === "4k"+ ? { width: 3840, height: 2160 }+ : { width: 1920, height: 1080 };+ return {+ lease: "lease",+ display: { id: "display", ...size },+ controlling: false,+ };+ }+ if (request.op === "stop") hostMode = "current";+ return original(...args);+ });+ const ops = (op: string) =>+ requests().filter((request) => request.op === op);+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(ops("resolution")).toMatchObject([{ modeId: "4k" }]);+ act(() => button("operations").click());+ await act(async () => button("displaySettings").click());+ act(() => button("resolution").click());+ await act(async () =>+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((item) => item.textContent === "1920 × 1080")!+ .click(),+ );+ expect(ops("resolution").at(-1)).toMatchObject({ modeId: "current" });++ await act(async () => root.unmount());+ fixture.invoke.mockClear();+ root = createRoot(host);+ act(() => root.render(<RemoteDesktopScreen />));+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ // Nothing remembered: no mode query and no switch on connect.+ expect(ops("start")).toHaveLength(1);+ expect(ops("displayModes")).toEqual([]);+ expect(ops("resolution")).toEqual([]);+ });++ it("fits this screen again on the next connection until restored", async () => {+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ viewerDisplay: true,+ viewerDisplayRestore: true,+ videoSettings: true,+ displayModes: true,+ };+ if (request.op === "restoreViewerDisplay")+ return { lease: "lease", controlling: false, display };+ if (request.op === "viewerDisplay")+ return {+ lease: "lease",+ controlling: false,+ display: {+ ...display,+ id: "virtual",+ width: request.width,+ height: request.height,+ },+ };+ return original(...args);+ });+ const viewportSize = (width = 390, height = 760) =>+ act(async () =>+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "viewportSize",+ epoch: "lease",+ width,+ height,+ }),+ },+ }),+ );+ const measured = () =>+ sent().filter((message) => message.type === "measureViewport");+ const reconnect = async () => {+ await act(async () => root.unmount());+ fixture.invoke.mockClear();+ fixture.post.mockClear();+ root = createRoot(host);+ act(() => root.render(<RemoteDesktopScreen />));+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ };+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(measured()).toEqual([]);+ await viewportSize();+ const fitted = () =>+ requests().filter((request) => request.op === "viewerDisplay");+ expect(fitted()).toHaveLength(1);+ // Then pick a smaller size from the fitted resolutions.+ act(() => button("operations").click());+ act(() => button("displaySettings").click());+ await act(async () => vi.advanceTimersByTimeAsync(0));+ act(() => button("resolution").click());+ await act(async () =>+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((item) => item.textContent === "658 × 1280")!+ .click(),+ );+ expect(fitted().at(-1)).toMatchObject({ width: 658, height: 1280 });++ // Same orientation: the remembered display exists before any video, so+ // the first stream already has its size and is never restarted.+ await reconnect();+ expect(measured()).toEqual([]);+ expect(fitted()).toEqual([+ { op: "viewerDisplay", lease: "lease", width: 658, height: 1280 },+ ]);+ expect(sent().find((message) => message.type === "init")).toMatchObject({+ width: 658,+ height: 1280,+ });+ expect(+ sent().filter((message) => message.type === "videoSettings"),+ ).toEqual([]);+ // The fit is recognized, so the button offers restore.+ act(() => button("operations").click());+ act(() => button("displaySettings").click());+ expect(button("restoreViewerDisplay")).not.toBeNull();++ // Rotated phone: measure the new viewport after the first frame and keep+ // the chosen long edge.+ fixture.size = { width: 844, height: 390 };+ await reconnect();+ expect(fitted()).toEqual([]);+ expect(measured()).toHaveLength(1);+ await viewportSize(760, 390);+ expect(fitted()).toEqual([+ { op: "viewerDisplay", lease: "lease", width: 1280, height: 658 },+ ]);++ // Restoring the computer's own display forgets the choice.+ act(() => button("operations").click());+ act(() => button("displaySettings").click());+ act(() => button("restoreViewerDisplay").click());+ await viewportSize(760, 390);+ expect(+ requests().filter((request) => request.op === "restoreViewerDisplay"),+ ).toHaveLength(1);+ await reconnect();+ expect(measured()).toEqual([]);+ });++ it("remembers the requested fit when a HiDPI host answers with a smaller mode", async () => {+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ viewerDisplay: true,+ viewerDisplayRestore: true,+ videoSettings: true,+ };+ // Same ratio at half the size, with the request echoed as a receipt.+ if (request.op === "viewerDisplay")+ return {+ lease: "lease",+ controlling: false,+ display: {+ ...display,+ id: "virtual",+ width: request.width / 2,+ height: request.height / 2,+ },+ viewerDisplayRequest: {+ width: request.width,+ height: request.height,+ },+ };+ return original(...args);+ });+ const fitted = () =>+ requests().filter((request) => request.op === "viewerDisplay");+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ await act(async () =>+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "viewportSize",+ epoch: "lease",+ width: 390,+ height: 760,+ }),+ },+ }),+ );+ const [first] = fitted();+ expect(first).toBeDefined();+ await act(async () => root.unmount());+ fixture.invoke.mockClear();+ fixture.post.mockClear();+ root = createRoot(host);+ act(() => root.render(<RemoteDesktopScreen />));+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ // Same window: requested again at the original size, before any video.+ expect(fitted()).toEqual([first]);+ });++ it.each([+ ["a different window in the same orientation", { width: 600, height: 844 }],+ ["no recorded window", undefined],+ ])(+ "measures after the first frame instead of reusing a fit for %s",+ async (_name, window) => {+ await AsyncStorage.setItem(+ "cindy.mobile.remote-desktop.resolution.v1.computer.display",+ JSON.stringify({+ kind: "fit",+ width: 658,+ height: 1280,+ viewport: { width: 390, height: 760 },+ ...(window ? { window } : {}),+ }),+ );+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ viewerDisplay: true,+ viewerDisplayRestore: true,+ videoSettings: true,+ };+ return original(...args);+ });+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(+ requests().filter((request) => request.op === "viewerDisplay"),+ ).toEqual([]);+ expect(sent().find((message) => message.type === "init")).toMatchObject({+ width: display.width,+ height: display.height,+ });+ expect(+ sent().filter((message) => message.type === "measureViewport"),+ ).toHaveLength(1);+ },+ );++ it("does not retry a remembered fit that failed after the first frame", async () => {+ // Another window size: the fit is reapplied only after the first frame.+ await AsyncStorage.setItem(+ "cindy.mobile.remote-desktop.resolution.v1.computer.display",+ JSON.stringify({+ kind: "fit",+ width: 658,+ height: 1280,+ viewport: { width: 390, height: 760 },+ window: { width: 600, height: 844 },+ }),+ );+ // A reconnect gets a fresh lease, as on a real host.+ let starts = 0;+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "start" && ++starts > 1)+ return { ...(await original(...args)), lease: "lease-2" };+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ viewerDisplay: true,+ viewerDisplayRestore: true,+ videoSettings: true,+ };+ if (request.op === "viewerDisplay")+ throw Object.assign(new Error("DESKTOP_DISPLAY_MODE_FAILED"), {+ code: "DESKTOP_DISPLAY_MODE_FAILED",+ });+ return original(...args);+ });+ const measured = () =>+ sent().filter((message) => message.type === "measureViewport");+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(measured()).toHaveLength(1);+ await act(async () =>+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "viewportSize",+ epoch: "lease",+ width: 390,+ height: 760,+ }),+ },+ }),+ );+ expect(+ requests().filter((request) => request.op === "viewerDisplay"),+ ).toHaveLength(1);+ fixture.invoke.mockClear();+ fixture.post.mockClear();+ await act(async () => vi.advanceTimersByTimeAsync(20_000));+ await act(async () => {+ fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } });+ });+ act(() => {+ fixture.message!({+ nativeEvent: { data: '{"type":"framePresented","epoch":"lease-2"}' },+ });+ });+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(starts).toBeGreaterThan(1);+ expect(sent().find((message) => message.type === "init")).toMatchObject({+ epoch: "lease-2",+ });+ expect(measured()).toEqual([]);+ expect(+ requests().filter((request) => request.op === "viewerDisplay"),+ ).toEqual([]);+ });++ it.each([+ ["control", "INVOKE_TIMEOUT", true],+ ["control", "DESKTOP_INPUT_BUSY", true],+ ["control", "DESKTOP_VIEW_ONLY", true],+ // Refused before the host touched the display: the lease is kept.+ ["viewerDisplay", "DESKTOP_VIEW_ONLY", true],+ ["viewerDisplay", "DESKTOP_DISPLAY_BUSY", true],+ ["viewerDisplay", "DESKTOP_INPUT_BUSY", true],+ // The host ends the lease when a sent change fails.+ ["viewerDisplay", "DESKTOP_VIEWER_DISPLAY_UNAVAILABLE", false],+ ["viewerDisplay", "DESKTOP_DISPLAY_MODE_FAILED", false],+ // The change may have happened: geometry is unknown, as for a manual fit.+ ["viewerDisplay", "INVOKE_TIMEOUT", false],+ ["viewerDisplay", "DESKTOP_LEASE_EXPIRED", false],+ ] as const)(+ "an early %s failure (%s) keeps the connection: %s",+ async (failingOp, code, keeps) => {+ await AsyncStorage.setItem(+ "cindy.mobile.remote-desktop.resolution.v1.computer.display",+ JSON.stringify({+ kind: "fit",+ width: 658,+ height: 1280,+ viewport: { width: 390, height: 760 },+ window: { width: 390, height: 844 },+ }),+ );+ let failures = 1;+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation(async (...args) => {+ const request = args[2][0];+ if (request.op === "capabilities")+ return {+ ...(await original(...args)),+ viewerDisplay: true,+ viewerDisplayRestore: true,+ videoSettings: true,+ };+ if (request.op === failingOp && failures > 0) {+ failures--;+ throw Object.assign(new Error(code), { code });+ }+ if (request.op === "viewerDisplay")+ return {+ lease: "lease",+ controlling: false,+ display: { ...display, id: "virtual", width: 658, height: 1280 },+ };+ return original(...args);+ });+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(failures).toBe(0);+ const init = sent().find((message) => message.type === "init");+ if (!keeps) {+ expect(init).toBeUndefined();+ // The reconnect stays at the computer's own size and never retries+ // the failed choice, so a persistent failure cannot loop.+ fixture.invoke.mockClear();+ fixture.post.mockClear();+ await act(async () => vi.advanceTimersByTimeAsync(20_000));+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(0));+ expect(+ requests().filter((request) => request.op === "start").length,+ ).toBeGreaterThan(0);+ expect(sent().find((message) => message.type === "init")).toMatchObject(+ { width: display.width, height: display.height },+ );+ expect(+ requests().filter((request) => request.op === "viewerDisplay"),+ ).toEqual([]);+ expect(+ sent().filter((message) => message.type === "measureViewport"),+ ).toEqual([]);+ return;+ }+ // Same session at the current size; the after-frame path fits again.+ expect(init).toMatchObject({+ width: display.width,+ height: display.height,+ });+ expect(requests().filter((request) => request.op === "stop")).toEqual([]);+ expect(+ sent().filter((message) => message.type === "measureViewport"),+ ).toHaveLength(1);+ },+ );+it.each([[false, 390, 760, 658, 1280],[true, 760, 390, 1280, 658],diff --git a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewer.test.tsindex a9a42c4a9b..b1cebdf28b 100644--- a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts+++ b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts@@ -264,6 +264,42 @@ function viewer(rtc = false, frameCallback = true, nativeMedia = false) {};}+describe("display change with a kept stream", () => {+ it("only re-lays out the desktop without reconnecting media", () => {+ const v = viewer(true);+ v.send({ type: "init", epoch: "one", width: 1920, height: 1080 });+ const negotiations = () =>+ v.messages.filter((m) => m.type === "iceConfig").length;+ const before = negotiations();+ expect(before).toBe(1);+ v.send({ type: "mouseButtons", topInset: 0, bottomInset: 100 });+ v.send({ type: "displayGeometry", width: 800, height: 1000 });+ expect(v.elements.video.style).toMatchObject({+ width: "400px",+ height: "500px",+ });+ expect(negotiations()).toBe(before);+ // Invalid geometry is ignored rather than distorting the layout.+ v.send({ type: "displayGeometry", width: 100, height: 1000 });+ expect(v.elements.video.style).toMatchObject({ width: "400px" });+ });++ it("moves the native video frame to the new geometry", () => {+ const v = viewer(true, true, true);+ v.send({ type: "init", epoch: "native", width: 1920, height: 1080 });+ const viewport = () =>+ v.messages.findLast((m) => m.type === "nativeViewport") as unknown as {+ width: number;+ height: number;+ };+ const wide = viewport();+ v.send({ type: "displayGeometry", width: 900, height: 1600 });+ const tall = viewport();+ expect(tall.width / tall.height).toBeCloseTo(900 / 1600, 2);+ expect(wide.width / wide.height).toBeCloseTo(1920 / 1080, 2);+ });+});+describe("native media overlay", () => {it("leaves RTC negotiation to native and shares the exact input geometry", () => {const v = viewer(true, true, true);diff --git a/apps/mobile/src/remote-desktop/resolutionMemory.ts b/apps/mobile/src/remote-desktop/resolutionMemory.tsnew file mode 100644index 0000000000..32a0095e80--- /dev/null+++ b/apps/mobile/src/remote-desktop/resolutionMemory.ts@@ -0,0 +1,78 @@+import AsyncStorage from "@react-native-async-storage/async-storage";+import type { RemoteDesktopDisplayMode } from "@cindy/device-link";++// Non-secret, phone-local: the last display choice this phone made for one+// monitor of one computer. The host still restores its own display on+// disconnect. "fit" keeps the virtual display size, the phone viewport it was+// fitted to and the app window at that time, so the next connection in the+// same window can create it before any video.+type Size = { width: number; height: number };+export type RememberedResolution =+ | ({ kind: "mode"; modeId: string } & Size)+ | ({ kind: "fit"; viewport: Size; window?: Size } & Size);++let writes: Promise<void> = Promise.resolve();+const storageKey = (deviceId: string, displayId: string) =>+ `cindy.mobile.remote-desktop.resolution.v1.${encodeURIComponent(deviceId)}.${encodeURIComponent(displayId)}`;++/** `null` forgets the choice, so the computer keeps its own display next time. */+export function rememberResolution(+ deviceId: string,+ displayId: string,+ value: RememberedResolution | null,+): Promise<void> {+ const key = storageKey(deviceId, displayId);+ writes = writes+ .then(() =>+ value+ ? AsyncStorage.setItem(key, JSON.stringify(value))+ : AsyncStorage.removeItem(key),+ )+ .catch(() => undefined);+ return writes;+}++export async function readRememberedResolution(+ deviceId: string,+ displayId: string,+): Promise<RememberedResolution | null> {+ try {+ await writes;+ const raw = await AsyncStorage.getItem(storageKey(deviceId, displayId));+ if (!raw) return null;+ const value = JSON.parse(raw) as Record<string, unknown> | null;+ const size = (item: unknown): Size | null => {+ const { width, height } = (item ?? {}) as Record<string, unknown>;+ return Number.isInteger(width) &&+ Number.isInteger(height) &&+ (width as number) > 0 &&+ (height as number) > 0+ ? { width: width as number, height: height as number }+ : null;+ };+ const display = size(value);+ if (!display) return null;+ if (value?.kind === "mode" && typeof value.modeId === "string")+ return { kind: "mode", modeId: value.modeId, ...display };+ const viewport = size(value?.viewport);+ const window = size(value?.window);+ return value?.kind === "fit" && viewport+ ? { kind: "fit", viewport, ...display, ...(window ? { window } : {}) }+ : null;+ } catch {+ return null;+ }+}++/** Mode IDs may change after OS or monitor updates; fall back to the same size. */+export function findRememberedMode(+ modes: RemoteDesktopDisplayMode[],+ remembered: { modeId: string } & Size,+): RemoteDesktopDisplayMode | undefined {+ const sameSize = (mode: RemoteDesktopDisplayMode) =>+ mode.width === remembered.width && mode.height === remembered.height;+ return (+ modes.find((mode) => mode.id === remembered.modeId && sameSize(mode)) ??+ modes.find(sameSize)+ );+}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 0f626c1af2..1bdde4e5f3 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -147,6 +147,20 @@ Mobile 未新增卡片入口。服务端无需改动。不得退回会留下系统分辨率变化的旧路径;不支持的选择返回“不支持”。旧控制端的无`temporary` 请求及响应保持兼容,其旧行为不代表新恢复能力已生效。此扩展不修改 relay。+### 切换显示时保留视频++被控端以可选能力 `liveDisplaySwitch` 声明:原生画布截屏(macOS、Windows 原生、Hyprland)+切换显示时可以保留同一条视频连接。新版控制端仅在该能力为真时,给 `resolution { temporary: true }`、+`viewerDisplay`、`restoreViewerDisplay` 附加 `keepVideo: true`(只接受布尔值)。被控端实际保留了+视频才在响应里附加 `videoKept: true`;控制端以这个回执为准,缺失时按原流程重建视频。+能力只说明显示器支持原生截屏,不代表本次连接在用它:切换前主进程通知截屏页暂停“5 秒无新帧即停流”,+切换后由截屏页确认当前确实是原生截屏且视频流仍在,才算保留;浏览器截屏、流已结束或确认超时一律+按原流程拆掉重建。+旧被控端丢弃不认识的 `keepVideo`,照旧拆掉重建;旧控制端不发 `keepVideo`,新被控端照旧拆掉重建。+切换失败仍只结束本次远程桌面 lease。不修改 relay、IPC allowlist 或协议版本;先发被控端。+实现见 `apps/desktop/src/main/remote-desktop/controller.ts`,回归见同目录 `__tests__/controller.test.ts`+与 `packages/device-link/src/__tests__/viewerDisplay.test.ts`。+## 远程桌面窗口操作新增可选能力 `windowActions`,只在支持的主机上发送 `windowAction`:`list` 返回有界窗口diff --git a/docs/remote-desktop-viewer-aspect-prototype.md b/docs/remote-desktop-viewer-aspect-prototype.mdindex 84d22824d6..1e5eb132a9 100644--- a/docs/remote-desktop-viewer-aspect-prototype.md+++ b/docs/remote-desktop-viewer-aspect-prototype.md@@ -33,7 +33,15 @@ continue to offer matching only.- Resizing preserves the lease and input sequence; old video/input are stopped,queued old-geometry input is discarded, and the viewer negotiates video andreacquires control on the confirmed new display. Shared Device Link connections- are not restarted.+ are not restarted. Hosts advertising `liveDisplaySwitch` instead keep the+ existing video connection when the Mobile viewer asks with `keepVideo`; the+ viewer only updates its layout (`displayGeometry`) and reacquires control.+- Mobile remembers the last choice per computer and monitor (system mode, or the+ fitted size with the viewport and app window it was fitted in) and reapplies+ it before the first frame of the next connection. A fit is reused early only+ in the same app window; after a rotation, fold, split view or resize it is+ refitted from a fresh measurement after the first frame. Choosing the+ computer's own mode or restoring forgets it.- Failure ends only this remote-desktop lease and restores its temporary display.The viewer's existing recovery remains responsible for reconnecting.- On hosts advertising both viewer-display capabilities, the resolution dropdowndiff --git a/packages/device-link/src/__tests__/viewerDisplay.test.ts b/packages/device-link/src/__tests__/viewerDisplay.test.tsindex be8d69d39b..4064f96d09 100644--- a/packages/device-link/src/__tests__/viewerDisplay.test.ts+++ b/packages/device-link/src/__tests__/viewerDisplay.test.ts@@ -212,3 +212,81 @@ it("keeps explicit system modes exact even with a virtual-display acknowledgemen"INVALID_RESPONSE",);});++describe("live display switch", () => {+ it("accepts keepVideo only as a boolean on the three display changes", () => {+ for (const request of [+ { op: "viewerDisplay", lease: "lease", width: 900, height: 1600 },+ { op: "restoreViewerDisplay", lease: "lease" },+ { op: "resolution", lease: "lease", modeId: "1", temporary: true },+ ]) {+ expect(+ parseRemoteDesktopRequest({ ...request, keepVideo: true }),+ ).toEqual({ ...request, keepVideo: true });+ // false is the legacy behaviour and stays off the wire.+ expect(+ parseRemoteDesktopRequest({ ...request, keepVideo: false }),+ ).toEqual(request);+ expect(() =>+ parseRemoteDesktopRequest({ ...request, keepVideo: "true" }),+ ).toThrow("INVALID_REQUEST");+ }+ // Other operations never read it.+ expect(+ parseRemoteDesktopRequest({+ op: "displayModes",+ lease: "lease",+ keepVideo: "ignored",+ }),+ ).toEqual({ op: "displayModes", lease: "lease" });+ });++ it("asks to keep video only when requested and reports only an acknowledged keep", async () => {+ let kept = true;+ const request = vi.fn(async (value) => {+ if (value.op === "capabilities")+ return { version: 1, enabled: true, displays: [{ id: "1" }] };+ if (value.op === "start")+ return {+ lease: "lease",+ display: { id: "1", width: 1920, height: 1080 },+ controlling: false,+ };+ if (value.op === "control") return { controlling: value.enabled };+ return {+ lease: "lease",+ display: { id: "1", width: 3840, height: 2160 },+ controlling: false,+ ...(kept ? { videoKept: true } : {}),+ };+ });+ const session = new RemoteDesktopViewerSession(+ request as DesktopViewerRequest,+ );+ await session.connect({ isCurrent: () => true });+ await session.control(true);+ const kept1 = await session.fitDisplay(3840, 2160, false, "4", true);+ expect(request).toHaveBeenLastCalledWith(+ {+ op: "resolution",+ lease: "lease",+ modeId: "4",+ temporary: true,+ keepVideo: true,+ },+ expect.any(Function),+ );+ expect(kept1.videoKept).toBe(true);+ // The shared lease itself never carries the per-change flag.+ expect(session.lease?.videoKept).toBeUndefined();+ await session.control(true);+ // Not requested: an unexpected acknowledgement is not surfaced.+ const legacy = await session.fitDisplay(3840, 2160, false, "4");+ expect(request.mock.calls.at(-1)?.[0]).not.toHaveProperty("keepVideo");+ expect(legacy.videoKept).toBeUndefined();+ await session.control(true);+ kept = false;+ const torn = await session.fitDisplay(3840, 2160, false, "4", true);+ expect(torn.videoKept).toBeUndefined();+ });+});diff --git a/packages/device-link/src/remoteDesktop.ts b/packages/device-link/src/remoteDesktop.tsindex ec39a6dfba..c8fb22c2fb 100644--- a/packages/device-link/src/remoteDesktop.ts+++ b/packages/device-link/src/remoteDesktop.ts@@ -167,6 +167,8 @@ export interface RemoteDesktopCapabilities {* send them otherwise: older hosts end the session on unknown channel data.*/channelRequests?: boolean;+ /** Display changes requested with `keepVideo` may keep the live video stream. */+ liveDisplaySwitch?: boolean;backgroundViewing?: boolean;cursorOverlay?: boolean;clipboardText?: boolean;@@ -204,6 +206,8 @@ export interface RemoteDesktopLease {controlling: boolean;/** Acknowledges the requested virtual mode when OS logical geometry differs. */viewerDisplayRequest?: { width: number; height: number };+ /** The display change kept the existing video stream; no new offer is needed. */+ videoKept?: boolean;}export type RemoteDesktopRequest =| { op: "windowAction"; lease: string; action: "list" | "desktop" }@@ -243,9 +247,21 @@ export type RemoteDesktopRequest =| { op: "clipboard"; lease: string; action: "copy" }| { op: "clipboard"; lease: string; action: "paste"; text: string }| { op: "displayModes"; lease: string }- | { op: "viewerDisplay"; lease: string; width: number; height: number }- | { op: "restoreViewerDisplay"; lease: string }- | { op: "resolution"; lease: string; modeId: string; temporary?: boolean };+ | {+ op: "viewerDisplay";+ lease: string;+ width: number;+ height: number;+ keepVideo?: boolean;+ }+ | { op: "restoreViewerDisplay"; lease: string; keepVideo?: boolean }+ | {+ op: "resolution";+ lease: string;+ modeId: string;+ temporary?: boolean;+ keepVideo?: boolean;+ };export function parseRemoteDesktopRequest(value: unknown,@@ -362,7 +378,14 @@ export function parseRemoteDesktopRequest(typeof v.enabled === "boolean")return { op: v.op, lease, enabled: v.enabled };- if (v.op === "restoreViewerDisplay") return { op: v.op, lease };+ // Optional on display changes only; older hosts drop it and tear down video.+ const keepVideo = () => {+ if (v.keepVideo !== undefined && typeof v.keepVideo !== "boolean")+ throw new Error("INVALID_REQUEST");+ return v.keepVideo === true ? { keepVideo: true as const } : {};+ };+ if (v.op === "restoreViewerDisplay")+ return { op: v.op, lease, ...keepVideo() };if (v.op === "displayModes") return { op: v.op, lease };if (v.op === "viewerDisplay") {if (@@ -380,6 +403,7 @@ export function parseRemoteDesktopRequest(lease,width: v.width as number,height: v.height as number,+ ...keepVideo(),};}if (@@ -394,6 +418,7 @@ export function parseRemoteDesktopRequest(lease,modeId: v.modeId,...(v.temporary === true ? { temporary: true } : {}),+ ...keepVideo(),};}if (v.op === "offer" && typeof v.sdp === "string" && v.sdp.length <= 64_000) {diff --git a/packages/device-link/src/remoteDesktopViewerSession.ts b/packages/device-link/src/remoteDesktopViewerSession.tsindex 0af41f0c38..0306653401 100644--- a/packages/device-link/src/remoteDesktopViewerSession.ts+++ b/packages/device-link/src/remoteDesktopViewerSession.ts@@ -162,12 +162,17 @@ export class RemoteDesktopViewerSession {return { controlling: lease.controlling };}- /** Keep the lease and input sequence, replacing only its display geometry. */+ /**+ * Keep the lease and input sequence, replacing only its display geometry.+ * With `keepVideo`, a host advertising `liveDisplaySwitch` may also keep the+ * current video stream; the result then carries `videoKept: true`.+ */async fitDisplay(width: number,height: number,restore = false,modeId?: string,+ keepVideo = false,): Promise<RemoteDesktopLease> {const lease = this.active;if (!lease?.controlling) throw new Error("DESKTOP_VIEW_ONLY");@@ -178,10 +183,26 @@ export class RemoteDesktopViewerSession {};const operation = this.request<RemoteDesktopLease>(modeId- ? { op: "resolution", lease: lease.lease, modeId, temporary: true }+ ? {+ op: "resolution",+ lease: lease.lease,+ modeId,+ temporary: true,+ ...(keepVideo ? { keepVideo: true } : {}),+ }: restore- ? { op: "restoreViewerDisplay", lease: lease.lease }- : { op: "viewerDisplay", lease: lease.lease, width, height },+ ? {+ op: "restoreViewerDisplay",+ lease: lease.lease,+ ...(keepVideo ? { keepVideo: true } : {}),+ }+ : {+ op: "viewerDisplay",+ lease: lease.lease,+ width,+ height,+ ...(keepVideo ? { keepVideo: true } : {}),+ },check,);this.controlPending = operation;@@ -219,7 +240,9 @@ export class RemoteDesktopViewerSession {throw new Error("INVALID_RESPONSE");lease.display = result.display;lease.controlling = false;- return lease;+ return keepVideo && result.videoKept === true+ ? { ...lease, videoKept: true }+ : lease;} finally {if (this.controlPending === operation) this.controlPending = null;}diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.jsindex eaf55868bb..4b19f680d0 100644--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.js+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js@@ -2042,6 +2042,27 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {listen(video, "webkitpresentationmodechanged", reportPresentation);listen(video, "enterpictureinpicture", reportPresentation);listen(video, "leavepictureinpicture", reportPresentation);+ function applyDisplayGeometry(message) {+ if (+ !Number.isInteger(message.width) ||+ !Number.isInteger(message.height) ||+ message.width < 320 ||+ message.height < 320 ||+ (message.restore !== true &&+ (message.width > 2560 || message.height > 2560))+ )+ return;+ release();+ stopPanAnimation();+ viewerSized = message.restore !== true;+ zoom = 1;+ desktopScale = null;+ fx = fy = 0.5;+ followRest = null;+ dw = message.width;+ dh = message.height;+ render();+ }function receive(event) {let message;try {@@ -2112,29 +2133,15 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {}break;case "videoSettings":- if (- Number.isInteger(message.width) &&- Number.isInteger(message.height) &&- message.width >= 320 &&- message.height >= 320 &&- (message.restore === true ||- (message.width <= 2560 && message.height <= 2560))- ) {- release();- stopPanAnimation();- viewerSized = message.restore !== true;- zoom = 1;- desktopScale = null;- fx = fy = 0.5;- followRest = null;- dw = message.width;- dh = message.height;- render();- }+ applyDisplayGeometry(message);video.muted = !message.audio;retries = 0;if (!config.nativeMedia) connect();break;+ // The host kept the stream across a display change: layout only.+ case "displayGeometry":+ applyDisplayGeometry(message);+ break;case "keyboard":showKeyboard(message.enabled === true);break;diff --git a/packages/maker-shared/src/remote-desktop/viewerSource.ts b/packages/maker-shared/src/remote-desktop/viewerSource.tsindex f87dd909f3..7e790ec0a6 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 let nativeVideoActive = false;\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 fit = fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh));\n // Pinch stops at two viewer points per desktop point, never below fit.\n const maxZoom = Math.max(1, 2 / fit);\n const scale = fit * Math.max(1, Math.min(maxZoom, 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, maxZoom };\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 // Shared ambient backdrop. Minimal viewer embeds may omit its subtree.\n const bg = find(\"bg\") || null,\n bgCanvas = find(\"bg-canvas\") || null,\n bgContext = bgCanvas ? bgCanvas.getContext(\"2d\") : null;\n let dw = 1920,\n dh = 1080,\n viewerSized = false,\n zoom = 1,\n desktopScale = null,\n reportedScaleMode = null,\n desktopPan = null,\n edgePointer = null,\n edgeFrame = null,\n edgeTime = 0,\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 pendingSince = 0,\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 let nativeMouseControls = false;\n const mouseControlHandlers = new Map();\n function listenMouse(el, type, handler) {\n listen(el, type, handler);\n mouseControlHandlers.set(el.id + \":\" + type, handler);\n }\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 fitToInsets = false;\n const usesViewportInsets = () => viewerSized || fitToInsets;\n let panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n viewportTopInset = 0,\n keyboardViewportInset = 0,\n portraitKeyboardTopInset = 0;\n let keyboardViewportOpen = false;\n let keyboardFitWidth = null;\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 usableHeight = () =>\n Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);\n const viewportHeight = () =>\n usesViewportInsets() ? usableHeight() : Math.max(1, stage.clientHeight);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n // Center between the measured top controls and the keyboard edge (stage bottom).\n // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.\n // Keep the fitted size and cap the shift when the desktop is too tall to fit.\n const verticalOffset = (height) =>\n (usesViewportInsets() ? viewportTopInset : 0) +\n (fillHeight\n ? 0\n : Math.min(\n Math.max(\n 0,\n portraitKeyboardTopInset - (usesViewportInsets() ? viewportTopInset : 0),\n ) / 2,\n Math.max(0, (viewportHeight() - height) / 2),\n ));\n const layout = () => {\n const r =\n config.desktop && desktopScale !== null\n ? {\n scale: desktopScale,\n width: dw * desktopScale,\n height: dh * desktopScale,\n maxZoom: 1,\n }\n : transform(\n keyboardFitWidth?.stageWidth === stage.clientWidth\n ? keyboardFitWidth.width : viewportWidth(),\n viewportHeight(),\n dw,\n dh,\n zoom,\n fx,\n fy,\n // Mobile fits both axes; retain Desktop scale semantics.\n config.desktop ? fillHeight && !viewerSized : false,\n );\n return {\n ...r,\n x: viewportLeft() + viewportWidth() / 2 - fx * r.width,\n y: viewportHeight() / 2 + verticalOffset(r.height) - fy * r.height,\n };\n };\n // 0 at fit, 1 at the pinch limit for the current viewport and display.\n const zoomProgress = (r = layout()) =>\n r.maxZoom > 1\n ? Math.max(0, Math.min(1, (zoom - 1) / (r.maxZoom - 1)))\n : 0;\n // The backdrop uses 5% / 90% / 5% source segments. The middle 90%\n // keeps the fitted picture's scale; each outer 5% stretches uniformly\n // to fill the remaining space, horizontally or vertically as needed.\n // Zoom and pan never move the backdrop: where the picture covers it, the\n // opaque picture simply occludes it, so input mapping stays uniform. Returns\n // null when the fitted picture already covers the stage, unless a Desktop\n // viewer has shrunk its foreground below fit and still needs the backdrop.\n const bgEdgeFraction = 0.05;\n const bgCenterFraction = 1 - 2 * bgEdgeFraction;\n function backgroundSegments(vw, vh, dw, dh, fill, includeFitted = false) {\n if (!(vw > 0 && vh > 0 && dw > 0 && dh > 0)) return null;\n const s = fill\n ? vh / Math.max(1, dh)\n : Math.min(vw / dw, vh / Math.max(1, dh));\n const w = dw * s,\n h = dh * s;\n if (w < vw || (includeFitted && w === vw && h === vh)) {\n const centerW = w * bgCenterFraction,\n centerX = vw / 2 - centerW / 2,\n sideW = centerX,\n top = (vh - h) / 2;\n return { axis: \"x\", s, w, h, top, centerW, centerX, sideW };\n }\n if (h < vh) {\n const centerH = h * bgCenterFraction,\n centerY = vh / 2 - centerH / 2,\n sideH = centerY,\n left = (vw - w) / 2;\n return { axis: \"y\", s, w, h, left, centerH, centerY, sideH };\n }\n return null;\n }\n // Native video renders beneath this WebView, so z-order cannot hide the\n // status behind the picture; cut the picture's rectangle out instead.\n // Measure the status only after its text or the stage changes, not per frame.\n let statusOrigin = null;\n function clipNetworkStatus(r = layout()) {\n const status = find(\"network-status\");\n if (!status) return;\n if (!nativeVideoActive || status.style.display === \"none\") {\n status.style.clipPath = \"\";\n return;\n }\n if (!statusOrigin)\n statusOrigin = { x: status.offsetLeft, y: status.offsetTop };\n const left = r.x - statusOrigin.x,\n top = r.y - statusOrigin.y,\n right = left + r.width,\n bottom = top + r.height;\n status.style.clipPath = `polygon(evenodd,0 0,100% 0,100% 100%,0 100%,0 0,${left}px ${top}px,${right}px ${top}px,${right}px ${bottom}px,${left}px ${bottom}px,${left}px ${top}px)`;\n }\n function paintBackground() {\n if (nativeVideoActive) {\n if (bg) bg.style.display = \"none\";\n return;\n }\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const picture = config.desktop ? layout() : null;\n const coversStage =\n picture &&\n picture.x <= 0 &&\n picture.y <= 0 &&\n picture.x + picture.width >= vw &&\n picture.y + picture.height >= vh;\n const seg = coversStage\n ? null\n : backgroundSegments(vw, vh, dw, dh, config.desktop ? fillHeight : false, config.desktop);\n if (!seg) {\n bg.style.display = \"none\";\n bgRects = null;\n stopBackgroundLoop();\n return;\n }\n bg.style.display = \"block\";\n bgAxis = seg.axis;\n // The ambient layer also fills the notch and the area beneath native\n // controls. Only the interactive picture respects viewport insets.\n const originX = 0;\n // Source segments are resolved at draw time from the live source dimensions;\n // these dest rects only encode where each segment lands on the stage.\n bgRects =\n seg.axis === \"x\"\n ? [\n {\n x: originX,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX,\n y: seg.top,\n w: seg.centerW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX + seg.centerW,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n ]\n : [\n {\n x: seg.left,\n y: 0,\n w: seg.w,\n h: seg.sideH,\n },\n {\n x: seg.left,\n y: seg.centerY,\n w: seg.w,\n h: seg.centerH,\n },\n {\n x: seg.left,\n y: seg.centerY + seg.centerH,\n w: seg.w,\n h: seg.sideH,\n },\n ];\n // Keep the backing store at stage resolution (capped) so the stretched\n // edges stay crisp without oversized allocations.\n bgDpr = Math.min(2, window.devicePixelRatio || 1);\n const bw = Math.round(stage.clientWidth * bgDpr),\n bh = Math.round(vh * bgDpr);\n if (bgCanvas.width !== bw || bgCanvas.height !== bh) {\n bgCanvas.width = bw;\n bgCanvas.height = bh;\n }\n scheduleBackgroundDraw();\n startBackgroundLoop();\n }\n // One canvas, three draws: each source segment stretches into whatever bar\n // the picture leaves open. The live video feeds it once presented; until\n // then the decoded JPEG frame does, so the backdrop always matches the\n // picture's own pixels and scale in the center segment.\n let bgRects = null,\n bgAxis = \"x\",\n bgDpr = 1,\n bgDrawFrame = null,\n bgLoopFrame = null;\n function drawBackground() {\n if (!bgContext || !bgRects) return;\n const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n // Cursor updates can schedule a repaint while the next JPEG is loading.\n // Keep the last backdrop until the replacement has drawable pixels.\n if ((!useVideo && !image.complete) || !(sw > 0 && sh > 0)) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\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 * zoomProgress(r);\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 + verticalOffset(r.height),\n maxY: y.max + verticalOffset(r.height),\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 + verticalOffset(r.height) - 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 + 40 * zoomProgress();\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 = (viewportHeight() / 2 + verticalOffset(r.height) - 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(\n bottom - 1,\n (usesViewportInsets() ? viewportTopInset : 0) + 8 + hotY,\n );\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 if (config.nativeMedia && epoch)\n post({\n type: \"nativeViewport\",\n fillHeight: false,\n x: r.x,\n y: r.y,\n width: r.width,\n height: r.height,\n });\n if (config.desktop && epoch) {\n const scaleMode =\n desktopScale === null\n ? \"fit\"\n : desktopScale === 1\n ? \"actual\"\n : \"custom\";\n if (reportedScaleMode !== scaleMode) {\n reportedScaleMode = scaleMode;\n post({ type: \"scaleMode\", mode: scaleMode });\n }\n }\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 clipNetworkStatus(r);\n paintBackground();\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\")\n ? \"block\"\n : \"none\";\n }\n if (config.desktop) {\n // Let the local OS own pointer size, DPI and accessibility preferences.\n // Never use a remote URL or bitmap as the desktop's native cursor.\n cursor.style.display = \"none\";\n const shape = remoteCursor?.shape;\n stage.style.cursor =\n control &&\n [\n \"default\",\n \"text\",\n \"vertical-text\",\n \"pointer\",\n \"crosshair\",\n \"grab\",\n \"grabbing\",\n \"ew-resize\",\n \"ns-resize\",\n \"nwse-resize\",\n \"nesw-resize\",\n \"move\",\n \"not-allowed\",\n \"copy\",\n \"alias\",\n \"wait\",\n \"progress\",\n \"help\",\n ].includes(shape)\n ? shape\n : \"default\";\n }\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 (!pending.length) pendingSince = performance.now();\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) return;\n // Input is an intent about the picture the user saw, not durable work.\n // Never replay old clicks/typing after a stalled ACK or data channel drains.\n if (performance.now() - pendingSince >= 2000) {\n pending = [];\n control = false;\n release();\n updateMouseButtons();\n post({ type: \"inputOverflow\" });\n return;\n }\n if (sending) return;\n // Do not route around a congested live data channel: the relay could\n // overtake its already-buffered key/button events and reorder input.\n if (pc?.connectionState === \"connected\" && dc?.readyState === \"open\" && dc.bufferedAmount >= 16384) 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 try {\n dc.send(JSON.stringify({ sequence, events }));\n } catch {\n pending = [];\n control = false;\n release();\n post({ type: \"inputOverflow\" });\n }\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 stopEdgePan();\n desktopPan = null;\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 =\n showMouseButtons && control && !nativeMouseControls ? \"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 listenMouse(el, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || heldMouse.has(button)) return;\n clearTimeout(hold);\n if (!e.nativeInput) 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 listenMouse(el, \"pointerup\", up);\n listenMouse(el, \"pointercancel\", up);\n listenMouse(el, \"lostpointercapture\", up);\n listenMouse(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 listenMouse(wheel, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || wheelY) return;\n if (!e.nativeInput) 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 listenMouse(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 listenMouse(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 listenMouse(wheel, \"pointercancel\", cancelWheel);\n listenMouse(wheel, \"lostpointercapture\", cancelWheel);\n listenMouse(wheel, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(1);\n flush();\n }\n });\n listenMouse(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 stopEdgePan() {\n if (edgeFrame !== null) cancelAnimationFrame(edgeFrame);\n edgeFrame = null;\n edgePointer = null;\n }\n function edgePanTick(now) {\n edgeFrame = null;\n if (!edgePointer || desktopPan || !epoch) return;\n const r = layout(),\n vw = viewportWidth(),\n vh = viewportHeight();\n const p = edgePointer;\n const dt = Math.min(32, Math.max(0, now - edgeTime)) / 1000;\n edgeTime = now;\n // rAF timestamps describe the frame start and can precede the pointer\n // handler's performance.now(). A zero-time first frame is not a boundary.\n if (dt === 0) {\n edgeFrame = requestAnimationFrame(edgePanTick);\n return;\n }\n // A narrow edge band accelerates smoothly to 720 local pixels per second.\n const velocity = (position, extent) => {\n const band = Math.min(28, extent / 4);\n return position < band\n ? -(1 - position / band)\n : position > extent - band\n ? (position - extent + band) / band\n : 0;\n };\n const x =\n r.width > vw\n ? bounded(\n r.x - velocity(p.x - viewportLeft(), vw) * 720 * dt,\n viewportLeft() + vw - r.width,\n viewportLeft(),\n )\n : r.x;\n const y =\n r.height > vh\n ? bounded(r.y - velocity(p.y, vh) * 720 * dt, vh - r.height, 0)\n : r.y;\n if (Math.abs(x - r.x) < 0.001 && Math.abs(y - r.y) < 0.001) return;\n stopPanAnimation();\n manualViewMoved = true;\n place(x, y, r);\n // Keep remote hover/drag attached to the local pointer as the picture moves.\n if (control) {\n const next = point(p);\n cx = next.x;\n cy = next.y;\n queue({ kind: \"move\", x: cx, y: cy });\n }\n render();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n function trackEdgePointer(e) {\n const p = desktopPoint(e);\n if (\n !epoch ||\n desktopPan ||\n p.x < viewportLeft() ||\n p.x > viewportLeft() + viewportWidth() ||\n p.y < 0 ||\n p.y > viewportHeight() ||\n !insideDesktop(p)\n ) {\n stopEdgePan();\n return;\n }\n edgePointer = p;\n if (edgeFrame === null) {\n edgeTime = performance.now();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n }\n listen(stage, \"pointerleave\", stopEdgePan);\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) {\n multi.kind = \"scroll\";\n multi.restX = 0;\n multi.restY = 0;\n multi.aimed = mode !== \"touch\";\n }\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n const { maxZoom } = layout();\n zoom = Math.max(\n 1,\n Math.min(\n maxZoom,\n (Math.min(maxZoom, multi.zoom) * next.d) / Math.max(1, multi.d),\n ),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy =\n multi.anchor.y +\n (viewportHeight() / 2 + verticalOffset(r.height) - 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 // Hosts scroll whatever is under the desktop cursor. Touch mode has no\n // visible pointer, so aim it at the fingers once they are over the\n // desktop; like taps, scrolling over the letterbox does nothing.\n if (!multi.aimed && insideDesktop(next)) {\n const p = point(next);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n multi.aimed = true;\n }\n // Hosts inject whole pixels; carry fractions so slow drags still scroll.\n const sx = multi.restX - dx,\n sy = multi.restY - dy,\n wx = Math.trunc(sx),\n wy = Math.trunc(sy);\n multi.restX = sx - wx;\n multi.restY = sy - wy;\n if (multi.aimed && (wx || wy))\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, wx)),\n dy: Math.max(-2000, Math.min(2000, wy)),\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 if (\n e.button === 1 &&\n (layout().width > viewportWidth() || layout().height > viewportHeight())\n ) {\n stopEdgePan();\n stopPanAnimation();\n desktopPan = {\n id: e.pointerId,\n x: e.clientX,\n y: e.clientY,\n start: e,\n moved: false,\n };\n stage.setPointerCapture(e.pointerId);\n return;\n }\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 (desktopPan?.id === e.pointerId) {\n const dx = e.clientX - desktopPan.x,\n dy = e.clientY - desktopPan.y;\n if (!desktopPan.moved && Math.hypot(dx, dy) < 3) return;\n desktopPan.moved = true;\n desktopPan.x = e.clientX;\n desktopPan.y = e.clientY;\n pan(dx, dy);\n return;\n }\n trackEdgePointer(e);\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 if (desktopPan?.id === e.pointerId) {\n const gesture = desktopPan;\n desktopPan = null;\n if (gesture.moved) settlePan();\n else {\n mouse(gesture.start, true);\n mouse(e, false);\n }\n return;\n }\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 desktopPan = null;\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) ===\n (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\"\n ? e.metaKey && !e.ctrlKey\n : 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({\n type: \"clipboard\",\n action: e.code === \"KeyC\" ? \"copy\" : \"paste\",\n });\n }\n return;\n }\n }\n // The focused textarea delivers characters through input (and editing\n // keys through beforeinput). Forwarding their keydown too types twice on\n // iOS, where the software keyboard reports both events.\n if (\n (config.desktop || keyboardEnabled) &&\n document.activeElement === keyboardInput &&\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 ||\n e.key === \"Process\" ||\n e.key === \"Dead\" ||\n (keyboardEnabled && [\"Backspace\", \"Enter\"].includes(e.code)))\n )\n return;\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 (!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 function reportViewport() {\n post({\n type: \"viewportChanged\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n }\n const observer = new ResizeObserver(() => {\n statusOrigin = null;\n reportViewport();\n release();\n settlePan();\n render();\n });\n observer.observe(stage);\n cleanups.push(\n () => observer.disconnect(),\n () => stopPanAnimation(),\n () => stopBackgroundLoop(),\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 if (typeof startBackgroundLoop === \"function\") startBackgroundLoop();\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 (typeof stopBackgroundLoop === \"function\") stopBackgroundLoop();\n if (!preserveFrame) {\n image.removeAttribute(\"src\");\n if (typeof clearBackground === \"function\") clearBackground();\n }\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : 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 () => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n },\n (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n );\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 message.type === \"reply\" &&\n typeof message.id === \"string\" &&\n message.id.length <= 64\n )\n post({\n type: \"channelReply\",\n id: message.id,\n ok: message.ok === true,\n result: message.result,\n error: typeof message.error === \"string\" ? message.error : null,\n });\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 scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\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 // A small control request routed over the live data channel. The host\n // only receives it after advertising support; otherwise the parent uses\n // the relay. `sent` tells the parent whether the channel took it.\n case \"channelRequest\": {\n const id =\n typeof message.id === \"string\" && message.id.length <= 64\n ? message.id\n : null;\n if (!id) break;\n let sent = false;\n try {\n const data = JSON.stringify({\n type: \"request\",\n id,\n request: message.request,\n });\n if (\n pc?.connectionState === \"connected\" &&\n dc?.readyState === \"open\" &&\n dc.bufferedAmount < 16384 &&\n data.length <= 32768\n ) {\n dc.send(data);\n sent = true;\n }\n } catch {}\n post({ type: \"channelRequestState\", id, sent });\n break;\n }\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n break;\n case \"presentation\":\n if (config.nativeMedia) {\n release();\n showKeyboard(false);\n break;\n }\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 if (\n Number.isInteger(message.width) &&\n Number.isInteger(message.height) &&\n message.width >= 320 &&\n message.height >= 320 &&\n (message.restore === true ||\n (message.width <= 2560 && message.height <= 2560))\n ) {\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n desktopScale = null;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n video.muted = !message.audio;\n retries = 0;\n if (!config.nativeMedia) 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 = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.background = config.nativeMedia\n ? \"transparent\"\n : 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 \"networkStatus\": {\n const status = find(\"network-status\");\n if (!status) break;\n status.textContent =\n typeof message.text === \"string\" ? message.text : \"\";\n status.style.display = status.textContent ? \"block\" : \"none\";\n for (const key of [\"top\", \"right\", \"fontSize\"]) {\n if (Number.isFinite(message[key]) && message[key] >= 0)\n status.style[key] = message[key] + \"px\";\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.color))\n status.style.color = message.color;\n statusOrigin = null;\n clipNetworkStatus();\n break;\n }\n case \"nativeTouchpad\": {\n if (!nativeMouseControls || !control) break;\n if (message.tap === true) {\n if (!heldMouse.size) { click(); flush(); }\n break;\n }\n if (!Number.isFinite(message.dx) || !Number.isFinite(message.dy)) break;\n moveTouchpad(message.dx, message.dy);\n queue({ kind: \"move\", x: cx, y: cy });\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n break;\n }\n case \"nativeMouse\": {\n if (\n !nativeMouseControls ||\n ![\"left\", \"right\", \"wheel\"].includes(message.control)\n )\n break;\n if (\n ![\n \"pointerdown\",\n \"pointermove\",\n \"pointerup\",\n \"pointercancel\",\n \"click\",\n ].includes(message.event)\n )\n break;\n if (!Number.isFinite(message.id) || !Number.isFinite(message.y)) break;\n mouseControlHandlers.get(\n \"mouse-\" + message.control + \":\" + message.event,\n )?.({\n pointerId: message.id,\n clientY: message.y,\n detail: 0,\n nativeInput: true,\n preventDefault() {},\n });\n break;\n }\n case \"mouseButtons\": {\n nativeMouseControls = message.native === true;\n const before = layout(),\n previousTopInset = viewportTopInset,\n previousBottomInset = viewportBottomInset,\n keyboardOpen = fillHeight && message.keyboardOpen === true;\n const keepHorizontal =\n fillHeight && (keyboardOpen || keyboardViewportOpen);\n // Hiding the rail for the keyboard must not enlarge a width-fitted desktop.\n if (keyboardOpen && (!keyboardViewportOpen || !keyboardFitWidth)) {\n keyboardFitWidth = { stageWidth: stage.clientWidth, width: viewportWidth() };\n }\n if (!keyboardOpen) keyboardFitWidth = null;\n // Opening is observable before the native keyboard has a measured height.\n keyboardViewportOpen = keyboardOpen;\n const fitChanged = fitToInsets !== (message.fitToInsets === true);\n fitToInsets = message.fitToInsets === true;\n const previousOffset = portraitKeyboardTopInset;\n if (Number.isFinite(message.portraitKeyboardTopInset))\n portraitKeyboardTopInset = Math.max(\n 0,\n message.portraitKeyboardTopInset,\n );\n const offsetChanged = previousOffset !== portraitKeyboardTopInset;\n let sideInsetsChanged = false;\n if (Number.isFinite(message.topInset))\n viewportTopInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.topInset),\n );\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 inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportLeftInset;\n viewportLeftInset = inset;\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportRightInset;\n viewportRightInset = inset;\n }\n // Hiding the side toolbar changes the viewport center. Keep the image's\n // actual horizontal position instead of following that center sideways.\n if (keepHorizontal) {\n stopPanAnimation();\n const r = layout();\n place(before.x, r.y, r);\n }\n const keyboardInset = keyboardOpen ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n const r = layout(),\n v = cursorViewport();\n place(r.x, (v.minY + v.maxY) / 2 - cy * r.height, r);\n cursorNeedsEntry = false;\n manualViewMoved = false;\n }\n }\n if (keepHorizontal) {\n // Restoring the toolbar can cover the cursor even after a zero-height opening.\n if (!keyboardOpen || keyboardInset > 0) {\n const r = layout(),\n v = cursorViewport(),\n x = r.x + cx * r.width;\n place(r.x + bounded(x, v.minX, v.maxX) - x, r.y, r);\n }\n followRest = { fx, fy, zoom };\n render();\n } else if (\n fitChanged ||\n sideInsetsChanged ||\n offsetChanged ||\n (usesViewportInsets() && previousTopInset !== viewportTopInset) ||\n (usesViewportInsets() && previousBottomInset !== viewportBottomInset)\n ) {\n settlePan();\n render();\n }\n reportViewport();\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 }\n case \"init\":\n nativeVideoActive = false;\n image.style.visibility = \"visible\";\n desktopScale = null;\n reportedScaleMode = null;\n if (config.desktop) {\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n }\n viewerSized = false;\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 =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n 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 if (!config.nativeMedia) connect();\n break;\n case \"nativeVideo\":\n if (!config.nativeMedia || message.epoch !== epoch) break;\n nativeVideoActive = message.active === true;\n image.style.visibility = nativeVideoActive ? \"hidden\" : \"visible\";\n clipNetworkStatus();\n paintBackground();\n break;\n case \"nativeCursor\":\n if (config.nativeMedia && message.epoch === epoch)\n receiveCursor(message.cursor);\n break;\n case \"viewport\":\n if (fillHeight !== (message.fillHeight === true)) keyboardFitWidth = null;\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(\n message.capturePending === true ? \"capture-pending\" : \"host\",\n message.retry !== false,\n );\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) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n // A new control intent abandons the previous relay batch. Advance the\n // existing sequence fence so a late old ACK cannot unlock a new batch.\n seq++;\n sending = false;\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 \"zoom\":\n stopEdgePan();\n if (\n !config.desktop ||\n !Number.isFinite(message.factor) ||\n message.factor <= 0\n )\n break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n const fitScale = Math.min(viewportWidth() / dw, viewportHeight() / dh);\n // Include actual size even when it lies outside the fit-relative range.\n desktopScale = Math.max(\n Math.min(fitScale, 1) * 0.1,\n Math.min(Math.max(5 * fitScale, 5), layout().scale * message.factor),\n );\n if (Math.abs(desktopScale - fitScale) < 1e-9) desktopScale = null;\n if (desktopScale === null) {\n fx = 0.5;\n fy = 0.5;\n manualViewMoved = false;\n }\n render();\n settlePan();\n break;\n case \"actualSize\":\n stopEdgePan();\n if (!config.desktop) break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n desktopScale = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"fit\":\n stopEdgePan();\n desktopScale = null;\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 nativeVideoActive = false;\n image.style.visibility = \"visible\";\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 // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\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 if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\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 let nativeVideoActive = false;\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 fit = fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh));\n // Pinch stops at two viewer points per desktop point, never below fit.\n const maxZoom = Math.max(1, 2 / fit);\n const scale = fit * Math.max(1, Math.min(maxZoom, 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, maxZoom };\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 // Shared ambient backdrop. Minimal viewer embeds may omit its subtree.\n const bg = find(\"bg\") || null,\n bgCanvas = find(\"bg-canvas\") || null,\n bgContext = bgCanvas ? bgCanvas.getContext(\"2d\") : null;\n let dw = 1920,\n dh = 1080,\n viewerSized = false,\n zoom = 1,\n desktopScale = null,\n reportedScaleMode = null,\n desktopPan = null,\n edgePointer = null,\n edgeFrame = null,\n edgeTime = 0,\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 pendingSince = 0,\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 let nativeMouseControls = false;\n const mouseControlHandlers = new Map();\n function listenMouse(el, type, handler) {\n listen(el, type, handler);\n mouseControlHandlers.set(el.id + \":\" + type, handler);\n }\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 fitToInsets = false;\n const usesViewportInsets = () => viewerSized || fitToInsets;\n let panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n viewportTopInset = 0,\n keyboardViewportInset = 0,\n portraitKeyboardTopInset = 0;\n let keyboardViewportOpen = false;\n let keyboardFitWidth = null;\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 usableHeight = () =>\n Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);\n const viewportHeight = () =>\n usesViewportInsets() ? usableHeight() : Math.max(1, stage.clientHeight);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n // Center between the measured top controls and the keyboard edge (stage bottom).\n // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.\n // Keep the fitted size and cap the shift when the desktop is too tall to fit.\n const verticalOffset = (height) =>\n (usesViewportInsets() ? viewportTopInset : 0) +\n (fillHeight\n ? 0\n : Math.min(\n Math.max(\n 0,\n portraitKeyboardTopInset - (usesViewportInsets() ? viewportTopInset : 0),\n ) / 2,\n Math.max(0, (viewportHeight() - height) / 2),\n ));\n const layout = () => {\n const r =\n config.desktop && desktopScale !== null\n ? {\n scale: desktopScale,\n width: dw * desktopScale,\n height: dh * desktopScale,\n maxZoom: 1,\n }\n : transform(\n keyboardFitWidth?.stageWidth === stage.clientWidth\n ? keyboardFitWidth.width : viewportWidth(),\n viewportHeight(),\n dw,\n dh,\n zoom,\n fx,\n fy,\n // Mobile fits both axes; retain Desktop scale semantics.\n config.desktop ? fillHeight && !viewerSized : false,\n );\n return {\n ...r,\n x: viewportLeft() + viewportWidth() / 2 - fx * r.width,\n y: viewportHeight() / 2 + verticalOffset(r.height) - fy * r.height,\n };\n };\n // 0 at fit, 1 at the pinch limit for the current viewport and display.\n const zoomProgress = (r = layout()) =>\n r.maxZoom > 1\n ? Math.max(0, Math.min(1, (zoom - 1) / (r.maxZoom - 1)))\n : 0;\n // The backdrop uses 5% / 90% / 5% source segments. The middle 90%\n // keeps the fitted picture's scale; each outer 5% stretches uniformly\n // to fill the remaining space, horizontally or vertically as needed.\n // Zoom and pan never move the backdrop: where the picture covers it, the\n // opaque picture simply occludes it, so input mapping stays uniform. Returns\n // null when the fitted picture already covers the stage, unless a Desktop\n // viewer has shrunk its foreground below fit and still needs the backdrop.\n const bgEdgeFraction = 0.05;\n const bgCenterFraction = 1 - 2 * bgEdgeFraction;\n function backgroundSegments(vw, vh, dw, dh, fill, includeFitted = false) {\n if (!(vw > 0 && vh > 0 && dw > 0 && dh > 0)) return null;\n const s = fill\n ? vh / Math.max(1, dh)\n : Math.min(vw / dw, vh / Math.max(1, dh));\n const w = dw * s,\n h = dh * s;\n if (w < vw || (includeFitted && w === vw && h === vh)) {\n const centerW = w * bgCenterFraction,\n centerX = vw / 2 - centerW / 2,\n sideW = centerX,\n top = (vh - h) / 2;\n return { axis: \"x\", s, w, h, top, centerW, centerX, sideW };\n }\n if (h < vh) {\n const centerH = h * bgCenterFraction,\n centerY = vh / 2 - centerH / 2,\n sideH = centerY,\n left = (vw - w) / 2;\n return { axis: \"y\", s, w, h, left, centerH, centerY, sideH };\n }\n return null;\n }\n // Native video renders beneath this WebView, so z-order cannot hide the\n // status behind the picture; cut the picture's rectangle out instead.\n // Measure the status only after its text or the stage changes, not per frame.\n let statusOrigin = null;\n function clipNetworkStatus(r = layout()) {\n const status = find(\"network-status\");\n if (!status) return;\n if (!nativeVideoActive || status.style.display === \"none\") {\n status.style.clipPath = \"\";\n return;\n }\n if (!statusOrigin)\n statusOrigin = { x: status.offsetLeft, y: status.offsetTop };\n const left = r.x - statusOrigin.x,\n top = r.y - statusOrigin.y,\n right = left + r.width,\n bottom = top + r.height;\n status.style.clipPath = `polygon(evenodd,0 0,100% 0,100% 100%,0 100%,0 0,${left}px ${top}px,${right}px ${top}px,${right}px ${bottom}px,${left}px ${bottom}px,${left}px ${top}px)`;\n }\n function paintBackground() {\n if (nativeVideoActive) {\n if (bg) bg.style.display = \"none\";\n return;\n }\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const picture = config.desktop ? layout() : null;\n const coversStage =\n picture &&\n picture.x <= 0 &&\n picture.y <= 0 &&\n picture.x + picture.width >= vw &&\n picture.y + picture.height >= vh;\n const seg = coversStage\n ? null\n : backgroundSegments(vw, vh, dw, dh, config.desktop ? fillHeight : false, config.desktop);\n if (!seg) {\n bg.style.display = \"none\";\n bgRects = null;\n stopBackgroundLoop();\n return;\n }\n bg.style.display = \"block\";\n bgAxis = seg.axis;\n // The ambient layer also fills the notch and the area beneath native\n // controls. Only the interactive picture respects viewport insets.\n const originX = 0;\n // Source segments are resolved at draw time from the live source dimensions;\n // these dest rects only encode where each segment lands on the stage.\n bgRects =\n seg.axis === \"x\"\n ? [\n {\n x: originX,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX,\n y: seg.top,\n w: seg.centerW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX + seg.centerW,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n ]\n : [\n {\n x: seg.left,\n y: 0,\n w: seg.w,\n h: seg.sideH,\n },\n {\n x: seg.left,\n y: seg.centerY,\n w: seg.w,\n h: seg.centerH,\n },\n {\n x: seg.left,\n y: seg.centerY + seg.centerH,\n w: seg.w,\n h: seg.sideH,\n },\n ];\n // Keep the backing store at stage resolution (capped) so the stretched\n // edges stay crisp without oversized allocations.\n bgDpr = Math.min(2, window.devicePixelRatio || 1);\n const bw = Math.round(stage.clientWidth * bgDpr),\n bh = Math.round(vh * bgDpr);\n if (bgCanvas.width !== bw || bgCanvas.height !== bh) {\n bgCanvas.width = bw;\n bgCanvas.height = bh;\n }\n scheduleBackgroundDraw();\n startBackgroundLoop();\n }\n // One canvas, three draws: each source segment stretches into whatever bar\n // the picture leaves open. The live video feeds it once presented; until\n // then the decoded JPEG frame does, so the backdrop always matches the\n // picture's own pixels and scale in the center segment.\n let bgRects = null,\n bgAxis = \"x\",\n bgDpr = 1,\n bgDrawFrame = null,\n bgLoopFrame = null;\n function drawBackground() {\n if (!bgContext || !bgRects) return;\n const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n // Cursor updates can schedule a repaint while the next JPEG is loading.\n // Keep the last backdrop until the replacement has drawable pixels.\n if ((!useVideo && !image.complete) || !(sw > 0 && sh > 0)) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\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 * zoomProgress(r);\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 + verticalOffset(r.height),\n maxY: y.max + verticalOffset(r.height),\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 + verticalOffset(r.height) - 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 + 40 * zoomProgress();\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 = (viewportHeight() / 2 + verticalOffset(r.height) - 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(\n bottom - 1,\n (usesViewportInsets() ? viewportTopInset : 0) + 8 + hotY,\n );\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 if (config.nativeMedia && epoch)\n post({\n type: \"nativeViewport\",\n fillHeight: false,\n x: r.x,\n y: r.y,\n width: r.width,\n height: r.height,\n });\n if (config.desktop && epoch) {\n const scaleMode =\n desktopScale === null\n ? \"fit\"\n : desktopScale === 1\n ? \"actual\"\n : \"custom\";\n if (reportedScaleMode !== scaleMode) {\n reportedScaleMode = scaleMode;\n post({ type: \"scaleMode\", mode: scaleMode });\n }\n }\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 clipNetworkStatus(r);\n paintBackground();\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\")\n ? \"block\"\n : \"none\";\n }\n if (config.desktop) {\n // Let the local OS own pointer size, DPI and accessibility preferences.\n // Never use a remote URL or bitmap as the desktop's native cursor.\n cursor.style.display = \"none\";\n const shape = remoteCursor?.shape;\n stage.style.cursor =\n control &&\n [\n \"default\",\n \"text\",\n \"vertical-text\",\n \"pointer\",\n \"crosshair\",\n \"grab\",\n \"grabbing\",\n \"ew-resize\",\n \"ns-resize\",\n \"nwse-resize\",\n \"nesw-resize\",\n \"move\",\n \"not-allowed\",\n \"copy\",\n \"alias\",\n \"wait\",\n \"progress\",\n \"help\",\n ].includes(shape)\n ? shape\n : \"default\";\n }\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 (!pending.length) pendingSince = performance.now();\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) return;\n // Input is an intent about the picture the user saw, not durable work.\n // Never replay old clicks/typing after a stalled ACK or data channel drains.\n if (performance.now() - pendingSince >= 2000) {\n pending = [];\n control = false;\n release();\n updateMouseButtons();\n post({ type: \"inputOverflow\" });\n return;\n }\n if (sending) return;\n // Do not route around a congested live data channel: the relay could\n // overtake its already-buffered key/button events and reorder input.\n if (pc?.connectionState === \"connected\" && dc?.readyState === \"open\" && dc.bufferedAmount >= 16384) 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 try {\n dc.send(JSON.stringify({ sequence, events }));\n } catch {\n pending = [];\n control = false;\n release();\n post({ type: \"inputOverflow\" });\n }\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 stopEdgePan();\n desktopPan = null;\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 =\n showMouseButtons && control && !nativeMouseControls ? \"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 listenMouse(el, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || heldMouse.has(button)) return;\n clearTimeout(hold);\n if (!e.nativeInput) 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 listenMouse(el, \"pointerup\", up);\n listenMouse(el, \"pointercancel\", up);\n listenMouse(el, \"lostpointercapture\", up);\n listenMouse(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 listenMouse(wheel, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || wheelY) return;\n if (!e.nativeInput) 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 listenMouse(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 listenMouse(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 listenMouse(wheel, \"pointercancel\", cancelWheel);\n listenMouse(wheel, \"lostpointercapture\", cancelWheel);\n listenMouse(wheel, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(1);\n flush();\n }\n });\n listenMouse(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 stopEdgePan() {\n if (edgeFrame !== null) cancelAnimationFrame(edgeFrame);\n edgeFrame = null;\n edgePointer = null;\n }\n function edgePanTick(now) {\n edgeFrame = null;\n if (!edgePointer || desktopPan || !epoch) return;\n const r = layout(),\n vw = viewportWidth(),\n vh = viewportHeight();\n const p = edgePointer;\n const dt = Math.min(32, Math.max(0, now - edgeTime)) / 1000;\n edgeTime = now;\n // rAF timestamps describe the frame start and can precede the pointer\n // handler's performance.now(). A zero-time first frame is not a boundary.\n if (dt === 0) {\n edgeFrame = requestAnimationFrame(edgePanTick);\n return;\n }\n // A narrow edge band accelerates smoothly to 720 local pixels per second.\n const velocity = (position, extent) => {\n const band = Math.min(28, extent / 4);\n return position < band\n ? -(1 - position / band)\n : position > extent - band\n ? (position - extent + band) / band\n : 0;\n };\n const x =\n r.width > vw\n ? bounded(\n r.x - velocity(p.x - viewportLeft(), vw) * 720 * dt,\n viewportLeft() + vw - r.width,\n viewportLeft(),\n )\n : r.x;\n const y =\n r.height > vh\n ? bounded(r.y - velocity(p.y, vh) * 720 * dt, vh - r.height, 0)\n : r.y;\n if (Math.abs(x - r.x) < 0.001 && Math.abs(y - r.y) < 0.001) return;\n stopPanAnimation();\n manualViewMoved = true;\n place(x, y, r);\n // Keep remote hover/drag attached to the local pointer as the picture moves.\n if (control) {\n const next = point(p);\n cx = next.x;\n cy = next.y;\n queue({ kind: \"move\", x: cx, y: cy });\n }\n render();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n function trackEdgePointer(e) {\n const p = desktopPoint(e);\n if (\n !epoch ||\n desktopPan ||\n p.x < viewportLeft() ||\n p.x > viewportLeft() + viewportWidth() ||\n p.y < 0 ||\n p.y > viewportHeight() ||\n !insideDesktop(p)\n ) {\n stopEdgePan();\n return;\n }\n edgePointer = p;\n if (edgeFrame === null) {\n edgeTime = performance.now();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n }\n listen(stage, \"pointerleave\", stopEdgePan);\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) {\n multi.kind = \"scroll\";\n multi.restX = 0;\n multi.restY = 0;\n multi.aimed = mode !== \"touch\";\n }\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n const { maxZoom } = layout();\n zoom = Math.max(\n 1,\n Math.min(\n maxZoom,\n (Math.min(maxZoom, multi.zoom) * next.d) / Math.max(1, multi.d),\n ),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy =\n multi.anchor.y +\n (viewportHeight() / 2 + verticalOffset(r.height) - 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 // Hosts scroll whatever is under the desktop cursor. Touch mode has no\n // visible pointer, so aim it at the fingers once they are over the\n // desktop; like taps, scrolling over the letterbox does nothing.\n if (!multi.aimed && insideDesktop(next)) {\n const p = point(next);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n multi.aimed = true;\n }\n // Hosts inject whole pixels; carry fractions so slow drags still scroll.\n const sx = multi.restX - dx,\n sy = multi.restY - dy,\n wx = Math.trunc(sx),\n wy = Math.trunc(sy);\n multi.restX = sx - wx;\n multi.restY = sy - wy;\n if (multi.aimed && (wx || wy))\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, wx)),\n dy: Math.max(-2000, Math.min(2000, wy)),\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 if (\n e.button === 1 &&\n (layout().width > viewportWidth() || layout().height > viewportHeight())\n ) {\n stopEdgePan();\n stopPanAnimation();\n desktopPan = {\n id: e.pointerId,\n x: e.clientX,\n y: e.clientY,\n start: e,\n moved: false,\n };\n stage.setPointerCapture(e.pointerId);\n return;\n }\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 (desktopPan?.id === e.pointerId) {\n const dx = e.clientX - desktopPan.x,\n dy = e.clientY - desktopPan.y;\n if (!desktopPan.moved && Math.hypot(dx, dy) < 3) return;\n desktopPan.moved = true;\n desktopPan.x = e.clientX;\n desktopPan.y = e.clientY;\n pan(dx, dy);\n return;\n }\n trackEdgePointer(e);\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 if (desktopPan?.id === e.pointerId) {\n const gesture = desktopPan;\n desktopPan = null;\n if (gesture.moved) settlePan();\n else {\n mouse(gesture.start, true);\n mouse(e, false);\n }\n return;\n }\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 desktopPan = null;\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) ===\n (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\"\n ? e.metaKey && !e.ctrlKey\n : 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({\n type: \"clipboard\",\n action: e.code === \"KeyC\" ? \"copy\" : \"paste\",\n });\n }\n return;\n }\n }\n // The focused textarea delivers characters through input (and editing\n // keys through beforeinput). Forwarding their keydown too types twice on\n // iOS, where the software keyboard reports both events.\n if (\n (config.desktop || keyboardEnabled) &&\n document.activeElement === keyboardInput &&\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 ||\n e.key === \"Process\" ||\n e.key === \"Dead\" ||\n (keyboardEnabled && [\"Backspace\", \"Enter\"].includes(e.code)))\n )\n return;\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 (!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 function reportViewport() {\n post({\n type: \"viewportChanged\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n }\n const observer = new ResizeObserver(() => {\n statusOrigin = null;\n reportViewport();\n release();\n settlePan();\n render();\n });\n observer.observe(stage);\n cleanups.push(\n () => observer.disconnect(),\n () => stopPanAnimation(),\n () => stopBackgroundLoop(),\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 if (typeof startBackgroundLoop === \"function\") startBackgroundLoop();\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 (typeof stopBackgroundLoop === \"function\") stopBackgroundLoop();\n if (!preserveFrame) {\n image.removeAttribute(\"src\");\n if (typeof clearBackground === \"function\") clearBackground();\n }\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : 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 () => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n },\n (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n );\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 message.type === \"reply\" &&\n typeof message.id === \"string\" &&\n message.id.length <= 64\n )\n post({\n type: \"channelReply\",\n id: message.id,\n ok: message.ok === true,\n result: message.result,\n error: typeof message.error === \"string\" ? message.error : null,\n });\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 scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\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 applyDisplayGeometry(message) {\n if (\n !Number.isInteger(message.width) ||\n !Number.isInteger(message.height) ||\n message.width < 320 ||\n message.height < 320 ||\n (message.restore !== true &&\n (message.width > 2560 || message.height > 2560))\n )\n return;\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n desktopScale = null;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\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 // A small control request routed over the live data channel. The host\n // only receives it after advertising support; otherwise the parent uses\n // the relay. `sent` tells the parent whether the channel took it.\n case \"channelRequest\": {\n const id =\n typeof message.id === \"string\" && message.id.length <= 64\n ? message.id\n : null;\n if (!id) break;\n let sent = false;\n try {\n const data = JSON.stringify({\n type: \"request\",\n id,\n request: message.request,\n });\n if (\n pc?.connectionState === \"connected\" &&\n dc?.readyState === \"open\" &&\n dc.bufferedAmount < 16384 &&\n data.length <= 32768\n ) {\n dc.send(data);\n sent = true;\n }\n } catch {}\n post({ type: \"channelRequestState\", id, sent });\n break;\n }\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n break;\n case \"presentation\":\n if (config.nativeMedia) {\n release();\n showKeyboard(false);\n break;\n }\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 applyDisplayGeometry(message);\n video.muted = !message.audio;\n retries = 0;\n if (!config.nativeMedia) connect();\n break;\n // The host kept the stream across a display change: layout only.\n case \"displayGeometry\":\n applyDisplayGeometry(message);\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 = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.background = config.nativeMedia\n ? \"transparent\"\n : 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 \"networkStatus\": {\n const status = find(\"network-status\");\n if (!status) break;\n status.textContent =\n typeof message.text === \"string\" ? message.text : \"\";\n status.style.display = status.textContent ? \"block\" : \"none\";\n for (const key of [\"top\", \"right\", \"fontSize\"]) {\n if (Number.isFinite(message[key]) && message[key] >= 0)\n status.style[key] = message[key] + \"px\";\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.color))\n status.style.color = message.color;\n statusOrigin = null;\n clipNetworkStatus();\n break;\n }\n case \"nativeTouchpad\": {\n if (!nativeMouseControls || !control) break;\n if (message.tap === true) {\n if (!heldMouse.size) { click(); flush(); }\n break;\n }\n if (!Number.isFinite(message.dx) || !Number.isFinite(message.dy)) break;\n moveTouchpad(message.dx, message.dy);\n queue({ kind: \"move\", x: cx, y: cy });\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n break;\n }\n case \"nativeMouse\": {\n if (\n !nativeMouseControls ||\n ![\"left\", \"right\", \"wheel\"].includes(message.control)\n )\n break;\n if (\n ![\n \"pointerdown\",\n \"pointermove\",\n \"pointerup\",\n \"pointercancel\",\n \"click\",\n ].includes(message.event)\n )\n break;\n if (!Number.isFinite(message.id) || !Number.isFinite(message.y)) break;\n mouseControlHandlers.get(\n \"mouse-\" + message.control + \":\" + message.event,\n )?.({\n pointerId: message.id,\n clientY: message.y,\n detail: 0,\n nativeInput: true,\n preventDefault() {},\n });\n break;\n }\n case \"mouseButtons\": {\n nativeMouseControls = message.native === true;\n const before = layout(),\n previousTopInset = viewportTopInset,\n previousBottomInset = viewportBottomInset,\n keyboardOpen = fillHeight && message.keyboardOpen === true;\n const keepHorizontal =\n fillHeight && (keyboardOpen || keyboardViewportOpen);\n // Hiding the rail for the keyboard must not enlarge a width-fitted desktop.\n if (keyboardOpen && (!keyboardViewportOpen || !keyboardFitWidth)) {\n keyboardFitWidth = { stageWidth: stage.clientWidth, width: viewportWidth() };\n }\n if (!keyboardOpen) keyboardFitWidth = null;\n // Opening is observable before the native keyboard has a measured height.\n keyboardViewportOpen = keyboardOpen;\n const fitChanged = fitToInsets !== (message.fitToInsets === true);\n fitToInsets = message.fitToInsets === true;\n const previousOffset = portraitKeyboardTopInset;\n if (Number.isFinite(message.portraitKeyboardTopInset))\n portraitKeyboardTopInset = Math.max(\n 0,\n message.portraitKeyboardTopInset,\n );\n const offsetChanged = previousOffset !== portraitKeyboardTopInset;\n let sideInsetsChanged = false;\n if (Number.isFinite(message.topInset))\n viewportTopInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.topInset),\n );\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 inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportLeftInset;\n viewportLeftInset = inset;\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportRightInset;\n viewportRightInset = inset;\n }\n // Hiding the side toolbar changes the viewport center. Keep the image's\n // actual horizontal position instead of following that center sideways.\n if (keepHorizontal) {\n stopPanAnimation();\n const r = layout();\n place(before.x, r.y, r);\n }\n const keyboardInset = keyboardOpen ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n const r = layout(),\n v = cursorViewport();\n place(r.x, (v.minY + v.maxY) / 2 - cy * r.height, r);\n cursorNeedsEntry = false;\n manualViewMoved = false;\n }\n }\n if (keepHorizontal) {\n // Restoring the toolbar can cover the cursor even after a zero-height opening.\n if (!keyboardOpen || keyboardInset > 0) {\n const r = layout(),\n v = cursorViewport(),\n x = r.x + cx * r.width;\n place(r.x + bounded(x, v.minX, v.maxX) - x, r.y, r);\n }\n followRest = { fx, fy, zoom };\n render();\n } else if (\n fitChanged ||\n sideInsetsChanged ||\n offsetChanged ||\n (usesViewportInsets() && previousTopInset !== viewportTopInset) ||\n (usesViewportInsets() && previousBottomInset !== viewportBottomInset)\n ) {\n settlePan();\n render();\n }\n reportViewport();\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 }\n case \"init\":\n nativeVideoActive = false;\n image.style.visibility = \"visible\";\n desktopScale = null;\n reportedScaleMode = null;\n if (config.desktop) {\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n }\n viewerSized = false;\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 =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n 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 if (!config.nativeMedia) connect();\n break;\n case \"nativeVideo\":\n if (!config.nativeMedia || message.epoch !== epoch) break;\n nativeVideoActive = message.active === true;\n image.style.visibility = nativeVideoActive ? \"hidden\" : \"visible\";\n clipNetworkStatus();\n paintBackground();\n break;\n case \"nativeCursor\":\n if (config.nativeMedia && message.epoch === epoch)\n receiveCursor(message.cursor);\n break;\n case \"viewport\":\n if (fillHeight !== (message.fillHeight === true)) keyboardFitWidth = null;\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(\n message.capturePending === true ? \"capture-pending\" : \"host\",\n message.retry !== false,\n );\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) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n // A new control intent abandons the previous relay batch. Advance the\n // existing sequence fence so a late old ACK cannot unlock a new batch.\n seq++;\n sending = false;\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 \"zoom\":\n stopEdgePan();\n if (\n !config.desktop ||\n !Number.isFinite(message.factor) ||\n message.factor <= 0\n )\n break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n const fitScale = Math.min(viewportWidth() / dw, viewportHeight() / dh);\n // Include actual size even when it lies outside the fit-relative range.\n desktopScale = Math.max(\n Math.min(fitScale, 1) * 0.1,\n Math.min(Math.max(5 * fitScale, 5), layout().scale * message.factor),\n );\n if (Math.abs(desktopScale - fitScale) < 1e-9) desktopScale = null;\n if (desktopScale === null) {\n fx = 0.5;\n fy = 0.5;\n manualViewMoved = false;\n }\n render();\n settlePan();\n break;\n case \"actualSize\":\n stopEdgePan();\n if (!config.desktop) break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n desktopScale = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"fit\":\n stopEdgePan();\n desktopScale = null;\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 nativeVideoActive = false;\n image.style.visibility = \"visible\";\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 // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\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 if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";