Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-desktop): 剪贴板同步不再随焦点开关,复制粘贴即时同步 (#6067)
Dashc699328098ba
diff --git a/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts b/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.tsindex 4d49294ba1..a3f022c73d 100644--- a/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts@@ -1,5 +1,6 @@-import { describe, it, expect, vi } from 'vitest';+import { afterEach, describe, it, expect, vi } from 'vitest';import { RemoteViewerConnection } from '../connection';+import { ViewerSafety, type ViewerClipboard } from '../safety';import {ClipboardSync,remoteDesktopVideoSettingsWire,@@ -38,58 +39,273 @@ function fixture() {};}describe('standalone remote viewer authority', () => {- it('stops counters on blur and orders remote disable after an in-flight enable', async () => {- let focused = true;- let finish!: () => void;- const stop = vi.fn();- const tick = vi.spyOn(ClipboardSync.prototype, 'tick').mockResolvedValue(undefined);- const request = vi.fn(async (_target, message, check) => {+ afterEach(() => {+ vi.useRealTimers();+ });+ function syncFixture(focused: () => boolean, stop = vi.fn()) {+ const clipboard: ViewerClipboard = {+ stop,+ version: async () => '1',+ read: async () => '',+ write: async () => '1',+ };+ const request = vi.fn(async (_target, message, check): Promise<unknown> => {check();if (message.op === 'capabilities') return { clipboardSync: true };if (message.op === 'start') return { lease: 'lease', controlling: false };if (message.op === 'control') return { controlling: true };- if (message.op === 'clipboardSync' && message.enabled && !finish)- await new Promise<void>((resolve) => {- finish = resolve;- });return { enabled: message.enabled };});const connection = new RemoteViewerConnection({owner: () => 'owner',request,- focused: () => focused,+ focused,readClipboard: () => '',writeClipboard: () => {},preferences: () => ({ ...DEFAULT_VIEWER_PREFERENCES, clipboardSync: true }),- clipboard: { stop, version: async () => '1', read: async () => '', write: async () => '1' },+ clipboard,});- try {+ const enables = () =>+ request.mock.calls.filter(([, m]) => m.op === 'clipboardSync').map(([, m]) => m.enabled);+ const control = async () => {connection.bind({ deviceId: 'target', name: 'Target' });connection.setActive(true);const generation = connection.generation;await connection.request(generation, { op: 'capabilities' });await connection.request(generation, { op: 'start', displayId: '1' });await connection.request(generation, { op: 'control', lease: 'lease', enabled: true });- const pending = connection.safety(generation);- await vi.waitFor(() => expect(finish).toBeTypeOf('function'));- focused = false;- const paused = connection.focusChanged();- expect(stop).toHaveBeenCalledOnce();- finish();- await Promise.all([pending, paused]);- expect(- request.mock.calls.filter(([, m]) => m.op === 'clipboardSync').map(([, m]) => m.enabled),- ).toEqual([true, false]);- expect(tick).not.toHaveBeenCalled();- focused = true;+ return generation;+ };+ return { connection, request, enables, control, stop, clipboard };+ }+ it('keeps the computer sync on across focus changes: one last pass on blur, an immediate one on focus', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ let focused = true;+ const tick = vi.spyOn(ClipboardSync.prototype, 'tick').mockResolvedValue(undefined);+ const { connection, enables, control, stop } = syncFixture(() => focused);+ try {+ const generation = await control();await connection.safety(generation);expect(tick).toHaveBeenCalledOnce();+ // Leaving admits a last pass without cancelling a queued shortcut pull.+ focused = false;+ await connection.focusChanged();+ expect(tick).toHaveBeenCalledTimes(2);+ expect(stop).not.toHaveBeenCalled();+ // A copy chord's delayed pull lands after that pass but inside the 1 s grace.+ await connection.syncClipboard(generation);+ expect(tick).toHaveBeenCalledTimes(3);+ // Past the grace, unfocused polls neither read the clipboard nor switch the computer's sync off.+ vi.setSystemTime(Date.now() + 1000);+ await connection.safety(generation);+ await connection.syncClipboard(generation);+ expect(tick).toHaveBeenCalledTimes(3);+ expect(enables()).toEqual([true]);+ // Back in front: sync at once instead of at the next poll, with no re-enable churn.+ focused = true;+ await connection.focusChanged();+ expect(tick).toHaveBeenCalledTimes(4);+ expect(enables()).toEqual([true]);connection.deactivate();- expect(stop).toHaveBeenCalledTimes(2);+ expect(stop).toHaveBeenCalledOnce();+ } finally {+ tick.mockRestore();+ }+ });+ it('a shortcut sync runs a fresh pass once the in-flight one settles, even if that one fails', async () => {+ let finish!: (error: Error) => void;+ const tick = vi+ .spyOn(ClipboardSync.prototype, 'tick')+ .mockImplementationOnce(+ () =>+ new Promise<void>((_resolve, reject) => {+ finish = reject;+ }),+ )+ .mockResolvedValue(undefined);+ const { connection, control } = syncFixture(() => true);+ try {+ const generation = await control();+ const pending = connection.safety(generation);+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));+ let synced = false;+ const sync = connection.syncClipboard(generation).then(() => {+ synced = true;+ });+ await Promise.resolve();+ await Promise.resolve();+ expect(synced).toBe(false);+ expect(tick).toHaveBeenCalledOnce();+ // The failure arms the backoff; the shortcut still gets its own pass right away.+ finish(new Error('DESKTOP_UNAVAILABLE'));+ await Promise.all([pending, sync]);+ expect(tick).toHaveBeenCalledTimes(2);+ await expect(connection.syncClipboard(generation + 1)).rejects.toThrow('DESKTOP_STOPPED');} finally {tick.mockRestore();}});+ it.each([true, false])(+ 'a pass admitted with focused=%s survives blur and grace expiry',+ async (startFocused) => {+ vi.useFakeTimers({ toFake: ['Date'] });+ const snapshot = { privacyActive: false, notice: null, clipboardProgress: null };+ const captured: Array<Parameters<ViewerSafety['tick']>[0]> = [];+ let finish!: () => void;+ const tick = vi+ .spyOn(ViewerSafety.prototype, 'tick')+ .mockImplementationOnce(async (value) => {+ captured.push(value);+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ return snapshot;+ })+ .mockImplementation(async (value) => {+ captured.push(value);+ return snapshot;+ });+ let focused = true;+ const { connection, control } = syncFixture(() => focused);+ try {+ const generation = await control();+ focused = startFocused;+ const pass = startFocused ? connection.safety(generation) : connection.focusChanged();+ await vi.waitFor(() => expect(captured).toHaveLength(1));+ expect(captured[0].clipboardCurrent()).toBe(true);+ // Neither a new blur nor grace expiry revokes an admitted pass.+ focused = false;+ vi.setSystemTime(Date.now() + 1000);+ expect(captured[0].clipboardCurrent()).toBe(true);+ finish();+ await pass;+ // But no new pass may read the clipboard after the deadline.+ await connection.safety(generation);+ expect(captured).toHaveLength(2);+ expect(captured[1].clipboardCurrent()).toBe(false);+ } finally {+ tick.mockRestore();+ }+ },+ );+ it('a paste racing a focus wakeup for the same idle pass waits for the fresh pass the focus started', async () => {+ let finishFirst!: () => void, finishSecond!: () => void;+ const tick = vi+ .spyOn(ClipboardSync.prototype, 'tick')+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishFirst = resolve;+ }),+ )+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishSecond = resolve;+ }),+ )+ .mockResolvedValue(undefined);+ const { connection, control } = syncFixture(() => true);+ try {+ const generation = await control();+ const first = connection.safety(generation);+ await vi.waitFor(() => expect(finishFirst).toBeTypeOf('function'));+ // Both wakeups wait on the same in-flight pass; focus registered first.+ const focus = connection.focusChanged();+ let synced = false;+ const sync = connection.syncClipboard(generation).then(() => {+ synced = true;+ });+ finishFirst();+ await first;+ await vi.waitFor(() => expect(finishSecond).toBeTypeOf('function'));+ await Promise.resolve();+ await Promise.resolve();+ // The paste shares the fresh pass instead of settling on a stale snapshot.+ expect(tick).toHaveBeenCalledTimes(2);+ expect(synced).toBe(false);+ finishSecond();+ await Promise.all([focus, sync]);+ expect(synced).toBe(true);+ expect(tick).toHaveBeenCalledTimes(2);+ } finally {+ tick.mockRestore();+ }+ });+ it.each(['finish', 'release', 'close'] as const)(+ 'a delayed copy queued behind blur survives blur cleanup but respects %s',+ async (ending) => {+ vi.useFakeTimers({ toFake: ['Date'] });+ let focused = true;+ const { connection, request, clipboard, control } = syncFixture(() => focused);+ let local = JSON.stringify({ text: 'before copy' });+ let remote = local;+ let remoteVersion = '1';+ clipboard.read = async () => local;+ const write = vi.fn(async (json: string) => {+ local = json;+ return '1';+ });+ clipboard.write = write;+ let blockVersion = false;+ let finishBlur!: (value: { version: string }) => void;+ const originalRequest = request.getMockImplementation()!;+ request.mockImplementation(async (target, message, check) => {+ check();+ if (message.op === 'capabilities') return { clipboardSync: true, clipboardInline: true };+ if (message.op === 'clipboardVersion') {+ if (blockVersion) {+ blockVersion = false;+ return new Promise((resolve) => {+ finishBlur = resolve;+ });+ }+ return { version: remoteVersion };+ }+ if (message.op === 'clipboardContent' && message.action === 'copy')+ return { length: remote.length, data: remote };+ return originalRequest(target, message, check);+ });+ const generation = await control();+ await connection.safety(generation); // Establish both baselines using the real sync engine.+ blockVersion = true;+ focused = false;+ const blur = connection.focusChanged();+ await vi.waitFor(() => expect(finishBlur).toBeTypeOf('function'));+ // The delayed copy waits on the blur pass, which read the old remote version.+ const sync = connection.syncClipboard(generation);+ await Promise.resolve();+ remoteVersion = '2';+ remote = JSON.stringify({ text: 'new remote copy' });+ let secondCurrent!: () => boolean;+ let finishCopy!: (version: string) => void;+ clipboard.version = (current) =>+ new Promise((resolve) => {+ secondCurrent = current;+ finishCopy = resolve;+ });+ finishBlur({ version: '1' });+ await vi.waitFor(() => expect(secondCurrent).toBeTypeOf('function'));+ try {+ // Blur cleanup has run by now. Only the start deadline applies, not a+ // second cancellation generation; crossing that deadline is harmless.+ expect(secondCurrent()).toBe(true);+ vi.setSystemTime(Date.now() + 1000);+ expect(secondCurrent()).toBe(true);+ if (ending === 'release')+ await connection.request(generation, { op: 'control', lease: 'lease', enabled: false });+ if (ending === 'close') connection.deactivate();+ expect(secondCurrent()).toBe(ending === 'finish');+ } finally {+ clipboard.version = async () => '1';+ finishCopy('1');+ await Promise.allSettled([blur, sync]);+ }+ if (ending === 'finish')+ expect(write).toHaveBeenCalledWith(remote, '1', expect.any(Function));+ else expect(write).not.toHaveBeenCalled();+ },+ );it.each(['target', 'owner'])('does not block a new %s behind the old scope cleanup',async (changed) => {diff --git a/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts b/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.tsindex ffdd8f39c8..a254f3c466 100644--- a/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts@@ -1,5 +1,9 @@import { expect, it, vi } from 'vitest';-import { ClipboardSync, type RemoteDesktopCapabilities } from '@cindy/device-link';+import {+ ClipboardSync,+ type RemoteDesktopCapabilities,+ type RemoteDesktopRequest,+} from '@cindy/device-link';import { DEFAULT_VIEWER_PREFERENCES } from '../../../shared/remoteDesktopViewer';import { ViewerSafety } from '../safety';@@ -32,7 +36,7 @@ it('does not apply opt-ins without confirmed control', async () => {await safety.tick({ ...options, current: () => false });expect(request).not.toHaveBeenCalled();});-it('focus pause preserves privacy state and does not retry failed mute settings', async () => {+it('background passes preserve privacy state and do not retry failed mute settings', async () => {const { safety, options, request } = fixture();request.mockImplementation(async (message: { op: string }) => {if (message.op === 'hostMute') throw new Error('DESKTOP_UNAVAILABLE');@@ -40,9 +44,8 @@ it('focus pause preserves privacy state and does not retry failed mute settings'});await safety.tick(options);const before = safety.snapshot();- await safety.pauseClipboard();- expect(safety.snapshot()).toEqual(before);await safety.tick(options);+ expect(safety.snapshot()).toEqual(before);expect(request.mock.calls.filter(([message]: [{ op: string }]) => message.op === 'privacyScreen'),).toHaveLength(1);@@ -72,7 +75,7 @@ it('pauses until old work settles and discards its late success', async () => {expect(request).toHaveBeenCalledTimes(1);});-it('a window-switch pause keeps the stopped read from updating the notice or failure count', async () => {+it('authority invalidation keeps a stopped read from updating the notice or failure count', async () => {const { safety, options } = fixture();const now = vi.spyOn(Date, 'now').mockReturnValue(10000);let fail!: (error: Error) => void;@@ -86,18 +89,16 @@ it('a window-switch pause keeps the stopped read from updating the notice or fai).mockRejectedValueOnce(new Error('DESKTOP_UNAVAILABLE')).mockResolvedValue(undefined);- let focused = true;const sync = {...options,preferences: { ...options.preferences, clipboardSync: true },- clipboardCurrent: () => focused,+ clipboardCurrent: () => true,clipboard: { version: async () => 'v', read: async () => '{}', write: async () => 'v' },};try {const stale = safety.tick(sync);await vi.waitFor(() => expect(tick).toHaveBeenCalledTimes(1));- focused = false;- const paused = safety.pauseClipboard();+ const paused = safety.pause();// Pausing stops the in-flight read, which then reports the clipboard as unavailable.fail(new Error('DESKTOP_CLIPBOARD_UNAVAILABLE'));expect((await stale).notice).toBeNull();@@ -105,7 +106,6 @@ it('a window-switch pause keeps the stopped read from updating the notice or faiexpect(safety.snapshot().notice).toBeNull();// The stale result was not counted: the first real failure backs off 1.5s, not 3s.- focused = true;expect((await safety.tick(sync)).notice).toBe('clipboardSyncFailed');now.mockReturnValue(12000);await safety.tick(sync);@@ -116,6 +116,137 @@ it('a window-switch pause keeps the stopped read from updating the notice or fai}});+function syncFixture() {+ const { safety, options, request } = fixture();+ const clipboardEnables = () =>+ request.mock.calls.filter(([message]: [{ op: string }]) => message.op === 'clipboardSync');+ return {+ safety,+ request,+ clipboardEnables,+ sync: {+ ...options,+ preferences: { ...options.preferences, clipboardSync: true },+ clipboardCurrent: () => true,+ clipboard: { version: async () => 'v', read: async () => '{}', write: async () => 'v' },+ },+ };+}++it('background passes keep the computer sync enabled without reading clipboard contents', async () => {+ const { safety, sync, clipboardEnables } = syncFixture();+ const tick = vi.spyOn(ClipboardSync.prototype, 'tick').mockResolvedValue(undefined);+ try {+ await safety.tick(sync);+ await safety.tick({ ...sync, clipboardCurrent: () => false });+ expect(tick).toHaveBeenCalledOnce();+ await safety.tick(sync);+ expect(clipboardEnables()).toHaveLength(1);+ expect(tick).toHaveBeenCalledTimes(2);+ } finally {+ tick.mockRestore();+ }+});++it('a locked computer waits at a fixed interval with its own status, never growing the backoff', async () => {+ const { safety, sync, clipboardEnables } = syncFixture();+ const now = vi.spyOn(Date, 'now').mockReturnValue(10000);+ const tick = vi+ .spyOn(ClipboardSync.prototype, 'tick')+ .mockRejectedValueOnce(new Error('DESKTOP_CLIPBOARD_UNAVAILABLE'))+ .mockRejectedValueOnce(new Error('DESKTOP_CLIPBOARD_UNAVAILABLE'))+ .mockRejectedValueOnce(new Error('DESKTOP_CLIPBOARD_UNAVAILABLE'))+ .mockResolvedValue(undefined);+ try {+ expect((await safety.tick(sync)).notice).toBe('clipboardSyncWaiting');+ for (const [at, calls] of [+ [11000, 1],+ [11500, 2],+ [12500, 2],+ [13000, 3],+ [14500, 4],+ ] as const) {+ now.mockReturnValue(at);+ await safety.tick(sync);+ expect(tick).toHaveBeenCalledTimes(calls);+ }+ expect(safety.snapshot().notice).toBeNull();+ // The computer refused sync while locked, so each attempt re-enabled it first.+ expect(clipboardEnables()).toHaveLength(4);+ } finally {+ now.mockRestore();+ tick.mockRestore();+ }+});++it('a copy mid-read keeps the status; other failures back off to 5s at most and wake retries at once', async () => {+ const { safety, sync } = syncFixture();+ const now = vi.spyOn(Date, 'now').mockReturnValue(10000);+ const tick = vi+ .spyOn(ClipboardSync.prototype, 'tick')+ .mockRejectedValueOnce(new Error('CLIPBOARD_CHANGED'))+ .mockRejectedValueOnce(new Error('DESKTOP_UNAVAILABLE'))+ .mockRejectedValueOnce(new Error('DESKTOP_UNAVAILABLE'))+ .mockRejectedValueOnce(new Error('DESKTOP_UNAVAILABLE'))+ .mockRejectedValueOnce(new Error('DESKTOP_UNAVAILABLE'))+ .mockResolvedValue(undefined);+ try {+ expect((await safety.tick(sync)).notice).toBeNull();+ // 1.5s later the unexplained failures start: 1.5s, 3s, then capped at 5s.+ for (const [at, calls, notice] of [+ [11500, 2, 'clipboardSyncFailed'],+ [12900, 2, 'clipboardSyncFailed'],+ [13000, 3, 'clipboardSyncFailed'],+ [15900, 3, 'clipboardSyncFailed'],+ [16000, 4, 'clipboardSyncFailed'],+ [20900, 4, 'clipboardSyncFailed'],+ ] as const) {+ now.mockReturnValue(at);+ expect((await safety.tick(sync)).notice).toBe(notice);+ expect(tick).toHaveBeenCalledTimes(calls);+ }+ // Regained focus or a shortcut: no waiting, and the failure count starts over.+ safety.wake();+ expect((await safety.tick(sync)).notice).toBe('clipboardSyncFailed');+ expect(tick).toHaveBeenCalledTimes(5);+ now.mockReturnValue(22400);+ expect((await safety.tick(sync)).notice).toBeNull();+ expect(tick).toHaveBeenCalledTimes(6);+ } finally {+ now.mockRestore();+ tick.mockRestore();+ }+});++it('a permission failure still waits for an explicit retry', async () => {+ const { safety, sync } = syncFixture();+ const tick = vi+ .spyOn(ClipboardSync.prototype, 'tick')+ .mockRejectedValueOnce(new Error('CLIPBOARD_PERMISSION_DENIED'))+ .mockResolvedValue(undefined);+ try {+ expect((await safety.tick(sync)).notice).toBe('clipboardSyncPermission');+ safety.wake();+ expect((await safety.tick(sync)).notice).toBe('clipboardSyncPermission');+ expect(tick).toHaveBeenCalledOnce();+ } finally {+ tick.mockRestore();+ }+});++it("this computer's own clipboard helper failing is a plain failure, not the other computer being locked", async () => {+ const { safety, sync, clipboardEnables } = syncFixture();+ const version = vi.fn(async () => {+ throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');+ });+ expect((await safety.tick({ ...sync, clipboard: { ...sync.clipboard, version } })).notice).toBe(+ 'clipboardSyncFailed',+ );+ expect(version).toHaveBeenCalled();+ await safety.tick({ ...sync, clipboard: { ...sync.clipboard, version } });+ expect(clipboardEnables()).toHaveLength(1);+});+it('keeps conflict feedback until content is actually synchronized', async () => {const { safety, options } = fixture();const now = vi.spyOn(Date, 'now').mockReturnValue(10000);@@ -138,3 +269,89 @@ it('keeps conflict feedback until content is actually synchronized', async () =>tick.mockRestore();}});++it.each([+ ['none', 'local'],+ ['none', 'remote'],+ ['remote', 'local'],+ ['local', 'remote'],+] as const)(+ 'after a conflict with %s unreadable, recopying identical %s content selects it',+ async (unreadable, chosen) => {+ const { safety, sync } = syncFixture();+ const local = {+ version: 1,+ json: JSON.stringify({ text: 'local initial' }),+ unreadable: false,+ };+ const remote = {+ version: 1,+ json: JSON.stringify({ text: 'remote initial' }),+ unreadable: false,+ };+ const write = vi.fn(async (json: string, version: string | undefined) => {+ expect(version).toBe(String(local.version));+ local.json = json;+ local.unreadable = false;+ return String(++local.version);+ });+ const paste = vi.fn((json: string) => {+ remote.json = json;+ remote.unreadable = false;+ return { version: String(++remote.version) };+ });+ const request = vi.fn(async (message: RemoteDesktopRequest): Promise<unknown> => {+ if (message.op === 'clipboardVersion') return { version: String(remote.version) };+ if (message.op === 'clipboardContent' && message.action === 'copy') {+ if (remote.unreadable) throw new Error('CLIPBOARD_UNSUPPORTED');+ return { length: remote.json.length, data: remote.json };+ }+ if (message.op === 'clipboardContent' && message.action === 'paste')+ return paste(message.data);+ return { enabled: true };+ });+ const options: Parameters<ViewerSafety['tick']>[0] = {+ ...sync,+ caps: { ...sync.caps, clipboardInline: true },+ request: request as Parameters<ViewerSafety['tick']>[0]['request'],+ clipboard: {+ version: async () => String(local.version),+ read: async () => {+ if (local.unreadable) throw new Error('CLIPBOARD_UNSUPPORTED');+ return local.json;+ },+ write,+ },+ };+ await safety.tick(options);+ local.version++;+ remote.version++;+ local.json = JSON.stringify({ text: 'local choice' });+ remote.json = JSON.stringify({ text: 'remote choice' });+ local.unreadable = unreadable === 'local';+ remote.unreadable = unreadable === 'remote';+ expect((await safety.tick(options)).notice).toBe('clipboardSyncConflict');++ // An idle poll cannot pick a winner or clear the conflict on its own.+ safety.wake();+ expect((await safety.tick(options)).notice).toBe('clipboardSyncConflict');+ expect(write).not.toHaveBeenCalled();+ expect(paste).not.toHaveBeenCalled();++ const source = chosen === 'local' ? local : remote;+ const selected = source.json;+ source.version++; // Recopy exactly the same readable content, changing only its counter.+ safety.wake();+ expect((await safety.tick(options)).notice).toBeNull();+ expect(local.json).toBe(selected);+ expect(remote.json).toBe(selected);+ expect(write).toHaveBeenCalledTimes(chosen === 'remote' ? 1 : 0);+ expect(paste).toHaveBeenCalledTimes(chosen === 'local' ? 1 : 0);++ // Once resolved, normal identical-content deduplication is restored.+ source.version++;+ await safety.tick(options);+ expect(write).toHaveBeenCalledTimes(chosen === 'remote' ? 1 : 0);+ expect(paste).toHaveBeenCalledTimes(chosen === 'local' ? 1 : 0);+ },+);diff --git a/apps/desktop/src/main/remote-desktop-viewer/connection.ts b/apps/desktop/src/main/remote-desktop-viewer/connection.tsindex 56c65fd362..16dfcd3888 100644--- a/apps/desktop/src/main/remote-desktop-viewer/connection.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/connection.ts@@ -28,6 +28,9 @@ import {import { ViewerSafety, type ViewerClipboard } from './safety.js';import type { ViewerCredentials } from './credentials.js';+/** After the window leaves the foreground, one last pass may still read the local clipboard. */+const CLIPBOARD_GRACE_MS = 1000;+/** Main owns the target, account generation and lease for one lightweight viewer.* A destroyed/hidden window cannot leave late starts or inputs alive. No closeLink.*/@@ -51,6 +54,7 @@ export class RemoteViewerConnection {private preferencesValue = { ...DEFAULT_VIEWER_PREFERENCES };private safetyState = new ViewerSafety();private clipboardProgress: number | null = null;+ private clipboardGrace = 0;private channelRequests = new Map<string, (outcome: RemoteViewerChannelOutcome) => void>();private channelRequestId = 0;constructor(@@ -247,7 +251,8 @@ export class RemoteViewerConnection {check();const caps = result as RemoteDesktopCapabilities;// A window view never runs whole-desktop safety features (masks, mute, clipboard sync).- this.caps = target.handoff && caps?.handoffWindow ? handoffWindowCapabilities(caps) : caps;+ this.caps =+ target.handoff && caps?.handoffWindow ? handoffWindowCapabilities(caps) : caps;}if (isStart) {const lease = result as RemoteDesktopLease;@@ -470,13 +475,41 @@ export class RemoteViewerConnection {this.check(generation);return parsed;}+ private focused(): boolean {+ return this.deps.focused?.() ?? true;+ }+ /**+ * Focus only decides when this window reads its own clipboard; the computer's+ * sync stays enabled for the whole control session. Regaining focus syncs at+ * once; leaving runs one pass at once (so a copy made on the computer arrives+ * here before the user pastes). New local reads stay+ * allowed for CLIPBOARD_GRACE_MS after the blur, not just for that pass: a+ * copy chord's delayed pull (about 200 ms after the key) may land after it.+ */async focusChanged(): Promise<void> {const generation = this.generation;- // Cancel local reads immediately, then reconcile after any old enable has- // settled. Use current focus when reconciling (blur/focus may race).- await this.safetyState.pauseClipboard();- if (!this.active || generation !== this.generation) return;+ const live = () => this.active && generation === this.generation;+ if (this.focused()) {+ // Wake only after in-flight work settles: its failure would re-arm the backoff.+ await this.safetyState.idle();+ this.safetyState.wake();+ if (live()) await this.safety(generation).catch(() => {});+ return;+ }+ this.clipboardGrace = Date.now() + CLIPBOARD_GRACE_MS;+ await this.safetyState.idle();+ if (!live() || this.focused()) return;await this.safety(generation).catch(() => {});+ // No blur cleanup: idle() waiters may already have started the delayed+ // copy pass. The grace gates new passes; ClipboardCounter retires itself+ // when idle. Only authority changes cancel work already admitted.+ }+ /** A copy or paste in the picture: sync now instead of at the next poll. */+ async syncClipboard(generation: number): Promise<RemoteViewerSafety> {+ this.check(generation);+ await this.safetyState.idle();+ this.safetyState.wake();+ return this.safety(generation);}async safety(generation: number, retry = false): Promise<RemoteViewerSafety> {this.check(generation);@@ -491,18 +524,18 @@ export class RemoteViewerConnection {return false;}};+ // Focus and blur grace only admit a pass. Once admitted it finishes across+ // focus changes and deadline expiry; authority and manual transfers still+ // invalidate it through current()/clipboardPending.+ const clipboardAllowed = this.focused() || Date.now() < this.clipboardGrace;const value =lease && this.caps? await this.safetyState.tick({lease,caps: this.caps,- preferences: {- ...this.preferencesValue,- clipboardSync: this.preferencesValue.clipboardSync && (this.deps.focused?.() ?? true),- },+ preferences: { ...this.preferencesValue },current,- clipboardCurrent: () =>- current() && !this.clipboardPending && (this.deps.focused?.() ?? true),+ clipboardCurrent: () => current() && !this.clipboardPending && clipboardAllowed,clipboard: this.deps.clipboard,request: async (message, check) => {check();diff --git a/apps/desktop/src/main/remote-desktop-viewer/safety.ts b/apps/desktop/src/main/remote-desktop-viewer/safety.tsindex 30c1184abf..577e39836e 100644--- a/apps/desktop/src/main/remote-desktop-viewer/safety.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/safety.ts@@ -1,6 +1,7 @@import { createHash } from 'node:crypto';import {ClipboardSync,+ clipboardSyncErrorCode,clipboardSyncFailure,parseClipboardContent,type ClipboardSyncBaseline,@@ -17,24 +18,63 @@ export interface ViewerClipboard {write(json: string, version: string | undefined, current: () => boolean): Promise<string>;}+/** The viewer's own clipboard helper failing is not the computer being locked. */+const VIEWER_CLIPBOARD_UNAVAILABLE = 'DESKTOP_VIEWER_CLIPBOARD_UNAVAILABLE';+const RETRY_MS = 1500;+const MAX_BACKOFF_MS = 5000;++export interface ViewerClipboardFailure {+ code: string;+ /** Status key for the viewer window; null keeps whatever is shown. */+ notice: string | null;+ /** Milliseconds until the next attempt; null waits for an explicit retry. */+ delay: number | null;+ /** Settles by itself (locked computer, a copy mid-read); never grows the backoff. */+ transient: boolean;+}++/** How one sync failure is retried. Only unexplained failures back off, and briefly. */+export function viewerClipboardFailure(error: unknown, failures: number): ViewerClipboardFailure {+ const shared = clipboardSyncFailure(error, failures);+ const code = clipboardSyncErrorCode(error);+ if (shared.delay === null) return { ...shared, transient: false };+ if (code === 'CLIPBOARD_CONFLICT')+ return { code, notice: 'clipboardSyncConflict', delay: RETRY_MS, transient: true };+ // The computer's clipboard is refused while its screen is locked or it is busy.+ if (code === 'DESKTOP_CLIPBOARD_UNAVAILABLE')+ return { code, notice: 'clipboardSyncWaiting', delay: RETRY_MS, transient: true };+ if (+ code.endsWith('_CHANGED') ||+ ['DESKTOP_BUSY', 'DESKTOP_CLIPBOARD_BUSY', 'DESKTOP_INPUT_BUSY'].includes(code)+ )+ return { code, notice: null, delay: RETRY_MS, transient: true };+ return {+ code,+ notice: 'clipboardSyncFailed',+ delay: Math.min(MAX_BACKOFF_MS, RETRY_MS * 2 ** Math.min(failures, 2)),+ transient: false,+ };+}+/** One lease's opt-ins. Clipboard payloads stay in Main; callers only receive status. */export class ViewerSafety {private clipboard: ViewerClipboard | undefined;private revision = 0;- private clipboardRevision = 0;- private pending = false;+ private inflight: Promise<RemoteViewerSafety> | null = null;private settled: Promise<void> = Promise.resolve();async pause(): Promise<void> {this.invalidate();await this.settled;}- async pauseClipboard(): Promise<void> {- this.clipboardRevision++;- this.clipboard?.stop?.();- await this.settled;- // Focus changes must not retry privacy/mute failures or clear their status.- this.applied.delete('clipboardSync');+ /** Resolves once in-flight work has settled, so a caller can run a fresh tick. */+ idle(): Promise<void> {+ return this.settled;+ }+ /** Regained focus or a copy/paste: retry now, unless sync waits for a permission. */+ wake(): void {+ if (this.retryAt === Infinity) return;this.retryAt = 0;+ this.failures = 0;}private baseline: ClipboardSyncBaseline = { local: '', remote: '' };private localReadCache: LocalClipboardReadCache = {};@@ -67,6 +107,21 @@ export class ViewerSafety {clipboardProgress: null,};}+ private recordClipboardFailure(error: unknown): void {+ const failure = viewerClipboardFailure(error, this.failures);+ if (failure.code === 'CLIPBOARD_CONFLICT') {+ // Preserve counters so an idle poll cannot choose a winner. Forget the+ // conflicting digests so the next copy selects that side even when its+ // content is unchanged; a successful transfer restores normal deduping.+ delete this.baseline.localDigest;+ delete this.baseline.remoteDigest;+ }+ if (!failure.transient) this.failures++;+ // Only the computer refusing sync needs it re-enabled; a local helper failure does not.+ if (failure.code === 'DESKTOP_CLIPBOARD_UNAVAILABLE') this.applied.delete('clipboardSync');+ if (failure.notice) this.notices.set('clipboardSync', failure.notice);+ this.retryAt = failure.delay === null ? Infinity : Date.now() + failure.delay;+ }async tick(options: {lease: string;caps: RemoteDesktopCapabilities;@@ -76,119 +131,126 @@ export class ViewerSafety {clipboard?: ViewerClipboard;request<T>(request: RemoteDesktopRequest, check: () => void): Promise<T>;}): Promise<RemoteViewerSafety> {- if (this.pending || !options.current()) return this.snapshot();+ // One pass at a time, and a caller that finds one in flight shares its+ // result. Two wakeups that waited on the same idle() race for the fresh+ // pass; the loser must not settle on a stale snapshot and open the paste+ // gate before that pass has pushed the clipboard.+ if (this.inflight) return this.inflight;+ if (!options.current()) return this.snapshot();this.clipboard = options.clipboard;- this.pending = true;let settle!: () => void;this.settled = new Promise((resolve) => {settle = resolve;});+ this.inflight = this.pass(options).finally(() => {+ this.inflight = null;+ settle();+ });+ return this.inflight;+ }+ private async pass(options: {+ lease: string;+ caps: RemoteDesktopCapabilities;+ preferences: RemoteViewerPreferences;+ current(): boolean;+ clipboardCurrent(): boolean;+ clipboard?: ViewerClipboard;+ request<T>(request: RemoteDesktopRequest, check: () => void): Promise<T>;+ }): Promise<RemoteViewerSafety> {const revision = this.revision;- const clipboardRevision = this.clipboardRevision;const valid = () => revision === this.revision && options.current();const check = () => {if (!valid()) throw new Error('DESKTOP_STOPPED');};const request = <T>(message: RemoteDesktopRequest) => options.request<T>(message, check);const { caps, lease, preferences } = options;- try {- for (const op of ['privacyScreen', 'hostMute', 'clipboardSync'] as const) {- if (op === 'clipboardSync' && Date.now() < this.retryAt) continue;- if (!caps[op] || this.applied.get(op) === preferences[op]) continue;- try {- check();- const result = await request<{ enabled?: boolean }>({- op,- lease,- enabled: preferences[op],- ...(op === 'privacyScreen' ? { lockOnExit: preferences.lockOnExit } : {}),- });- check();+ for (const op of ['privacyScreen', 'hostMute', 'clipboardSync'] as const) {+ if (op === 'clipboardSync' && Date.now() < this.retryAt) continue;+ if (!caps[op] || this.applied.get(op) === preferences[op]) continue;+ try {+ check();+ const result = await request<{ enabled?: boolean }>({+ op,+ lease,+ enabled: preferences[op],+ ...(op === 'privacyScreen' ? { lockOnExit: preferences.lockOnExit } : {}),+ });+ check();+ this.applied.set(op, preferences[op]);+ if (op === 'privacyScreen') this.privacyActive = result.enabled === true;+ this.notices.delete(op);+ } catch (error) {+ if (!valid()) return this.snapshot();+ // Retry is explicit for safety failures; synchronization follows its own schedule.+ if (op === 'clipboardSync') this.recordClipboardFailure(error);+ else {+ this.notices.set(op, op === 'privacyScreen' ? 'privacyFailed' : 'hostMuteFailed');this.applied.set(op, preferences[op]);- if (op === 'privacyScreen') this.privacyActive = result.enabled === true;- this.notices.delete(op);- } catch (error) {- if (!valid()) return this.snapshot();- this.notices.set(- op,- op === 'privacyScreen'- ? 'privacyFailed'- : op === 'hostMute'- ? 'hostMuteFailed'- : 'clipboardSyncFailed',- );- // Retry is explicit for safety failures; synchronization follows its existing backoff below.- if (op === 'clipboardSync') {- const failure = clipboardSyncFailure(error, this.failures++);- this.retryAt = failure.delay === null ? Infinity : Date.now() + failure.delay;- this.notices.set(op, failure.notice);- } else this.applied.set(op, preferences[op]);}}- if (- !preferences.clipboardSync ||- !caps.clipboardSync ||- !options.clipboard ||- this.applied.get('clipboardSync') !== true ||- Date.now() < this.retryAt ||- !options.clipboardCurrent()- )- return this.snapshot();- const current = () =>- valid() && clipboardRevision === this.clipboardRevision && options.clipboardCurrent();- const clipboardCheck = () => {- if (!current()) throw new Error('DESKTOP_STOPPED');- };- const engine = new ClipboardSync(- {- lease,- current,- inline: caps.clipboardInline === true,- request: (message) => options.request(message, clipboardCheck),- localVersion: () => options.clipboard!.version(current),- readLocal: () => options.clipboard!.read(current),- writeLocal: (json, version) => options.clipboard!.write(json, version, current),- localReadCache: this.localReadCache,- trace: (stage) => {- if (!valid()) return;- if (stage === 'content-skipped')- this.notices.set('clipboardSync', 'clipboardSyncSkipped');- else if (['phone-to-computer-complete', 'computer-to-phone-complete'].includes(stage))- this.notices.delete('clipboardSync');- },- digest: (json) => {- const c = parseClipboardContent(json);- return createHash('sha256')- .update(JSON.stringify([c.text, c.html, c.rtf, c.url, c.png]))- .digest('hex');- },+ }+ if (+ !preferences.clipboardSync ||+ !caps.clipboardSync ||+ !options.clipboard ||+ this.applied.get('clipboardSync') !== true ||+ Date.now() < this.retryAt ||+ !options.clipboardCurrent()+ )+ return this.snapshot();+ const current = () => valid() && options.clipboardCurrent();+ const clipboardCheck = () => {+ if (!current()) throw new Error('DESKTOP_STOPPED');+ };+ const local = <T>(work: Promise<T>) =>+ work.catch((error: unknown) => {+ throw error instanceof Error && error.message === 'DESKTOP_CLIPBOARD_UNAVAILABLE'+ ? new Error(VIEWER_CLIPBOARD_UNAVAILABLE)+ : error;+ });+ const engine = new ClipboardSync(+ {+ lease,+ current,+ inline: caps.clipboardInline === true,+ request: (message) => options.request(message, clipboardCheck),+ localVersion: () => local(options.clipboard!.version(current)),+ readLocal: () => local(options.clipboard!.read(current)),+ writeLocal: (json, version) => local(options.clipboard!.write(json, version, current)),+ localReadCache: this.localReadCache,+ trace: (stage) => {+ if (!valid()) return;+ if (stage === 'content-skipped')+ this.notices.set('clipboardSync', 'clipboardSyncSkipped');+ else if (['phone-to-computer-complete', 'computer-to-phone-complete'].includes(stage))+ this.notices.delete('clipboardSync');},- this.baseline,- );- // Results of a paused or refocused clipboard generation are stale: pauseClipboard stops- // the read (DESKTOP_CLIPBOARD_UNAVAILABLE), which must not count as a sync failure.- try {- await engine.tick();- if (current()) {- if (- ['clipboardSyncFailed', 'clipboardSyncPermission'].includes(- this.notices.get('clipboardSync') ?? '',- )+ digest: (json) => {+ const c = parseClipboardContent(json);+ return createHash('sha256')+ .update(JSON.stringify([c.text, c.html, c.rtf, c.url, c.png]))+ .digest('hex');+ },+ },+ this.baseline,+ );+ // Authority changes stop pending reads. Their late results must not count+ // as sync failures for the next control session.+ try {+ await engine.tick();+ if (current()) {+ if (+ ['clipboardSyncFailed', 'clipboardSyncPermission', 'clipboardSyncWaiting'].includes(+ this.notices.get('clipboardSync') ?? '',)- this.notices.delete('clipboardSync');- this.failures = 0;- }- } catch (error) {- if (!current()) return this.snapshot();- const failure = clipboardSyncFailure(error, this.failures++);- if (failure.code === 'DESKTOP_CLIPBOARD_UNAVAILABLE') this.applied.delete('clipboardSync');- this.notices.set('clipboardSync', failure.notice);- this.retryAt = failure.delay === null ? Infinity : Date.now() + failure.delay;+ )+ this.notices.delete('clipboardSync');+ this.failures = 0;}- return this.snapshot();- } finally {- this.pending = false;- settle();+ } catch (error) {+ if (!current()) return this.snapshot();+ this.recordClipboardFailure(error);}+ return this.snapshot();}}diff --git a/apps/desktop/src/main/remote-desktop-viewer/windows.ts b/apps/desktop/src/main/remote-desktop-viewer/windows.tsindex 3443bc661d..85c1fc106a 100644--- a/apps/desktop/src/main/remote-desktop-viewer/windows.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/windows.ts@@ -165,9 +165,11 @@ export class RemoteDesktopViewerWindows {},focused: () => entry.window?.isFocused() === true,clipboard: {+ // The plain counter: a multi-item local clipboard (several files) is+ // reported by the content read and skipped, without failing the pass.version: (current) => {if (!current()) return Promise.reject(new Error('DESKTOP_STOPPED'));- return counter.read(true);+ return counter.read();},stop: () => counter.stop(),read: async (current) =>@@ -226,6 +228,7 @@ export class RemoteDesktopViewerWindows {this.setInputCaptured(entry, false);void connection.focusChanged();});+ win.on('focus', () => void connection.focusChanged());// The session survives hiding; the page pauses the host's video instead.const hidden = (value: boolean) => () => {if (!win.isDestroyed() && !win.webContents.isDestroyed())@@ -329,6 +332,13 @@ export class RemoteDesktopViewerWindows {throwIpcError('PRECONDITION_FAILED', 'DESKTOP_STOPPED');}});+ ipcMain.handle(REMOTE_VIEWER.CLIPBOARD_SYNC, async (event, generation) => {+ try {+ return await this.entry(event).connection.syncClipboard(generation);+ } catch {+ throwIpcError('PRECONDITION_FAILED', 'DESKTOP_STOPPED');+ }+ });ipcMain.handle(REMOTE_VIEWER.REQUEST, async (event, generation, request, attempt) => {const result = await this.entry(event).connection.request(generation, request, attempt);if (!result.ok) throwIpcError('PRECONDITION_FAILED', result.code);diff --git a/apps/desktop/src/preload/remoteDesktopViewerPreload.ts b/apps/desktop/src/preload/remoteDesktopViewerPreload.tsindex cc4acd6daa..2843cafe53 100644--- a/apps/desktop/src/preload/remoteDesktopViewerPreload.ts+++ b/apps/desktop/src/preload/remoteDesktopViewerPreload.ts@@ -98,6 +98,7 @@ contextBridge.exposeInMainWorld('electronAPI', {preferences: (generation, patch) =>ipcRenderer.invoke(REMOTE_VIEWER.PREFERENCES, generation, patch),safety: (generation, retry) => ipcRenderer.invoke(REMOTE_VIEWER.SAFETY, generation, retry),+ clipboardSync: (generation) => ipcRenderer.invoke(REMOTE_VIEWER.CLIPBOARD_SYNC, generation),resolution: (generation, displayId, value) =>ipcRenderer.invoke(REMOTE_VIEWER.RESOLUTION, generation, displayId, value),onChannelRequest: (cb) => onPayload(REMOTE_VIEWER.CHANNEL_REQUEST, cb),diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerControl.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerControl.test.tsindex 39bcca491e..dcd5dfeb2e 100644--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerControl.test.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerControl.test.ts@@ -3,6 +3,7 @@ import type {RememberedViewerResolution,RemoteDesktopViewerApi,RemoteViewerChannelRequest,+ RemoteViewerSafety,} from '../../../../shared/remoteDesktopViewer';import {clipboardFailureKey,@@ -237,6 +238,194 @@ it('ignores clipboard messages from the picture; shortcuts reach the host as keyexpect(init).toMatchObject({ macKeyboard: false });});+const syncOn = async (clipboardSync: RemoteDesktopViewerApi['clipboardSync']) => {+ const current = await fixture(undefined, false, {+ api: {+ clipboardSync,+ preferences: async () => ({+ audio: true,+ privacyScreen: false,+ hostMute: false,+ clipboardSync: true,+ lockOnExit: false,+ }),+ },+ });+ present();+ await vi.advanceTimersByTimeAsync(0);+ return current;+};+const gateReleases = () =>+ runtime.receive.mock.calls.filter(([message]) => message.type === 'inputGate').length;+const idle: RemoteViewerSafety = { privacyActive: false, notice: null, clipboardProgress: null };++it('a paste shortcut holds the keys until the local clipboard has been pushed', async () => {+ const sync = deferred<RemoteViewerSafety>();+ const clipboardSync = vi.fn(() => sync.promise);+ await syncOn(clipboardSync);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(0);+ expect(clipboardSync).toHaveBeenCalledExactlyOnceWith(1);+ expect(gateReleases()).toBe(0);+ sync.resolve({ ...idle, notice: 'clipboardSyncSkipped' });+ await vi.advanceTimersByTimeAsync(0);+ // One gate holds both shortcuts; the latest paste's wait opens it once.+ expect(gateReleases()).toBe(1);+ expect(snapshot.safety.notice).toBe('clipboardSyncSkipped');+});++it('an earlier paste reaching its deadline never opens the gate a later paste re-armed', async () => {+ const sync = deferred<RemoteViewerSafety>();+ const clipboardSync = vi.fn(() => sync.promise);+ await syncOn(clipboardSync);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(900);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ // The first paste's second passes while the shared push is still in flight.+ await vi.advanceTimersByTimeAsync(500);+ expect(clipboardSync).toHaveBeenCalledOnce();+ expect(gateReleases()).toBe(0);+ sync.resolve(idle);+ await vi.advanceTimersByTimeAsync(0);+ expect(gateReleases()).toBe(1);+ // A stalled push: the latest paste's own deadline opens the gate, once.+ clipboardSync.mockImplementationOnce(() => new Promise<RemoteViewerSafety>(() => {}));+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(600);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(999);+ expect(gateReleases()).toBe(1);+ await vi.advanceTimersByTimeAsync(1);+ expect(gateReleases()).toBe(2);+});++it('a paste shortcut is released after one second when the sync pass stalls; later pastes keep waiting on that pass', async () => {+ const sync = deferred<RemoteViewerSafety>();+ const clipboardSync = vi.fn(() => sync.promise);+ await syncOn(clipboardSync);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(999);+ expect(gateReleases()).toBe(0);+ await vi.advanceTimersByTimeAsync(1);+ expect(gateReleases()).toBe(1);+ // The pass is still in flight: a second paste neither starts another one nor+ // opens early; it is released by the real push within its own second.+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(500);+ expect(clipboardSync).toHaveBeenCalledOnce();+ expect(gateReleases()).toBe(1);+ sync.resolve(idle);+ await vi.advanceTimersByTimeAsync(0);+ expect(gateReleases()).toBe(2);+ // Once that pass has settled, the next paste starts a fresh one.+ clipboardSync.mockImplementationOnce(async () => idle);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(0);+ expect(clipboardSync).toHaveBeenCalledTimes(2);+ expect(gateReleases()).toBe(3);+});++it('tells the picture which modifier is copy/paste on the controlled computer', async () => {+ await fixture(undefined, false, { caps: { platform: 'darwin' } });+ expect(runtime.receive.mock.calls.find(([m]) => m.type === 'init')?.[0]).toMatchObject({+ clipboardModifier: 'meta',+ });+ controller.dispose();+ await fixture(undefined, false, { caps: { platform: 'win32' } });+ expect(runtime.receive.mock.calls.findLast(([m]) => m.type === 'init')?.[0]).toMatchObject({+ clipboardModifier: 'control',+ });+});++it('a display switch that drops and regains control without a reconnect drops the old paste sync', async () => {+ const first = deferred<RemoteViewerSafety>();+ const clipboardSync = vi.fn(() => first.promise);+ await fixture(undefined, true, {+ api: {+ clipboardSync,+ preferences: async () => ({+ audio: true,+ privacyScreen: false,+ hostMute: false,+ clipboardSync: true,+ lockOnExit: false,+ }),+ },+ });+ present();+ await vi.advanceTimersByTimeAsync(0);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(0);+ expect(clipboardSync).toHaveBeenCalledOnce();+ // Changing the resolution suspends control and re-acquires it; no cancel() runs.+ await controller.resolution(mode4k);+ await vi.advanceTimersByTimeAsync(0);+ expect(+ runtime.receive.mock.calls.filter(([m]) => m.type === 'control').map(([m]) => m.enabled),+ ).toContain(false);+ expect(inputEnabled()).toBe(true);+ const second = deferred<RemoteViewerSafety>();+ clipboardSync.mockImplementationOnce(() => second.promise);+ const before = gateReleases();+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(0);+ // The retired pass is not reused, and its late settlement opens nothing.+ expect(clipboardSync).toHaveBeenCalledTimes(2);+ first.resolve(idle);+ await vi.advanceTimersByTimeAsync(0);+ expect(gateReleases()).toBe(before);+ second.resolve(idle);+ await vi.advanceTimersByTimeAsync(0);+ expect(gateReleases()).toBe(before + 1);+});++it('a paste waiting on the old session never opens the gate of the next one', async () => {+ const sync = deferred<RemoteViewerSafety>();+ const clipboardSync = vi.fn(() => sync.promise);+ await syncOn(clipboardSync);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(0);+ expect(clipboardSync).toHaveBeenCalledOnce();+ // Reconnecting retires the old session; its sync may still settle later.+ controller.retry();+ await vi.advanceTimersByTimeAsync(0);+ present();+ await vi.advanceTimersByTimeAsync(0);+ sync.resolve(idle);+ await vi.advanceTimersByTimeAsync(0);+ expect(gateReleases()).toBe(0);+ // The next session's paste starts its own pass and is released by it.+ const again = deferred<RemoteViewerSafety>();+ clipboardSync.mockImplementationOnce(() => again.promise);+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(0);+ expect(clipboardSync).toHaveBeenCalledTimes(2);+ expect(gateReleases()).toBe(0);+ again.resolve(idle);+ await vi.advanceTimersByTimeAsync(0);+ expect(gateReleases()).toBe(1);+});++it('a copy shortcut pulls the computer clipboard shortly after; paste never waits with sync off', async () => {+ const clipboardSync = vi.fn(async () => idle);+ await syncOn(clipboardSync);+ runtime.post?.({ type: 'clipboardIntent', action: 'copy', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(199);+ expect(clipboardSync).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(clipboardSync).toHaveBeenCalledExactlyOnceWith(1);+ controller.dispose();+ const off = vi.fn(async () => idle);+ await fixture(undefined, false, { api: { clipboardSync: off } });+ present();+ runtime.post?.({ type: 'clipboardIntent', action: 'paste', epoch: 'lease' });+ runtime.post?.({ type: 'clipboardIntent', action: 'copy', epoch: 'lease' });+ await vi.advanceTimersByTimeAsync(300);+ expect(off).not.toHaveBeenCalled();+ expect(gateReleases()).toBe(1);+});+it('tells the picture when the controller keyboard follows macOS Command rules', async () => {vi.stubGlobal('window', { electronAPI: { platform: 'darwin' } });try {diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.tsindex 2a5d96920d..67b7d8ccff 100644--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerInput.test.ts@@ -243,7 +243,13 @@ it.each([it.each(['control', 'meta'])('forwards %s clipboard shortcuts to the remote computer as ordinary keys',(modifier) => {- viewer.receive({ type: 'init', epoch: 'lease', width: 1000, height: 600 });+ viewer.receive({+ type: 'init',+ epoch: 'lease',+ width: 1000,+ height: 600,+ clipboardModifier: modifier,+ });viewer.receive({ type: 'control', enabled: true });pointer('pointerdown');pointer('pointerup');@@ -251,6 +257,22 @@ it.each(['control', 'meta'])(const input = document.getElementById('keyboard-input')!;const modifiers = { ctrlKey: modifier === 'control', metaKey: modifier === 'meta' };const modifierCode = modifier === 'meta' ? 'MetaLeft' : 'ControlLeft';+ // The other modifier is an ordinary chord on this computer (Ctrl+C in a macOS+ // terminal, Win+V on Windows): no announcement, no waiting.+ const other = modifier === 'meta' ? 'ControlLeft' : 'MetaLeft';+ const otherFlags = { ctrlKey: modifier !== 'control', metaKey: modifier !== 'meta' };+ for (const code of ['KeyC', 'KeyV']) {+ input.dispatchEvent(+ new KeyboardEvent('keydown', { code: other, ...otherFlags, bubbles: true }),+ );+ input.dispatchEvent(new KeyboardEvent('keydown', { code, ...otherFlags, bubbles: true }));+ input.dispatchEvent(new KeyboardEvent('keyup', { code, ...otherFlags, bubbles: true }));+ input.dispatchEvent(new KeyboardEvent('keyup', { code: other, bubbles: true }));+ }+ vi.advanceTimersByTime(34);+ expect(messages.some((m) => m.type === 'clipboardIntent')).toBe(false);+ expect(events().filter((event) => event.kind === 'key')).toHaveLength(8);+ messages = [];for (const code of ['KeyC', 'KeyV']) {input.dispatchEvent(new KeyboardEvent('keydown', { code: modifierCode, ...modifiers, bubbles: true }),@@ -271,6 +293,15 @@ it.each(['control', 'meta'])(}vi.advanceTimersByTime(34);expect(messages.some((message) => message.type === 'clipboard')).toBe(false);+ // The shortcuts are only announced: copy so the controller pulls the computer's+ // clipboard soon after, paste so it pushes the local one first. Until the+ // controller releases the paste gate, the queued keys wait.+ expect(messages.filter((m) => m.type === 'clipboardIntent').map((m) => m.action)).toEqual([+ 'copy',+ 'paste',+ ]);+ expect(events()).toEqual([]);+ viewer.receive({ type: 'inputGate' });expect(events().filter((event) => event.kind === 'key' || event.kind === 'text')).toEqual(['KeyC', 'KeyV'].flatMap((code) => [{ kind: 'key', code: modifierCode, down: true },@@ -281,6 +312,77 @@ it.each(['control', 'meta'])();},);+const macHost = () => {+ viewer.receive({+ type: 'init',+ epoch: 'lease',+ width: 1000,+ height: 600,+ clipboardModifier: 'meta',+ });+ viewer.receive({ type: 'control', enabled: true });+ pointer('pointerdown');+ pointer('pointerup');+ messages = [];+ const input = document.getElementById('keyboard-input')!;+ const key = (type: 'keydown' | 'keyup', code: string) =>+ input.dispatchEvent(new KeyboardEvent(type, { code, metaKey: true, bubbles: true }));+ const chord = (code: string) => {+ key('keydown', 'MetaLeft');+ key('keydown', code);+ key('keyup', code);+ input.dispatchEvent(new KeyboardEvent('keyup', { code: 'MetaLeft', bubbles: true }));+ };+ return { input, key, chord };+};+it('a held paste is dropped, not sent late, when the window loses focus', () => {+ const { key } = macHost();+ key('keydown', 'MetaLeft');+ key('keydown', 'KeyV');+ vi.advanceTimersByTime(34);+ expect(events()).toEqual([]);+ window.dispatchEvent(new Event('blur'));+ vi.advanceTimersByTime(34);+ // The release goes out at once; the queued Command and V never do.+ expect(events()).toEqual([{ kind: 'release' }]);+ vi.advanceTimersByTime(1300);+ expect(events()).toEqual([{ kind: 'release' }]);+});+it('re-arming the paste gate never ages the held batch into an input overflow', () => {+ const { chord } = macHost();+ chord('KeyV');+ vi.advanceTimersByTime(900);+ chord('KeyV');+ vi.advanceTimersByTime(900);+ chord('KeyV');+ // Older than the 2 s freshness budget, but held on purpose: no overflow, no reconnect.+ vi.advanceTimersByTime(300);+ expect(events()).toEqual([]);+ expect(messages.some((m) => m.type === 'inputOverflow')).toBe(false);+ viewer.receive({ type: 'inputGate' });+ vi.advanceTimersByTime(34);+ expect(events().filter((event) => event.kind === 'key')).toHaveLength(12);+ expect(messages.some((m) => m.type === 'inputOverflow')).toBe(false);+});+it('releases a paste that the controller never answers after 1.2s, and never holds a copy', () => {+ const { input, chord } = macHost();+ chord('KeyC');+ vi.advanceTimersByTime(34);+ expect(events().filter((event) => event.kind === 'key')).toHaveLength(4);+ chord('KeyV');+ vi.advanceTimersByTime(1100);+ expect(events().filter((event) => event.kind === 'key')).toHaveLength(4);+ vi.advanceTimersByTime(200);+ expect(events().filter((event) => event.kind === 'key')).toHaveLength(8);+ // Auto-repeat of a held paste neither re-announces nor re-arms the gate.+ messages = [];+ input.dispatchEvent(+ new KeyboardEvent('keydown', { code: 'KeyV', metaKey: true, repeat: true, bubbles: true }),+ );+ vi.advanceTimersByTime(34);+ expect(messages.some((m) => m.type === 'clipboardIntent')).toBe(false);+ expect(events().filter((event) => event.kind === 'key')).toHaveLength(1);+});// Invariant: a remote key is released only when its local keyup arrives, except// keys pressed while Command is held on a macOS controller (macOS swallows their// keyup); those alone are released together with Command.diff --git a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts b/apps/desktop/src/renderer/features/remote-desktop/viewerController.tsindex a7b96b01c4..6a0ff3d940 100644--- a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts@@ -70,6 +70,10 @@ const sameAspect = (display: Size, width: number, height: number) =>/** macOS reports native fullscreen transitions as a brief hide/show; only a* viewer that stays hidden pauses the host's video. Showing resumes at once. */const HIDDEN_VIDEO_PAUSE_MS = 1500;+/** A paste shortcut waits at most this long for the local clipboard to reach the computer. */+const CLIPBOARD_PASTE_WAIT_MS = 1000;+/** A copy shortcut pulls the computer's clipboard after it has had time to change. */+const CLIPBOARD_COPY_DELAY_MS = 200;function connectionBudget(caps: RemoteDesktopCapabilities | null): number {// Match Mobile: system consent has its own two-minute host deadline.@@ -135,6 +139,11 @@ export class DesktopViewerController {private clipboardQueue: Promise<void> = Promise.resolve();private clipboardQueued = 0;private clipboardRevision = 0;+ /** The sync pass a paste shortcut is waiting on; later pastes share it. */+ private pasteSync: Promise<void> | null = null;+ /** Serial of the latest paste wait: only it may open the picture's gate. */+ private pasteWait = 0;+ private copyTimer: ReturnType<typeof setTimeout> | null = null;private pendingSettings = false;private offers = new Set<import('@cindy/device-link').RemoteDesktopLease>();private mediaChanging = false;@@ -362,6 +371,10 @@ export class DesktopViewerController {this.epoch++;if (this.settingsTimer) clearTimeout(this.settingsTimer);this.settingsTimer = null;+ // A paste waiting on the old session must not open the next session's gate.+ this.pasteSync = null;+ if (this.copyTimer) clearTimeout(this.copyTimer);+ this.copyTimer = null;this.pendingSettings = false;this.mediaChanging = false;this.offers.clear();@@ -429,6 +442,8 @@ export class DesktopViewerController {trickleIce: caps.trickleIce === true,audio: caps.systemAudio && this.state.settings.audio,macKeyboard: typeof window !== 'undefined' && window.electronAPI?.platform === 'darwin',+ // Only the controlled computer's own copy/paste modifier is a clipboard shortcut.+ clipboardModifier: caps.platform === 'darwin' ? 'meta' : 'control',});this.runtime.receive({ type: 'mode', mode: 'pointer' });if (!caps.canControl) throw new Error('DESKTOP_INPUT_UNSUPPORTED');@@ -487,6 +502,14 @@ export class DesktopViewerController {this.state.ready && !this.state.controlPending && this.session.lease?.controlling === true;if (controlling === this.state.controlling) return;this.clipboardRevision++;+ if (!controlling) {+ // Main retires the sync of a lost control generation (a display switch+ // with auto-control drops and regains control without a reconnect); a+ // paste after control returns must start its own pass, not wait on it.+ this.pasteSync = null;+ if (this.copyTimer) clearTimeout(this.copyTimer);+ this.copyTimer = null;+ }this.publish({ controlling });this.runtime.receive({ type: 'control', enabled: controlling });if (controlling) void this.applyRememberedResolution();@@ -1111,6 +1134,10 @@ export class DesktopViewerController {case 'inputOverflow':this.fail(new Error('DESKTOP_INPUT_UNAVAILABLE'));break;+ case 'clipboardIntent':+ if (message.action === 'paste' || message.action === 'copy')+ this.clipboardIntent(message.action);+ break;case 'input':if (!Number.isSafeInteger(message.sequence) ||@@ -1139,6 +1166,60 @@ export class DesktopViewerController {break;}}+ /**+ * A clipboard shortcut typed into the picture. Paste holds the keys (the+ * picture gates its queue) until the local clipboard has been pushed, at+ * most CLIPBOARD_PASTE_WAIT_MS; copy pulls the computer's clipboard shortly+ * after. Neither waits for the regular poll. One push serves every paste+ * made while it is in flight, and only the latest paste's wait opens the+ * gate (the picture re-arms it per paste): an earlier paste's deadline must+ * not open it, and a second request would only get the pending pass's+ * snapshot from Main at once.+ */+ private clipboardIntent(action: 'copy' | 'paste'): void {+ const wanted =+ this.state.preferences.clipboardSync && this.state.controlling && !!this.api.clipboardSync;+ if (action === 'copy') {+ if (!wanted) return;+ if (this.copyTimer) clearTimeout(this.copyTimer);+ this.copyTimer = setTimeout(() => {+ this.copyTimer = null;+ void this.syncClipboard();+ }, CLIPBOARD_COPY_DELAY_MS);+ return;+ }+ const epoch = this.epoch,+ wait = ++this.pasteWait;+ const release = () => {+ // The picture resets its gate itself when a session ends or changes.+ if (!this.disposed && epoch === this.epoch && wait === this.pasteWait)+ this.runtime.receive({ type: 'inputGate' });+ };+ if (!wanted) {+ release();+ return;+ }+ if (!this.pasteSync) {+ const pending: Promise<void> = this.syncClipboard().finally(() => {+ if (this.pasteSync === pending) this.pasteSync = null;+ });+ this.pasteSync = pending;+ }+ void Promise.race([+ this.pasteSync,+ new Promise<void>((resolve) => setTimeout(resolve, CLIPBOARD_PASTE_WAIT_MS)),+ ]).then(release, release);+ }+ private async syncClipboard(): Promise<void> {+ if (!this.state.ready || this.state.closing || !this.api.clipboardSync) return;+ const epoch = this.epoch;+ try {+ const safety = await this.api.clipboardSync(this.scope.generation);+ if (epoch === this.epoch && !this.disposed) this.publish({ safety });+ } catch {+ /* Connection state owns disconnected/retired generations. */+ }+ }private present(status: string): void {if (status === 'live') this.mediaChanging = false;this.retryDelay = 1000;@@ -1158,6 +1239,8 @@ export class DesktopViewerController {this.disposed = true;if (this.hiddenTimer) clearTimeout(this.hiddenTimer);this.hiddenTimer = null;+ if (this.copyTimer) clearTimeout(this.copyTimer);+ this.copyTimer = null;if (this.connectionTimer !== null) clearTimeout(this.connectionTimer);this.connectionTimer = null;for (const t of this.timers) clearInterval(t);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 929e65d79e..c6d8cc114f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -773,6 +773,7 @@"clipboardSyncFailed": "Sync temporarily failed. Retrying automatically; your setting stays on.","clipboardSyncSkipped": "This content could not be synced and was skipped. Check paste access, or copy text or an image to try again.","clipboardSyncPermission": "Sync is paused. Allow paste access, then retry. Your setting stays on.",+ "clipboardSyncWaiting": "The remote computer’s clipboard is not available right now (it may be locked). Sync resumes automatically.","lockingOnExit": "Locking computer…","lockOnExit": "Lock Computer on Exit","lockOnExitHint": "Locks when you leave remote desktop. Reconnecting or switching apps does not lock the computer.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 5b68112feb..88f96f0eaf 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -765,6 +765,7 @@"clipboardSyncFailed": "同期に一時的に失敗しました。自動で再試行します。設定はオンのままです。","clipboardSyncSkipped": "この内容は同期できないためスキップしました。ペーストの許可を確認するか、テキストや画像をコピーして再試行してください。","clipboardSyncPermission": "同期を一時停止しました。ペーストを許可してから再試行してください。設定はオンのままです。",+ "clipboardSyncWaiting": "リモートのパソコンのクリップボードに現在アクセスできません(ロック中の可能性があります)。自動で同期を再開します。","lockingOnExit": "コンピューターをロック中…","lockOnExit": "終了時にパソコンをロック","lockOnExitHint": "リモートデスクトップを終了するとロックします。再接続やアプリ切り替えではロックしません。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 5e1e75aaf6..f0150aac4c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -765,6 +765,7 @@"clipboardSyncFailed": "동기화가 일시적으로 실패했습니다. 자동으로 재시도하며 설정은 켜진 상태로 유지됩니다.","clipboardSyncSkipped": "현재 콘텐츠를 동기화할 수 없어 건너뛰었습니다. 붙여넣기 권한을 확인하거나 텍스트 또는 이미지를 복사한 후 다시 시도해 주세요.","clipboardSyncPermission": "동기화가 일시 중지되었습니다. 붙여넣기를 허용한 후 다시 시도해 주세요. 설정은 켜진 상태로 유지됩니다.",+ "clipboardSyncWaiting": "원격 컴퓨터의 클립보드에 지금은 접근할 수 없습니다(잠겨 있을 수 있음). 자동으로 동기화를 재개합니다.","lockingOnExit": "컴퓨터를 잠그는 중…","lockOnExit": "종료 시 컴퓨터 잠금","lockOnExitHint": "원격 데스크톱을 종료하면 잠급니다. 재연결이나 앱 전환 시에는 잠그지 않습니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 01af98dab4..bcca7d27e2 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -765,6 +765,7 @@"clipboardSyncFailed": "同步暂时失败,正在自动重试。开关保持开启。","clipboardSyncSkipped": "当前内容无法同步,已跳过。请检查粘贴权限,或复制文字、图片后重试。","clipboardSyncPermission": "同步已暂停,请允许粘贴权限后重试。开关保持开启。",+ "clipboardSyncWaiting": "远程电脑的剪贴板暂时无法访问(可能已锁屏),解锁后会自动继续同步。","lockingOnExit": "正在锁定电脑…","lockOnExit": "退出后锁定电脑","lockOnExitHint": "退出远程桌面时锁屏。重连或切换 App 不会触发。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex a74a4f0351..ddf5a7663b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -765,6 +765,7 @@"clipboardSyncFailed": "同步暫時失敗,正在自動重試。開關保持開啟。","clipboardSyncSkipped": "目前內容無法同步,已略過。請檢查貼上權限,或複製文字、圖片後重試。","clipboardSyncPermission": "同步已暫停,請允許貼上權限後重試。開關保持開啟。",+ "clipboardSyncWaiting": "遠端電腦的剪貼簿暫時無法存取(可能已鎖定螢幕),解鎖後會自動繼續同步。","lockingOnExit": "正在鎖定電腦…","lockOnExit": "退出後鎖定電腦","lockOnExitHint": "離開遠端桌面時鎖定螢幕。重新連線或切換 App 不會觸發。",diff --git a/apps/desktop/src/shared/remoteDesktopViewer.ts b/apps/desktop/src/shared/remoteDesktopViewer.tsindex 196740ef94..a0971c6112 100644--- a/apps/desktop/src/shared/remoteDesktopViewer.ts+++ b/apps/desktop/src/shared/remoteDesktopViewer.ts@@ -18,6 +18,7 @@ export const REMOTE_VIEWER = {INPUT_FOCUS: 'remote-desktop-viewer:input-focus',PREFERENCES: 'remote-desktop-viewer:preferences',SAFETY: 'remote-desktop-viewer:safety',+ CLIPBOARD_SYNC: 'remote-desktop-viewer:clipboard-sync',CREDENTIAL: 'remote-desktop-viewer:credential',RESOLUTION: 'remote-desktop-viewer:resolution',CHANNEL_REQUEST: 'remote-desktop-viewer:channel-request',@@ -132,6 +133,8 @@ export interface RemoteDesktopViewerApi {patch?: Partial<RemoteViewerPreferences>,): Promise<RemoteViewerPreferences>;safety?(generation: number, retry?: boolean): Promise<RemoteViewerSafety>;+ /** One clipboard sync pass now (copy/paste in the picture) instead of at the next poll. */+ clipboardSync?(generation: number): Promise<RemoteViewerSafety>;/** Main routes channel-eligible requests through the window's media data channel. */onChannelRequest?(listener: (request: RemoteViewerChannelRequest) => void): () => void;channelReply?(generation: number, id: string, outcome: RemoteViewerChannelOutcome): Promise<void>;diff --git a/apps/mobile/src/remote-desktop/clipboardSync.test.ts b/apps/mobile/src/remote-desktop/clipboardSync.test.tsindex 6a4078d6e4..02a2a71438 100644--- a/apps/mobile/src/remote-desktop/clipboardSync.test.ts+++ b/apps/mobile/src/remote-desktop/clipboardSync.test.ts@@ -424,11 +424,41 @@ it("retains a successfully read new local digest when the remote read is unsuppothrow new Error("CLIPBOARD_UNSUPPORTED");return original(message);});- await engine.tick();+ // Both changed: both copies are kept, and the user is told rather than the+ // readable copy silently never arriving.+ await expect(engine.tick()).rejects.toThrow("CLIPBOARD_CONFLICT");expect(baseline.localDigest).toBe(clipboardDigest(JSON.stringify({ text: "local-2" })),);expect(baseline.remoteDigest).toBeUndefined();+ expect(h.write).not.toHaveBeenCalled();+});++it("an unreadable local item next to a new computer copy is a conflict; the next copy on either side syncs", async () => {+ const h = harness();+ const trace = vi.fn();+ const engine = new ClipboardSync({ ...h.deps, trace });+ await engine.tick();+ // Only the local item is unreadable (several files): skipped quietly.+ vi.mocked(h.deps.readLocal).mockRejectedValueOnce(+ new Error("CLIPBOARD_UNSUPPORTED"),+ );+ h.local("2");+ await expect(engine.tick()).resolves.toBeUndefined();+ expect(trace).toHaveBeenLastCalledWith("content-skipped");+ // Unreadable local item and a new computer copy in the same interval.+ vi.mocked(h.deps.readLocal).mockRejectedValueOnce(+ new Error("CLIPBOARD_UNSUPPORTED"),+ );+ h.local("3");+ h.remote("2");+ await expect(engine.tick()).rejects.toThrow("CLIPBOARD_CONFLICT");+ expect(h.write).not.toHaveBeenCalled();+ await expect(engine.tick()).resolves.toBeUndefined();+ // Copying again on the computer brings that copy over.+ h.remote("4");+ await engine.tick();+ expect(h.write).toHaveBeenCalledTimes(1);});it.each(["local", "remote"] as const)(diff --git a/docs/remote-desktop.md b/docs/remote-desktop.mdindex 858da03e3a..d6c96b7c54 100644--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@ -43,16 +43,46 @@ Desktop uses the local system cursor inside the remote picture, with standardshape hints from the host. Pointer size is independent of remote resolution and zoom.With the picture focused, Cmd/Ctrl+C/V are ordinary keys sent to the remotecomputer, so copy and paste act on its own clipboard exactly as they would locally;-they never move content between computers. Cross-computer transfer is explicit: the-settings panel's copy and paste actions copy selected remote content to the local-clipboard or paste local content remotely. Transfers use the existing authorized+the keys themselves never move content between computers. Content crosses+computers only through two explicit features: the settings panel's copy and paste+actions, which copy selected remote content to the local clipboard or paste local+content remotely, and the optional clipboard synchronization described below,+which the shortcuts merely trigger early when it is enabled. Transfers use the existing authorizedMain bridge, are ordered and user-triggered, and report the specific failure(view only, empty, unsupported, too large, copy/paste failed) without reconnecting;Main logs only the action and error code. Capable hosts support text, HTML, RTF,URLs and PNG; older hosts retain text-only behavior. Arbitrary files and cut arenot bridged. Optional clipboard synchronization reuses Mobile's version, conflict-and bounded-transfer logic, only while this viewer is focused and holds confirmed-control. Contents stay in Main/native code and do not cross the viewer Renderer bridge.+and bounded-transfer logic while this viewer holds confirmed control. The+computer's side stays enabled for the whole control session; focus only decides+when this window reads its own clipboard: while focused, plus 1 s after it leaves+the foreground (one pass at once, and a copy chord's delayed pull landing in that+second) so a copy made on the computer is already here. This deadline only gates+the start of a pass: admitted work finishes across blur and deadline expiry,+including a delayed copy waiting behind the blur-triggered pass. There is no+separate blur cancellation generation; control/session changes still invalidate+in-flight work, and the native counter helper retires on its existing idle timeout.+Regaining focus runs a+pass at once; so does the controlled+computer's own copy/cut chord (Cmd on macOS, Ctrl elsewhere; the other modifier+is an ordinary key) about 200 ms after the key, and its paste chord holds the+queued keys (at most 1 s) until the local clipboard has been pushed (pastes made+while that push is still in flight wait on it rather than starting another, and+only the latest paste's wait, at most 1 s, opens the gate); losing focus drops a+held paste instead of sending it late; the held keys do not age against the+2 s input-freshness budget while the gate is closed. Only one sync pass runs at+a time, and a wakeup that finds one in flight shares its result rather than a+stale status. The 1.5 s poll remains only as a fallback. A locked or busy computer and a clipboard that changed mid-read retry+at a fixed 1.5 s without growing the backoff (the locked case shows its own+notice); unexplained failures back off to at most 5 s and reset on focus or a+shortcut. A multi-item local clipboard (several files) is skipped rather than+failing the pass; if the computer copied something in the same interval, that is+reported as a conflict like any simultaneous change, and copying again on either+side syncs, even when that copy repeats identical readable content. The desktop+adapter retains conflict counters but clears their content digests: idle polls+preserve both clipboards, and the next copy chooses the source. A successful+transfer restores ordinary content deduplication. Contents stay in Main/native code and do not cross the viewer+Renderer bridge.The settings panel also supports host privacy screen, host mute, lock-on-exit andmacOS-to-macOS automatic unlock. Non-secret preferences are scoped to the localdiff --git a/packages/device-link/src/clipboardSync.ts b/packages/device-link/src/clipboardSync.tsindex d751974d86..cc2e2692df 100644--- a/packages/device-link/src/clipboardSync.ts+++ b/packages/device-link/src/clipboardSync.ts@@ -353,6 +353,8 @@ export class ClipboardSync {skippableContent(error)) {this.check();+ const bothChanged =+ local !== this.baseline.local && remote !== this.baseline.remote;Object.assign(this.baseline, {local,remote,@@ -368,6 +370,10 @@ export class ClipboardSync {: readRemoteDigest,});this.deps.trace?.("content-skipped");+ // Both peers changed and one of them is unreadable: as with any+ // simultaneous change, both copies are kept, but the user is told so+ // instead of the readable copy silently never arriving.+ if (bothChanged) throw new Error("CLIPBOARD_CONFLICT");return;}throw error;diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.jsindex 92988afc35..0c66cee627 100644--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.js+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js@@ -143,6 +143,10 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {let pending = [],pendingSince = 0,sending = false,+ // Deadline while a paste shortcut holds the queue (desktop only; 0 = open),+ // and which modifier is copy/paste on the controlled computer.+ inputGateUntil = 0,+ clipboardModifier = "control",cx = 0.5,cy = 0.5,drag = false,@@ -861,6 +865,14 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {}function flush() {if (!pending.length) return;+ // A paste shortcut waits for the controller to push the local clipboard+ // first. That hold is deliberate (and each further paste re-arms it), so+ // the batch's freshness clock only starts once the gate opens.+ if (inputGateUntil) {+ if (performance.now() < inputGateUntil) return;+ inputGateUntil = 0;+ pendingSince = performance.now();+ }// Input is an intent about the picture the user saw, not durable work.// Never replay old clicks/typing after a stalled ACK or data channel drains.if (performance.now() - pendingSince >= 2000) {@@ -913,6 +925,12 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {clearTimeout(hold);if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);gestureFrame = null;+ // A paste still waiting for its clipboard push is abandoned, never sent+ // late; the release itself must reach the computer at once.+ if (inputGateUntil) {+ inputGateUntil = 0;+ pending = [];+ }if (control) {queue({ kind: "release" });flush();@@ -1518,6 +1536,19 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {hardwareKeys.clear();commandKeys.clear();}+ // Desktop only. Cmd/Ctrl+V holds the queue until the controller has pushed+ // the local clipboard (or `inputGate` / the deadline releases it); Cmd/Ctrl+C+ // and +X ask it to pull the computer's new copy soon after. Both are intents:+ // the keys themselves still reach the computer unchanged.+ function clipboardShortcut(e, code) {+ const chord = clipboardModifier === "meta" ? e.metaKey : e.ctrlKey;+ if (!config.desktop || e.repeat || e.altKey || !chord) return;+ if (code === "KeyV") {+ inputGateUntil = performance.now() + 1200;+ post({ type: "clipboardIntent", action: "paste" });+ } else if (code === "KeyC" || code === "KeyX")+ post({ type: "clipboardIntent", action: "copy" });+ }listen(document, "keydown", (e) => {if (config.desktop) {if (e.ctrlKey && e.altKey && e.code === "Escape") {@@ -1551,7 +1582,9 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {return;if (control && validKeys.has(normalizedKey(e.code))) {e.preventDefault();- pressKey(normalizedKey(e.code));+ const code = normalizedKey(e.code);+ clipboardShortcut(e, code);+ pressKey(code);}});listen(document, "keyup", (e) => {@@ -2146,6 +2179,11 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {case "releaseInput":release();break;+ case "inputGate":+ if (inputGateUntil) pendingSince = performance.now();+ inputGateUntil = 0;+ flush();+ break;case "theme":if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {document.body.style.background = config.nativeMedia@@ -2363,6 +2401,9 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {seq = 0;epoch = message.epoch;macKeyboard = config.desktop && message.macKeyboard === true;+ clipboardModifier =+ message.clipboardModifier === "meta" ? "meta" : "control";+ inputGateUntil = 0;dw = message.width;dh = message.height;fillHeight = message.fillHeight === true;@@ -2428,6 +2469,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {// existing sequence fence so a late old ACK cannot unlock a new batch.seq++;sending = false;+ inputGateUntil = 0;control = message.enabled;if (!control) showKeyboard(false);pending = [];diff --git a/packages/maker-shared/src/remote-desktop/viewerSource.ts b/packages/maker-shared/src/remote-desktop/viewerSource.tsindex 0a8488468f..bc541383a6 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 macKeyboard = false,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n 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 its full reach\n // by 1.5x, so even a light zoom can pull edge content clear of the overlaid\n // chrome. Never count the unused space of a fitting axis.\n // Each axis reaches at most 240 points or 40% of its own viewport.\n const ramp = Math.min(0.5, r.maxZoom - 1);\n const grown = ramp > 0 ? clamp((zoom - 1) / ramp) : 0;\n const axis = (viewport, content) => {\n const clearance = grown * Math.min(240, viewport * 0.4);\n return content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n };\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 // 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 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 let wheelRestX = 0,\n wheelRestY = 0;\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) {\n wheelRestX = wheelRestY = 0;\n return;\n }\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n // Hosts inject whole pixels; carry fractions so slow trackpad and\n // scaled-display deltas still scroll.\n const sx = wheelRestX + e.deltaX * factor,\n sy = wheelRestY + e.deltaY * factor,\n wx = Math.trunc(sx) || 0,\n wy = Math.trunc(sy) || 0;\n wheelRestX = sx - wx;\n wheelRestY = sy - wy;\n if (!wx && !wy) return;\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 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 // Remote key state: a key is held from its first keydown until its keyup.\n // macOS sends no keyup for keys first pressed while Command is held (Cmd+C);\n // only those are released together with Command. Membership is decided once,\n // on the not-held -> held transition, so auto-repeat never reclassifies a key.\n const hardwareKeys = new Set();\n const commandKeys = new Set();\n const isModifier = (code) => /^(Shift|Control|Alt|Meta)Left$/.test(code);\n function pressKey(code) {\n if (!hardwareKeys.has(code)) {\n if (macKeyboard && hardwareKeys.has(\"MetaLeft\") && !isModifier(code))\n commandKeys.add(code);\n hardwareKeys.add(code);\n }\n queue({ kind: \"key\", code, down: true });\n }\n function releaseKey(code, send) {\n commandKeys.delete(code);\n if (!hardwareKeys.delete(code)) return false;\n if (code === \"MetaLeft\") {\n for (const held of commandKeys)\n if (hardwareKeys.delete(held) && send)\n queue({ kind: \"key\", code: held, down: false });\n commandKeys.clear();\n }\n if (send) queue({ kind: \"key\", code, down: false });\n return send;\n }\n function forgetKeys() {\n hardwareKeys.clear();\n commandKeys.clear();\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 }\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 pressKey(normalizedKey(e.code));\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (releaseKey(code, control && validKeys.has(code))) e.preventDefault();\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n forgetKeys();\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 // Clear instead of forcing visible: the stylesheet hides an image with\n // no frame yet, otherwise the browser paints a broken-image box.\n image.style.visibility = \"\";\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 macKeyboard = config.desktop && message.macKeyboard === true;\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\" : \"\";\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 // A local view-only switch keeps host control, so its release must\n // still reach the host even if a batch was waiting for its ACK.\n const releaseHost =\n control && message.enabled !== true && message.release === true;\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 if (releaseHost) {\n pending = [{ kind: \"release\" }];\n pendingSince = performance.now();\n flush();\n }\n updateMouseButtons();\n render();\n break;\n }\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 = \"\";\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 macKeyboard = false,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n pendingSince = 0,\n sending = false,\n // Deadline while a paste shortcut holds the queue (desktop only; 0 = open),\n // and which modifier is copy/paste on the controlled computer.\n inputGateUntil = 0,\n clipboardModifier = \"control\",\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 its full reach\n // by 1.5x, so even a light zoom can pull edge content clear of the overlaid\n // chrome. Never count the unused space of a fitting axis.\n // Each axis reaches at most 240 points or 40% of its own viewport.\n const ramp = Math.min(0.5, r.maxZoom - 1);\n const grown = ramp > 0 ? clamp((zoom - 1) / ramp) : 0;\n const axis = (viewport, content) => {\n const clearance = grown * Math.min(240, viewport * 0.4);\n return content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n };\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 // 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 // A paste shortcut waits for the controller to push the local clipboard\n // first. That hold is deliberate (and each further paste re-arms it), so\n // the batch's freshness clock only starts once the gate opens.\n if (inputGateUntil) {\n if (performance.now() < inputGateUntil) return;\n inputGateUntil = 0;\n pendingSince = performance.now();\n }\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 clearTimeout(hold);\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n // A paste still waiting for its clipboard push is abandoned, never sent\n // late; the release itself must reach the computer at once.\n if (inputGateUntil) {\n inputGateUntil = 0;\n pending = [];\n }\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 let wheelRestX = 0,\n wheelRestY = 0;\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) {\n wheelRestX = wheelRestY = 0;\n return;\n }\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n // Hosts inject whole pixels; carry fractions so slow trackpad and\n // scaled-display deltas still scroll.\n const sx = wheelRestX + e.deltaX * factor,\n sy = wheelRestY + e.deltaY * factor,\n wx = Math.trunc(sx) || 0,\n wy = Math.trunc(sy) || 0;\n wheelRestX = sx - wx;\n wheelRestY = sy - wy;\n if (!wx && !wy) return;\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 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 // Remote key state: a key is held from its first keydown until its keyup.\n // macOS sends no keyup for keys first pressed while Command is held (Cmd+C);\n // only those are released together with Command. Membership is decided once,\n // on the not-held -> held transition, so auto-repeat never reclassifies a key.\n const hardwareKeys = new Set();\n const commandKeys = new Set();\n const isModifier = (code) => /^(Shift|Control|Alt|Meta)Left$/.test(code);\n function pressKey(code) {\n if (!hardwareKeys.has(code)) {\n if (macKeyboard && hardwareKeys.has(\"MetaLeft\") && !isModifier(code))\n commandKeys.add(code);\n hardwareKeys.add(code);\n }\n queue({ kind: \"key\", code, down: true });\n }\n function releaseKey(code, send) {\n commandKeys.delete(code);\n if (!hardwareKeys.delete(code)) return false;\n if (code === \"MetaLeft\") {\n for (const held of commandKeys)\n if (hardwareKeys.delete(held) && send)\n queue({ kind: \"key\", code: held, down: false });\n commandKeys.clear();\n }\n if (send) queue({ kind: \"key\", code, down: false });\n return send;\n }\n function forgetKeys() {\n hardwareKeys.clear();\n commandKeys.clear();\n }\n // Desktop only. Cmd/Ctrl+V holds the queue until the controller has pushed\n // the local clipboard (or `inputGate` / the deadline releases it); Cmd/Ctrl+C\n // and +X ask it to pull the computer's new copy soon after. Both are intents:\n // the keys themselves still reach the computer unchanged.\n function clipboardShortcut(e, code) {\n const chord = clipboardModifier === \"meta\" ? e.metaKey : e.ctrlKey;\n if (!config.desktop || e.repeat || e.altKey || !chord) return;\n if (code === \"KeyV\") {\n inputGateUntil = performance.now() + 1200;\n post({ type: \"clipboardIntent\", action: \"paste\" });\n } else if (code === \"KeyC\" || code === \"KeyX\")\n post({ type: \"clipboardIntent\", action: \"copy\" });\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 }\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 const code = normalizedKey(e.code);\n clipboardShortcut(e, code);\n pressKey(code);\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (releaseKey(code, control && validKeys.has(code))) e.preventDefault();\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n forgetKeys();\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 \"inputGate\":\n if (inputGateUntil) pendingSince = performance.now();\n inputGateUntil = 0;\n flush();\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 // Clear instead of forcing visible: the stylesheet hides an image with\n // no frame yet, otherwise the browser paints a broken-image box.\n image.style.visibility = \"\";\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 macKeyboard = config.desktop && message.macKeyboard === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n inputGateUntil = 0;\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\" : \"\";\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 // A local view-only switch keeps host control, so its release must\n // still reach the host even if a batch was waiting for its ACK.\n const releaseHost =\n control && message.enabled !== true && message.release === true;\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 inputGateUntil = 0;\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n if (releaseHost) {\n pending = [{ kind: \"release\" }];\n pendingSince = performance.now();\n flush();\n }\n updateMouseButtons();\n render();\n break;\n }\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 = \"\";\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";