Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(remote-desktop): 优化手机全屏交互并恢复临时分辨率 (#4543)
Dash03b05eb6bce3
diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.tsindex cb20d85bc2..62353d710d 100644--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts@@ -140,6 +140,28 @@ function snapshotProcessListeners(events: ProcessEventName[]) {}describe('runQuitDisposers', () => {+ it('keeps the bootstrap quit budget open for an in-flight mode write and restoration', async () => {+ vi.useFakeTimers();+ const { onQuit, runQuitDisposers, SHUTDOWN_HARD_KILL_GRACE_SECONDS } = await freshLifecycle();+ const source = readFileSync(join(__dirname, '../bootstrap-electron.ts'), 'utf8');+ const budget = Number(source.match(/installQuitHandler\((\d+)\);/)?.[1]);+ expect(budget).toBeLessThan(SHUTDOWN_HARD_KILL_GRACE_SECONDS * 1000);+ const events: string[] = [];+ onQuit('remote-desktop-restore', async () => {+ for (const step of ['in-flight-write', 'restore-mode', 'display-projection']) {+ await new Promise((resolve) => setTimeout(resolve, 5000));+ events.push(step);+ }+ }, 'async');+ onQuit('after-restoration', () => { events.push('post-async'); }, 'post-async');+ const quitting = runQuitDisposers(budget);+ await vi.advanceTimersByTimeAsync(14_999);+ expect(events).toEqual(['in-flight-write', 'restore-mode']);+ await vi.advanceTimersByTimeAsync(1);+ await quitting;+ expect(events).toEqual(['in-flight-write', 'restore-mode', 'display-projection', 'post-async']);+ });+beforeEach(() => {vi.useRealTimers();vi.clearAllMocks();diff --git a/apps/desktop/src/main/__tests__/piSubagentQuitEscalation.test.ts b/apps/desktop/src/main/__tests__/piSubagentQuitEscalation.test.tsindex 239e7ac991..8796ea9c46 100644--- a/apps/desktop/src/main/__tests__/piSubagentQuitEscalation.test.ts+++ b/apps/desktop/src/main/__tests__/piSubagentQuitEscalation.test.ts@@ -212,7 +212,9 @@ describe('PI Subagent quit sweep', () => {// The kill confirmation is bounded but not free (~0.8s per surviving// runner), so the stop wait cannot also use the whole phase.expect(quitHookSource()).toMatch(/stopAllPiSubagentRunsForExit\(agentHome, 2_500,/);- expect(source).toContain('installQuitHandler(6000);');+ const budget = Number(source.match(/installQuitHandler\((\d+)\);/)?.[1]);+ expect(budget).toBeGreaterThan(2_500 + 800);+ expect(budget).toBeLessThan(20_000);});it('reports survivors as an error rather than an acknowledged stop', () => {diff --git a/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts b/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.tsindex 64abfde606..9c5af4fde0 100644--- a/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts+++ b/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts@@ -44,7 +44,7 @@ describe('update force-quit iOS Simulator cleanup', () => {const hostDisposeIndex = bootstrapSource.indexOf("onQuit('ios-simulator-host', disposeIOSSimulatorHost, 'async');",);- const quitHandlerIndex = bootstrapSource.indexOf('installQuitHandler(6000);');+ const quitHandlerIndex = bootstrapSource.search(/installQuitHandler\(\d+\);/);expect(abortIndex).toBeGreaterThanOrEqual(0);expect(hostDisposeIndex).toBeGreaterThan(abortIndex);diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex b1504126d2..930a0f2eed 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -9257,7 +9257,7 @@ app.on('ready', async () => {// - process.on('uncaughtException')—— main 进程未捕获异常// - app.on('render-process-gone') —— renderer 崩 (main 还活)//-// 三个阶段串成 sync → async(并发+6s 超时, 见下方 installQuitHandler) → post-async,+// 三个阶段串成 sync → async(并发+16s 超时, 见下方 installQuitHandler) → post-async,// 然后 app.exit(<code>)。// 散落的 fire-and-forget 已经收掉, 进程不会在 disposer 跑完之前死。// 真硬崩 (segfault / kill -9) JS 层无能为力, 子进程靠 stdin EOF 自死。@@ -9648,7 +9648,10 @@ onQuit('ios-simulator-ownership-registry', flushIOSSimulatorOwnershipRegistry, 'onQuit('db-client', () => lifecycleDbClientManager.dispose('quit'), 'post-async');onQuit('local-db-close', () => localDbCloseDb(), 'post-async');-installQuitHandler(6000);+// A display restore may join an in-flight native mode write (5s), restore the+// original mode (5s), then await Electron geometry (5s). Keep a margin before+// the existing 20s hard-exit watchdog; completed disposers never wait this long.+installQuitHandler(16000);app.on('window-all-closed', () => {if (process.platform !== 'darwin') {diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.tsindex 75c24b6b3a..8c87ad8b10 100644--- a/apps/desktop/src/main/lifecycle.ts+++ b/apps/desktop/src/main/lifecycle.ts@@ -189,7 +189,7 @@ export async function runQuitDisposers(timeoutMs = 2000): Promise<void> {}/**- * 外部硬杀 watchdog 的宽限期 (秒)。disposer 预算 6s 的 3 倍余量; 比更新脚本的+ * 外部硬杀 watchdog 的宽限期 (秒)。大于 bootstrap 的 16s disposer 预算; 比更新脚本的* 120s (updateScriptMacOS) 激进得多 —— 这是常规退出路径, 用户在旁边等。*/export const SHUTDOWN_HARD_KILL_GRACE_SECONDS = 20;diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.tsindex 5a85a2516f..67e3009cfa 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts@@ -3,6 +3,8 @@ import { DESKTOP_LOCAL } from '../../../shared/remoteDesktop';const h = vi.hoisted(() => ({handlers: new Map<string, any>(),+ screenHandlers: new Map<string, any>(),+ geometryMatches: vi.fn(() => true),windows: [] as any[],deps: null as any,permissionDeps: null as any,@@ -12,6 +14,9 @@ const h = vi.hoisted(() => ({owner: null as any,dispose: vi.fn(),stop: vi.fn(),+ stopAndRestore: vi.fn(async () => {}),+ waitForGeometry: vi.fn(async (..._args: any[]) => {}),+ quit: new Map<string, { fn: () => unknown; phase: string }>(),releaseControl: vi.fn(),inputFailure: null as null | (() => void),nativeStop: vi.fn(),@@ -23,13 +28,24 @@ const h = vi.hoisted(() => ({{ urls: ['turn:relay.example.test:3478'], username: 'temporary', credential: 'test-only' },]),}));+vi.mock('../../lifecycle', () => ({+ onQuit: (name: string, fn: () => unknown, phase = 'sync') => h.quit.set(name, { fn, phase }),+}));vi.mock('../iceConfig', () => ({ loadDesktopIceServers: h.iceConfig }));+vi.mock('../viewerDisplay', () => ({+ viewerDisplaySupported: vi.fn(async () => false),+ createViewerDisplay: vi.fn(),+ waitForDisplayRestore: h.waitForGeometry,+}));vi.mock('electron', () => ({app: { on: vi.fn() },powerMonitor: { on: vi.fn() },shell: {},nativeImage: {},- screen: { on: vi.fn(), getAllDisplays: () => [{ id: 1 }] },+ screen: {+ on: (name: string, handler: any) => h.screenHandlers.set(name, handler),+ getAllDisplays: () => [{ id: 1 }],+ },systemPreferences: { getMediaAccessStatus: () => 'granted' },desktopCapturer: {getSources: () => h.source ?? Promise.resolve([{ id: 'screen:1', display_id: '1' }]),@@ -86,6 +102,9 @@ vi.mock('../controller', () => ({h.deps = deps;}state = null;+ displayId = '1';+ changingDisplay = false;+ displayGeometryMatches = h.geometryMatches;hasLease(value: string) {return value === h.lease;}@@ -96,6 +115,7 @@ vi.mock('../controller', () => ({stopByUser() {this.stop();}+ stopAndRestore = h.stopAndRestore;releaseControl() {h.releaseControl();}@@ -125,7 +145,9 @@ vi.mock('../inputHost', () => ({}));vi.mock('../permissions', () => ({RemoteDesktopPermissionsService: class {- constructor(deps: any) { h.permissionDeps = deps; }+ constructor(deps: any) {+ h.permissionDeps = deps;+ }dismiss() {}},}));@@ -162,6 +184,8 @@ const offer = () =>beforeEach(() => {vi.useFakeTimers();h.handlers.clear();+ h.screenHandlers.clear();+ h.geometryMatches.mockReset().mockReturnValue(true);h.windows.length = 0;h.source = null;h.lease = 'lease';@@ -185,14 +209,109 @@ afterEach(() => {vi.unstubAllGlobals();});+it.each(['resolution', 'restoreResolution'])(+ 'waits for native completion and projection on %s',+ async (method) => {+ const { setDesktopDisplayMode } = await import('../inputHost');+ let nativeDone!: () => void;+ let projected!: () => void;+ vi.mocked(setDesktopDisplayMode).mockImplementationOnce(async () => {+ await new Promise<void>((resolve) => {+ nativeDone = resolve;+ });+ });+ h.waitForGeometry.mockImplementationOnce(async () => {+ await new Promise<void>((resolve) => {+ projected = resolve;+ });+ });+ const beforeChange = vi.fn();+ const settled = vi.fn();+ const expected = { width: 1920, height: 1080 };+ const pending = h.deps[method]('1', '1', beforeChange, expected).then(settled);+ expect(projected).toBeUndefined();+ nativeDone();+ for (let i = 0; i < 5; i++) await Promise.resolve();+ if (method === 'resolution') {+ expect(h.waitForGeometry).toHaveBeenLastCalledWith(+ '1',+ expected,+ beforeChange,+ expect.any(Function),+ );+ const present = h.waitForGeometry.mock.lastCall![3];+ expect(present([])).toBe(false);+ expect(present([{ id: 1 }])).toBe(true);+ } else expect(h.waitForGeometry).toHaveBeenLastCalledWith('1', expected, beforeChange);+ expect(settled).not.toHaveBeenCalled();+ projected();+ await pending;+ expect(settled).toHaveBeenCalledOnce();+ },+);++it.each([+ ['scaleFactor'],+ ['bounds', 'scaleFactor'],+ ['bounds', 'workArea', 'scaleFactor'],+])('keeps managed geometry after late display metrics %j', (...metrics) => {+ h.screenHandlers.get('display-metrics-changed')(+ {},+ { id: 1, size: { width: 1920, height: 1080 } },+ metrics,+ );+ expect(h.geometryMatches).toHaveBeenCalledWith('1', 1920, 1080);+ expect(h.stop).not.toHaveBeenCalled();+});++it.each([+ [true, ['rotation']],+ [true, ['scaleFactor', 'rotation']],+ [false, ['scaleFactor']],+ [false, ['bounds', 'scaleFactor']],+])('stops on rotation or unmatched geometry (%s, %j)', (matches, metrics) => {+ h.geometryMatches.mockReturnValue(matches);+ h.screenHandlers.get('display-metrics-changed')(+ {},+ { id: 1, size: { width: 1920, height: 1080 } },+ metrics,+ );+ expect(h.stop).toHaveBeenCalledOnce();+});++it('joins resolution restoration through the shared asynchronous quit phase', async () => {+ const cleanup = h.quit.get('remote-desktop-restore')!;+ expect(cleanup.phase).toBe('async');+ let finish!: () => void;+ h.stopAndRestore.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ const settled = vi.fn();+ const pending = Promise.resolve(cleanup.fn()).then(settled);+ await Promise.resolve();+ expect(settled).not.toHaveBeenCalled();+ finish();+ await pending;+ expect(settled).toHaveBeenCalledOnce();+});+it('bounds a stalled screen permission probe so the guide can finish its request', async () => {h.source = new Promise(() => {});- const pending = h.permissionDeps.request('screenRecording', () => true, new AbortController().signal);+ const pending = h.permissionDeps.request(+ 'screenRecording',+ () => true,+ new AbortController().signal,+ );const rejected = expect(pending).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');await vi.advanceTimersByTimeAsync(5000);await rejected;h.source = Promise.resolve([]);- await expect(h.permissionDeps.request('screenRecording', () => true, new AbortController().signal)).resolves.toBeUndefined();+ await expect(+ h.permissionDeps.request('screenRecording', () => true, new AbortController().signal),+ ).resolves.toBeUndefined();expect(h.stop).not.toHaveBeenCalled();});@@ -209,32 +328,40 @@ it('drops enumeration timeouts for one relay frame and resumes without stoppingawait expect(h.deps.frame('1', false)).rejects.toThrow('DESKTOP_DISABLED');});-it.each(['success', 'timeout'])('keeps relay polls out of native preparation and resumes after %s', async (outcome) => {- vi.stubGlobal('process', { ...process, platform: 'darwin' });- let sourcesReady!: (sources: any[]) => void;- h.source = new Promise((resolve) => { sourcesReady = resolve; });- const pending = offer();- const settled = outcome === 'success'- ? expect(pending).resolves.toBe('answer')- : expect(pending).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');- expect(h.nativeStop).toHaveBeenCalled();- await expect(h.deps.frame('1', true)).resolves.toBeNull();- h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());- await flush();- await expect(h.deps.frame('1', true)).resolves.toBeNull();- sourcesReady([{ id: 'screen:1', display_id: '1' }]);- await flush();- await expect(h.deps.frame('1', true)).resolves.toBeNull();- expect(h.nativeFrame).not.toHaveBeenCalled();- await expect(h.handlers.get(DESKTOP_LOCAL.NATIVE_FRAME)(event(), 'lease')).resolves.toBe('frame');- if (outcome === 'success') {- const id = h.owner.send.mock.calls[0][1].id;- h.handlers.get(DESKTOP_LOCAL.REPLY)(event(), id, 'answer');- } else await vi.advanceTimersByTimeAsync(18_000);- await settled;- await h.deps.frame('1', true);- expect(h.nativeFrame).toHaveBeenCalledTimes(2);-});+it.each(['success', 'timeout'])(+ 'keeps relay polls out of native preparation and resumes after %s',+ async (outcome) => {+ vi.stubGlobal('process', { ...process, platform: 'darwin' });+ let sourcesReady!: (sources: any[]) => void;+ h.source = new Promise((resolve) => {+ sourcesReady = resolve;+ });+ const pending = offer();+ const settled =+ outcome === 'success'+ ? expect(pending).resolves.toBe('answer')+ : expect(pending).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');+ expect(h.nativeStop).toHaveBeenCalled();+ await expect(h.deps.frame('1', true)).resolves.toBeNull();+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());+ await flush();+ await expect(h.deps.frame('1', true)).resolves.toBeNull();+ sourcesReady([{ id: 'screen:1', display_id: '1' }]);+ await flush();+ await expect(h.deps.frame('1', true)).resolves.toBeNull();+ expect(h.nativeFrame).not.toHaveBeenCalled();+ await expect(h.handlers.get(DESKTOP_LOCAL.NATIVE_FRAME)(event(), 'lease')).resolves.toBe(+ 'frame',+ );+ if (outcome === 'success') {+ const id = h.owner.send.mock.calls[0][1].id;+ h.handlers.get(DESKTOP_LOCAL.REPLY)(event(), id, 'answer');+ } else await vi.advanceTimersByTimeAsync(18_000);+ await settled;+ await h.deps.frame('1', true);+ expect(h.nativeFrame).toHaveBeenCalledTimes(2);+ },+);it.each(['ready', 'sources'])('revocation during %s prevents late capture from reviving the old offer',@@ -295,14 +422,23 @@ it('drops view-only input without breaking heartbeats, but still rejects invalidh.handlers.get(DESKTOP_LOCAL.REPLY)(event(), h.owner.send.mock.calls[0][1].id, 'answer');await pending;const input = h.handlers.get(DESKTOP_LOCAL.INPUT);- h.input.mockImplementation(() => { throw new Error('DESKTOP_VIEW_ONLY'); });+ h.input.mockImplementation(() => {+ throw new Error('DESKTOP_VIEW_ONLY');+ });expect(() => input(event(), 'lease', 1, [{ type: 'release' }])).not.toThrow();h.handlers.get(DESKTOP_LOCAL.VIEW_HEARTBEAT)(event(), 'lease');expect(h.viewHeartbeat).toHaveBeenCalledWith('lease');expect(h.owner.dead).toBe(false);expect(() => input(event(), 'old-lease', 2, [])).toThrow('PERMISSION_DENIED');- for (const reason of ['DESKTOP_STOPPED', 'DESKTOP_LEASE_EXPIRED', 'INVALID_REQUEST', 'DESKTOP_INPUT_UNAVAILABLE']) {- h.input.mockImplementation(() => { throw new Error(reason); });+ for (const reason of [+ 'DESKTOP_STOPPED',+ 'DESKTOP_LEASE_EXPIRED',+ 'INVALID_REQUEST',+ 'DESKTOP_INPUT_UNAVAILABLE',+ ]) {+ h.input.mockImplementation(() => {+ throw new Error(reason);+ });expect(() => input(event(), 'lease', 2, [])).toThrow('PERMISSION_DENIED');}});@@ -394,7 +530,12 @@ it('revocation while fetching ICE config prevents a late credential from startinit('keeps replacement capture and its in-flight ICE exchange when revoked config arrives late', async () => {let finish!: (servers: any[]) => void;- h.iceConfig.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ h.iceConfig.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );const pending = offer();const rejected = expect(pending).rejects.toThrow('DESKTOP_LEASE_EXPIRED');const old = h.owner;@@ -410,7 +551,11 @@ it('keeps replacement capture and its in-flight ICE exchange when revoked configh.handlers.get(DESKTOP_LOCAL.REPLY)(event(), command.id, 'new-answer');await expect(next).resolves.toBe('new-answer');const ice = h.deps.ice({- op: 'ice', lease: 'replacement', attemptId: 'attempt', after: 0, candidates: [],+ op: 'ice',+ lease: 'replacement',+ attemptId: 'attempt',+ after: 0,+ candidates: [],});const exchange = owner.send.mock.calls.at(-1)[1];finish([]);diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.tsindex 6b0249a497..b6c65e0b0e 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts@@ -39,6 +39,187 @@ function harness() {};}describe('remote desktop authority and lifecycle', () => {+ it('does not publish selected geometry or resume control before it is observed', async () => {+ const h = harness();+ h.deps.displayModes = async () => [+ { id: '1', width: 1920, height: 1080, current: true },+ { id: '2', width: 3840, height: 2160, current: false },+ ];+ let projected!: () => void;+ h.deps.resolution = vi.fn(async (_display, _mode, beforeChange, expected) => {+ beforeChange();+ expect(expected).toMatchObject({ width: 3840, height: 2160 });+ await new Promise<void>((resolve) => {+ projected = resolve;+ });+ beforeChange();+ });+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ const settled = vi.fn();+ const changing = h.controller+ .request('phone', {+ op: 'resolution',+ lease,+ modeId: '2',+ temporary: true,+ })+ .then(settled);+ for (let i = 0; i < 10; i++) await Promise.resolve();+ expect(projected).toBeTypeOf('function');+ expect(settled).not.toHaveBeenCalled();+ await expect(+ h.controller.request('phone', { op: 'control', lease, enabled: true }),+ ).rejects.toThrow();+ projected();+ await changing;+ expect(settled).toHaveBeenCalledWith(+ expect.objectContaining({+ controlling: false,+ display: expect.objectContaining({ width: 3840, height: 2160 }),+ }),+ );+ });++ it('keeps shutdown pending until resolution restoration finishes', async () => {+ const h = harness();+ h.deps.displayModes = async () => [+ { id: '1', width: 1920, height: 1080, current: true },+ { id: '2', width: 3840, height: 2160, current: false },+ ];+ h.deps.resolution = async (_display, _mode, beforeChange) => beforeChange();+ let finish!: () => void;+ h.deps.restoreResolution = vi.fn(async (_display, _mode, beforeChange) => {+ beforeChange();+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ });+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ await h.controller.request('phone', { op: 'resolution', lease, modeId: '2', temporary: true });+ const settled = vi.fn();+ const quitting = h.controller.stopAndRestore().then(settled);+ for (let i = 0; i < 5; i++) await Promise.resolve();+ expect(h.controller.state).toBeNull();+ expect(settled).not.toHaveBeenCalled();+ expect(h.deps.restoreResolution).toHaveBeenCalledWith(+ '1',+ '1',+ expect.any(Function),+ expect.objectContaining({ width: 1920, height: 1080 }),+ );+ finish();+ await quitting;+ expect(settled).toHaveBeenCalledOnce();+ expect(h.deps.restoreResolution).toHaveBeenCalledOnce();+ });+ it('waits for an in-flight mode change before restoring after disconnect', async () => {+ const h = harness();+ let finish!: () => void;+ let began!: () => void;+ const started = new Promise<void>((resolve) => {+ began = resolve;+ });+ const order: string[] = [];+ h.deps.displayModes = async () => [+ { id: '1', width: 1920, height: 1080, current: true },+ { id: '2', width: 3840, height: 2160, current: false },+ ];+ h.deps.resolution = async (_display, mode, beforeChange) => {+ beforeChange();+ if (mode === '2') {+ began();+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ }+ order.push(mode);+ };+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ const change = h.controller.request('phone', {+ op: 'resolution',+ lease,+ modeId: '2',+ temporary: true,+ });+ const rejected = expect(change).rejects.toThrow('DESKTOP_LEASE_EXPIRED');+ await started;+ await h.controller.request('phone', { op: 'stop', lease });+ await expect(h.start()).rejects.toThrow('DESKTOP_BUSY');+ expect(order).toEqual([]);+ finish();+ await rejected;+ await h.start();+ expect(order).toEqual(['2', '1']);+ });+ it('retains the original mode after a failed restore and retries before a new lease', async () => {+ const h = harness();+ h.deps.displayModes = async () => [+ { id: '1', width: 1920, height: 1080, current: true },+ { id: '2', width: 3840, height: 2160, current: false },+ ];+ let fail = true;+ h.deps.resolution = vi.fn(async (_display, mode, beforeChange) => {+ beforeChange();+ if (mode === '1' && fail) throw new Error('restore failed');+ });+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ await h.controller.request('phone', { op: 'resolution', lease, modeId: '2', temporary: true });+ await h.controller.request('phone', { op: 'stop', lease });+ await expect(h.start()).rejects.toThrow('restore failed');+ fail = false;+ await h.start();+ expect(h.deps.resolution).toHaveBeenLastCalledWith(+ '1',+ '1',+ expect.any(Function),+ expect.objectContaining({ width: 1920, height: 1080 }),+ );+ });+ it.each(['stop', 'timeout', 'takeover', 'revoke'] as const)(+ 'restores the first system mode after multiple changes on %s',+ async (ending) => {+ const h = harness();+ let modeId = '1';+ h.deps.displayModes = async () => [+ { id: '1', width: 1920, height: 1080, current: modeId === '1' },+ { id: '2', width: 3840, height: 2160, current: modeId === '2' },+ { id: '3', width: 1280, height: 720, current: modeId === '3' },+ ];+ h.deps.resolution = vi.fn(async (_display, mode, beforeChange) => {+ beforeChange();+ modeId = mode;+ });+ const { lease } = await h.start();+ for (const mode of ['2', '3']) {+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ const next = await h.controller.request('phone', {+ op: 'resolution',+ lease,+ modeId: mode,+ temporary: true,+ });+ expect(next).toMatchObject({ lease, controlling: false });+ expect(h.controller.hasLease(lease)).toBe(true);+ expect(modeId).toBe(mode);+ }+ if (ending === 'stop') await h.controller.request('phone', { op: 'stop', lease });+ else if (ending === 'timeout') {+ h.advance(60000);+ h.controller.tick();+ } else if (ending === 'revoke') {+ h.revoke();+ h.controller.tick();+ } else await h.controller.request('other', { op: 'start', displayId: '1', takeover: true });+ if (ending === 'revoke') await vi.waitFor(() => expect(modeId).toBe('1'));+ else if (ending !== 'takeover') await h.start(); // Starting waits for restoration.+ expect(modeId).toBe('1');+ expect(h.deps.resolution).toHaveBeenCalledTimes(3);+ },+ );it('keeps viewing and peer isolation after native input fails, and allows explicit control recovery', async () => {const h = harness(),lease = await h.start();@@ -100,81 +281,136 @@ describe('remote desktop authority and lifecycle', () => {});it('locks only on explicit owner exit and blocks takeover until lock completes', async () => {- const h = harness(), first = await h.start();+ const h = harness(),+ first = await h.start();let finish!: () => void;- h.deps.lockScreen = vi.fn(async current => {+ h.deps.lockScreen = vi.fn(async (current) => {expect(current()).toBe(true);- await new Promise<void>(resolve => { finish = resolve; });+ await new Promise<void>((resolve) => {+ finish = resolve;+ });});- await expect(h.controller.request('other', { op: 'stop', lease: first.lease, lockScreen: true })).rejects.toThrow('DESKTOP_LEASE_EXPIRED');+ await expect(+ h.controller.request('other', { op: 'stop', lease: first.lease, lockScreen: true }),+ ).rejects.toThrow('DESKTOP_LEASE_EXPIRED');expect(h.deps.lockScreen).not.toHaveBeenCalled();- const locking = h.controller.request('phone', { op: 'stop', lease: first.lease, lockScreen: true });- await expect(h.controller.request('other', { op: 'start', displayId: '1', takeover: true })).rejects.toThrow('DESKTOP_BUSY');+ const locking = h.controller.request('phone', {+ op: 'stop',+ lease: first.lease,+ lockScreen: true,+ });+ await expect(+ h.controller.request('other', { op: 'start', displayId: '1', takeover: true }),+ ).rejects.toThrow('DESKTOP_BUSY');finish();await expect(locking).resolves.toEqual({ ok: true });expect(h.deps.lockScreen).toHaveBeenCalledTimes(1);- await expect(h.controller.request('phone', { op: 'stop', lease: first.lease, lockScreen: true })).rejects.toThrow('DESKTOP_LEASE_EXPIRED');+ await expect(+ h.controller.request('phone', { op: 'stop', lease: first.lease, lockScreen: true }),+ ).rejects.toThrow('DESKTOP_LEASE_EXPIRED');const second = await h.start();await h.controller.request('phone', { op: 'stop', lease: second.lease });expect(h.deps.lockScreen).toHaveBeenCalledTimes(1);});it('invalidates delayed lock preparation after revocation and reports lock failure', async () => {- const h = harness(), first = await h.start();+ const h = harness(),+ first = await h.start();let finish!: () => void;- h.deps.lockScreen = async current => {- await new Promise<void>(resolve => { finish = resolve; });+ h.deps.lockScreen = async (current) => {+ await new Promise<void>((resolve) => {+ finish = resolve;+ });expect(current()).toBe(false);throw new Error('DESKTOP_LOCK_FAILED');};- const pending = h.controller.request('phone', { op: 'stop', lease: first.lease, lockScreen: true });- h.revoke(); finish();+ const pending = h.controller.request('phone', {+ op: 'stop',+ lease: first.lease,+ lockScreen: true,+ });+ h.revoke();+ finish();await expect(pending).rejects.toThrow('DESKTOP_LOCK_FAILED');expect(h.controller.state).toBeNull();});- it.each(['stop', 'expiry', 'revoke', 'account'])('cancels an in-flight lock on %s without cancelling for another peer', async reason => {- const h = harness();- let account = 'first';- h.deps.authenticationSession = () => account;- const first = await h.start();- let signal!: AbortSignal;- h.deps.lockScreen = async (_current, cancellation) => {- signal = cancellation;- await new Promise<void>((_resolve, reject) => {- cancellation.addEventListener('abort', () => reject(new Error('cancelled')), { once: true });+ it.each(['stop', 'expiry', 'revoke', 'account'])(+ 'cancels an in-flight lock on %s without cancelling for another peer',+ async (reason) => {+ const h = harness();+ let account = 'first';+ h.deps.authenticationSession = () => account;+ const first = await h.start();+ let signal!: AbortSignal;+ h.deps.lockScreen = async (_current, cancellation) => {+ signal = cancellation;+ await new Promise<void>((_resolve, reject) => {+ cancellation.addEventListener('abort', () => reject(new Error('cancelled')), {+ once: true,+ });+ });+ };+ const pending = h.controller.request('phone', {+ op: 'stop',+ lease: first.lease,+ lockScreen: true,});- };- const pending = h.controller.request('phone', { op: 'stop', lease: first.lease, lockScreen: true });- const rejected = expect(pending).rejects.toThrow('cancelled');- h.controller.stop('other');- expect(signal.aborted).toBe(false);- if (reason === 'stop') h.controller.stop('phone');- if (reason === 'expiry') { h.advance(120000); h.controller.tick(); }- if (reason === 'revoke') { h.revoke(); h.controller.tick(); }- if (reason === 'account') { account = 'second'; h.controller.tick(); }- expect(signal.aborted).toBe(true);- await rejected;- expect(h.controller.state).toBeNull();- });+ const rejected = expect(pending).rejects.toThrow('cancelled');+ h.controller.stop('other');+ expect(signal.aborted).toBe(false);+ if (reason === 'stop') h.controller.stop('phone');+ if (reason === 'expiry') {+ h.advance(120000);+ h.controller.tick();+ }+ if (reason === 'revoke') {+ h.revoke();+ h.controller.tick();+ }+ if (reason === 'account') {+ account = 'second';+ h.controller.tick();+ }+ expect(signal.aborted).toBe(true);+ await rejected;+ expect(h.controller.state).toBeNull();+ },+ );it('releases a stalled fallback frame for another peer without stopping its lease', async () => {vi.useFakeTimers();try {- const h = harness(), first = await h.start();+ const h = harness(),+ first = await h.start();let finish!: (value: string) => void;- h.deps.frame = () => enumerateDesktopSources(() => new Promise<string>(yes => { finish = yes; }), 5000);+ h.deps.frame = () =>+ enumerateDesktopSources(+ () =>+ new Promise<string>((yes) => {+ finish = yes;+ }),+ 5000,+ );const stalled = h.controller.request('phone', { op: 'frame', lease: first.lease });const rejection = expect(stalled).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');- const next = await h.controller.request('other', { op: 'start', displayId: '1', takeover: true }) as RemoteDesktopLease;+ const next = (await h.controller.request('other', {+ op: 'start',+ displayId: '1',+ takeover: true,+ })) as RemoteDesktopLease;await vi.advanceTimersByTimeAsync(5000);await rejection;const stops = vi.mocked(h.deps.stopVideo).mock.calls.length;h.advance(350);h.deps.frame = async () => 'new frame';- await expect(h.controller.request('other', { op: 'frame', lease: next.lease })).resolves.toEqual({ jpeg: 'new frame' });+ await expect(+ h.controller.request('other', { op: 'frame', lease: next.lease }),+ ).resolves.toEqual({ jpeg: 'new frame' });finish('stale frame');await Promise.resolve();expect(h.controller.hasLease(next.lease)).toBe(true);expect(h.deps.stopVideo).toHaveBeenCalledTimes(stops);- } finally { vi.useRealTimers(); }+ } finally {+ vi.useRealTimers();+ }});it('keeps ICE and media retries inside their peer lease, including after takeover', async () => {const h = harness(),@@ -211,28 +447,41 @@ describe('remote desktop authority and lifecycle', () => {expect(h.controller.hasLease(next.lease)).toBe(true);expect(h.deps.stopVideo).toHaveBeenCalledTimes(stopped);});- it.each(['success', 'failure'] as const)('releases old geometry before the native write and preserves replacements on %s', async (outcome) => {- const h = harness(), first = await h.start();- await h.controller.request('phone', { op: 'control', lease: first.lease, enabled: true });- let finish!: () => void;- h.deps.resolution = async (_display, _mode, beforeChange) => {- beforeChange();- expect(h.controller.displayId).toBeNull();- expect(h.controller.hasLease(first.lease)).toBe(false);- // The real display listener matches displayId, now null, before helper exit.- if (h.controller.displayId === '1') h.controller.stop();- await new Promise<void>(resolve => { finish = resolve; });- if (outcome === 'failure') throw new Error('native failed');- };- const pending = h.controller.request('phone', { op: 'resolution', lease: first.lease, modeId: '1' });- const next = await h.controller.request('other', { op: 'start', displayId: '1' }) as RemoteDesktopLease;- const stops = vi.mocked(h.deps.stopVideo).mock.calls.length;- finish();- if (outcome === 'success') await expect(pending).resolves.toEqual({ ok: true });- else await expect(pending).rejects.toThrow('native failed');- expect(h.controller.hasLease(next.lease)).toBe(true);- expect(h.deps.stopVideo).toHaveBeenCalledTimes(stops);- });+ it.each(['success', 'failure'] as const)(+ 'releases old geometry before the native write and preserves replacements on %s',+ async (outcome) => {+ const h = harness(),+ first = await h.start();+ await h.controller.request('phone', { op: 'control', lease: first.lease, enabled: true });+ let finish!: () => void;+ h.deps.resolution = async (_display, _mode, beforeChange) => {+ beforeChange();+ expect(h.controller.displayId).toBeNull();+ expect(h.controller.hasLease(first.lease)).toBe(false);+ // The real display listener matches displayId, now null, before helper exit.+ if (h.controller.displayId === '1') h.controller.stop();+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ if (outcome === 'failure') throw new Error('native failed');+ };+ const pending = h.controller.request('phone', {+ op: 'resolution',+ lease: first.lease,+ modeId: '1',+ });+ const next = (await h.controller.request('other', {+ op: 'start',+ displayId: '1',+ })) as RemoteDesktopLease;+ const stops = vi.mocked(h.deps.stopVideo).mock.calls.length;+ finish();+ if (outcome === 'success') await expect(pending).resolves.toEqual({ ok: true });+ else await expect(pending).rejects.toThrow('native failed');+ expect(h.controller.hasLease(next.lease)).toBe(true);+ expect(h.deps.stopVideo).toHaveBeenCalledTimes(stops);+ },+ );it.each(['release', 'takeover', 'revoke'] as const)('invalidates pending resolution after %s without stopping replacement control',async (action) => {@@ -273,51 +522,84 @@ describe('remote desktop authority and lifecycle', () => {it('takes over only explicitly and prevents the evicted device from automatically returning', async () => {const h = harness();const first = await h.start();- await expect(h.controller.request('other', { op: 'start', displayId: '1' })).rejects.toThrow('DESKTOP_BUSY');- await expect(h.controller.request('other', { op: 'start', displayId: 'missing', takeover: true })).rejects.toThrow('DESKTOP_DISPLAY_MISSING');+ await expect(h.controller.request('other', { op: 'start', displayId: '1' })).rejects.toThrow(+ 'DESKTOP_BUSY',+ );+ await expect(+ h.controller.request('other', { op: 'start', displayId: 'missing', takeover: true }),+ ).rejects.toThrow('DESKTOP_DISPLAY_MISSING');expect(h.controller.hasLease(first.lease)).toBe(true);- await expect(h.controller.request('other', { op: 'start', displayId: '1', takeover: true, resume: true })).rejects.toThrow('INVALID_REQUEST');- const second = await h.controller.request('other', { op: 'start', displayId: '1', takeover: true }) as RemoteDesktopLease;+ await expect(+ h.controller.request('other', { op: 'start', displayId: '1', takeover: true, resume: true }),+ ).rejects.toThrow('INVALID_REQUEST');+ const second = (await h.controller.request('other', {+ op: 'start',+ displayId: '1',+ takeover: true,+ })) as RemoteDesktopLease;expect(h.controller.hasLease(first.lease)).toBe(false);expect(h.controller.hasLease(second.lease)).toBe(true);- await expect(h.controller.request('phone', { op: 'stop', lease: first.lease })).rejects.toThrow('DESKTOP_STOPPED');+ await expect(h.controller.request('phone', { op: 'stop', lease: first.lease })).rejects.toThrow(+ 'DESKTOP_STOPPED',+ );expect(h.controller.hasLease(second.lease)).toBe(true);h.controller.stop('other');- await expect(h.controller.request('phone', { op: 'start', displayId: '1', resume: true })).rejects.toThrow('DESKTOP_STOPPED');+ await expect(+ h.controller.request('phone', { op: 'start', displayId: '1', resume: true }),+ ).rejects.toThrow('DESKTOP_STOPPED');});it('recovers its own display with a fresh input sequence after a lost start reply', async () => {const h = harness();const first = await h.start();await h.controller.request('phone', { op: 'control', lease: first.lease, enabled: true });h.controller.input(first.lease, 100, [{ kind: 'release' }]);- for (const request of [- { displayId: '1' },- { displayId: 'other', resume: true },- ]) await expect(h.controller.request('phone', { op: 'start', ...request })).rejects.toThrow('DESKTOP_BUSY');- await expect(h.controller.request('other', { op: 'start', displayId: '1', resume: true })).rejects.toThrow('DESKTOP_BUSY');- const next = await h.controller.request('phone', { op: 'start', displayId: '1', resume: true }) as RemoteDesktopLease;+ for (const request of [{ displayId: '1' }, { displayId: 'other', resume: true }])+ await expect(h.controller.request('phone', { op: 'start', ...request })).rejects.toThrow(+ 'DESKTOP_BUSY',+ );+ await expect(+ h.controller.request('other', { op: 'start', displayId: '1', resume: true }),+ ).rejects.toThrow('DESKTOP_BUSY');+ const next = (await h.controller.request('phone', {+ op: 'start',+ displayId: '1',+ resume: true,+ })) as RemoteDesktopLease;expect(next.lease).not.toBe(first.lease);expect(h.controller.hasLease(first.lease)).toBe(false);expect(h.deps.stopInput).toHaveBeenCalledTimes(1);expect(h.deps.stopVideo).toHaveBeenCalledTimes(1);- await expect(h.controller.request('phone', { op: 'stop', lease: first.lease })).rejects.toThrow('DESKTOP_LEASE_EXPIRED');+ await expect(h.controller.request('phone', { op: 'stop', lease: first.lease })).rejects.toThrow(+ 'DESKTOP_LEASE_EXPIRED',+ );await h.controller.request('phone', { op: 'control', lease: next.lease, enabled: true });h.controller.input(next.lease, 0, [{ kind: 'release' }]);expect(h.deps.input).toHaveBeenCalledTimes(2);expect(h.controller.hasLease(next.lease)).toBe(true);});it.each(['cancel', 'revoke', 'host-stop', 'reject'] as const)(- 'does not revive a pending same-peer resume after %s', async (event) => {+ 'does not revive a pending same-peer resume after %s',+ async (event) => {const h = harness();const first = await h.start();let resolve!: (value: Awaited<ReturnType<DesktopControllerDeps['capabilities']>>) => void;let reject!: (reason: Error) => void;const caps = await h.deps.capabilities();- h.deps.capabilities = () => new Promise((yes, no) => { resolve = yes; reject = no; });- const pending = h.controller.request('phone', { op: 'start', displayId: '1', resume: true })- .then(() => null, (error: unknown) => error);+ h.deps.capabilities = () =>+ new Promise((yes, no) => {+ resolve = yes;+ reject = no;+ });+ const pending = h.controller+ .request('phone', { op: 'start', displayId: '1', resume: true })+ .then(+ () => null,+ (error: unknown) => error,+ );expect(resolve).toBeTypeOf('function');- await expect(h.controller.request('other', { op: 'start', displayId: '1', takeover: true })).rejects.toThrow('DESKTOP_BUSY');+ await expect(+ h.controller.request('other', { op: 'start', displayId: '1', takeover: true }),+ ).rejects.toThrow('DESKTOP_BUSY');if (event === 'cancel') h.controller.stop('phone');if (event === 'revoke') h.revoke();if (event === 'host-stop') h.controller.stopByUser();@@ -332,39 +614,63 @@ describe('remote desktop authority and lifecycle', () => {const h = harness();const first = await h.start();let finish!: (jpeg: string) => void;- h.deps.frame = vi.fn(() => new Promise<string>((resolve) => { finish = resolve; }));+ h.deps.frame = vi.fn(+ () =>+ new Promise<string>((resolve) => {+ finish = resolve;+ }),+ );const frame = h.controller.request('phone', { op: 'frame', lease: first.lease });- const next = await h.controller.request('phone', { op: 'start', displayId: '1', resume: true }) as RemoteDesktopLease;+ const next = (await h.controller.request('phone', {+ op: 'start',+ displayId: '1',+ resume: true,+ })) as RemoteDesktopLease;finish('old frame');await expect(frame).rejects.toThrow('DESKTOP_LEASE_EXPIRED');h.advance(350);h.deps.frame = vi.fn(async () => 'new frame');- await expect(h.controller.request('phone', { op: 'frame', lease: next.lease })).resolves.toEqual({ jpeg: 'new frame' });+ await expect(+ h.controller.request('phone', { op: 'frame', lease: next.lease }),+ ).resolves.toEqual({ jpeg: 'new frame' });expect(h.controller.hasLease(next.lease)).toBe(true);expect(h.deps.stopVideo).toHaveBeenCalledTimes(1);});- it.each([false, true])('bounds relay frames with cursor overlay=%s without stopping the lease', async (overlay) => {- const h = harness();- const { lease } = await h.start();- const cursor = null;- for (const bytes of [180_000, 180_001, 180_000]) {- const jpeg = Buffer.alloc(bytes).toString('base64');- h.deps.frame = vi.fn(async () => overlay ? { jpeg, cursor } : jpeg);- const result = await h.controller.request('phone', { op: 'frame', lease, cursorOverlay: overlay });- expect(result).toEqual(bytes > 180_000 ? { jpeg: null } : overlay ? { jpeg, cursor } : { jpeg });- h.advance(350);- }- expect(h.controller.hasLease(lease)).toBe(true);- expect(h.deps.stopVideo).not.toHaveBeenCalled();- expect(h.deps.stopInput).not.toHaveBeenCalled();- });+ it.each([false, true])(+ 'bounds relay frames with cursor overlay=%s without stopping the lease',+ async (overlay) => {+ const h = harness();+ const { lease } = await h.start();+ const cursor = null;+ for (const bytes of [180_000, 180_001, 180_000]) {+ const jpeg = Buffer.alloc(bytes).toString('base64');+ h.deps.frame = vi.fn(async () => (overlay ? { jpeg, cursor } : jpeg));+ const result = await h.controller.request('phone', {+ op: 'frame',+ lease,+ cursorOverlay: overlay,+ });+ expect(result).toEqual(+ bytes > 180_000 ? { jpeg: null } : overlay ? { jpeg, cursor } : { jpeg },+ );+ h.advance(350);+ }+ expect(h.controller.hasLease(lease)).toBe(true);+ expect(h.deps.stopVideo).not.toHaveBeenCalled();+ expect(h.deps.stopInput).not.toHaveBeenCalled();+ },+ );it('keeps the same lease and video negotiation through an empty fallback frame', async () => {const h = harness();h.deps.frame = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce('jpeg');const { lease } = await h.start();- await expect(h.controller.request('phone', { op: 'frame', lease })).resolves.toEqual({ jpeg: null });+ await expect(h.controller.request('phone', { op: 'frame', lease })).resolves.toEqual({+ jpeg: null,+ });h.advance(350);- await expect(h.controller.request('phone', { op: 'frame', lease })).resolves.toEqual({ jpeg: 'jpeg' });+ await expect(h.controller.request('phone', { op: 'frame', lease })).resolves.toEqual({+ jpeg: 'jpeg',+ });expect(h.controller.hasLease(lease)).toBe(true);expect(h.deps.stopVideo).not.toHaveBeenCalled();});@@ -554,13 +860,25 @@ describe('remote desktop authority and lifecycle', () => {let currentCopy!: () => boolean;h.deps.clipboard = (_action, _text, isCurrent) => {currentCopy = isCurrent;- return new Promise<string>((resolve) => { finishCopy = resolve; });+ return new Promise<string>((resolve) => {+ finishCopy = resolve;+ });};- const copy = h.controller.request('phone', { op: 'clipboard', lease: first.lease, action: 'copy' });+ const copy = h.controller.request('phone', {+ op: 'clipboard',+ lease: first.lease,+ action: 'copy',+ });const caps = await h.deps.capabilities();let finishStart!: (value: typeof caps) => void;- h.deps.capabilities = vi.fn()- .mockImplementationOnce(() => new Promise<typeof caps>((resolve) => { finishStart = resolve; }))+ h.deps.capabilities = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise<typeof caps>((resolve) => {+ finishStart = resolve;+ }),+ ).mockResolvedValue(caps);const next = h.controller.request('other', { op: 'start', displayId: '1', takeover: true });const changes = vi.mocked(h.deps.changed).mock.calls.length;@@ -580,22 +898,26 @@ describe('remote desktop authority and lifecycle', () => {finishStart(caps);await expect(next).rejects.toThrow('DESKTOP_DISABLED');expect(h.controller.hasLease(first.lease)).toBe(true);- await expect(h.controller.request('other', { op: 'start', displayId: '1', takeover: true }))- .resolves.toHaveProperty('lease');- });- it.each([false, true])('isolates unrelated peer stop while retaining global cancellation (global=%s)', async (global) => {- const h = harness();- const pending = h.start();- if (global) h.controller.stop();- else h.controller.stop('unrelated');- if (global) {- await expect(pending).rejects.toThrow('DESKTOP_DISABLED');- expect(h.controller.state).toBeNull();- } else {- await expect(pending).resolves.toHaveProperty('lease');- expect(h.deps.stopVideo).not.toHaveBeenCalled();- }+ await expect(+ h.controller.request('other', { op: 'start', displayId: '1', takeover: true }),+ ).resolves.toHaveProperty('lease');});+ it.each([false, true])(+ 'isolates unrelated peer stop while retaining global cancellation (global=%s)',+ async (global) => {+ const h = harness();+ const pending = h.start();+ if (global) h.controller.stop();+ else h.controller.stop('unrelated');+ if (global) {+ await expect(pending).rejects.toThrow('DESKTOP_DISABLED');+ expect(h.controller.state).toBeNull();+ } else {+ await expect(pending).resolves.toHaveProperty('lease');+ expect(h.deps.stopVideo).not.toHaveBeenCalled();+ }+ },+ );it('releases control after an input failure without ending the lease or its media', async () => {const h = harness();const lease = await h.start();@@ -623,9 +945,9 @@ describe('remote desktop authority and lifecycle', () => {}),).rejects.toThrow('VIEW_ONLY');expect(h.deps.input).toHaveBeenCalledTimes(1);- await expect(h.controller.request('phone', { op: 'frame', lease: lease.lease })).resolves.toEqual(- { jpeg: 'jpeg' },- );+ await expect(+ h.controller.request('phone', { op: 'frame', lease: lease.lease }),+ ).resolves.toEqual({ jpeg: 'jpeg' });});it('lets the same viewer take control again after a release without touching the media', async () => {const h = harness();diff --git a/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplay.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplay.test.tsindex 27a965cc59..50d1f3329a 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplay.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplay.test.ts@@ -41,6 +41,36 @@ function fixture() {}describe('viewer-sized desktop ownership', () => {+ it.each(['stop', 'restoreViewerDisplay'] as const)(+ 'restores the original system mode after switching from a system mode to fit on %s',+ async (ending) => {+ const f = fixture();+ let modeId = '10';+ f.deps.displayModes = async () => [+ { id: '10', width: 1920, height: 1080, current: modeId === '10' },+ { id: '20', width: 3840, height: 2160, current: modeId === '20' },+ ];+ f.deps.resolution = vi.fn(async (_display, mode, before) => {+ before();+ modeId = mode;+ });+ vi.mocked(f.handle.restore!).mockResolvedValue({+ id: '1',+ name: 'Main',+ width: 3840,+ height: 2160,+ });+ const { lease } = await f.start();+ await f.host.request('phone', { op: 'resolution', lease, modeId: '20', temporary: true });+ await f.host.request('phone', { op: 'control', lease, enabled: true });+ await f.host.request('phone', { op: 'viewerDisplay', lease, width: 900, height: 1600 });+ await f.host.request('phone', { op: 'control', lease, enabled: true });+ const result = await f.host.request('phone', { op: ending, lease });+ if (ending === 'stop') await f.start();+ else expect(result).toMatchObject({ display: { width: 1920, height: 1080 } });+ expect(modeId).toBe('10');+ },+ );it('hides the helper display during and across stopped-lease restoration', async () => {const f = fixture();const lease = await f.start();diff --git a/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplaySupport.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplaySupport.test.tsindex 3c8d16095f..d5d6c84a09 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplaySupport.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/viewerDisplaySupport.test.ts@@ -4,8 +4,9 @@ const mocks = vi.hoisted(() => ({app: { isPackaged: false, getAppPath: () => '/fake/app', getPath: () => '/fake/profile' },exec: vi.fn(),access: vi.fn(),+ displays: vi.fn(),}));-vi.mock('electron', () => ({ app: mocks.app, screen: {} }));+vi.mock('electron', () => ({ app: mocks.app, screen: { getAllDisplays: mocks.displays } }));vi.mock('node:child_process', () => ({ execFile: vi.fn(), spawn: vi.fn() }));vi.mock('node:util', () => ({ promisify: () => mocks.exec }));vi.mock('node:fs/promises', () => ({@@ -24,7 +25,57 @@ beforeEach(() => {mocks.access.mockReset().mockResolvedValue(undefined);vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');});-afterEach(() => vi.restoreAllMocks());+afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+});++it('waits for Electron to observe restored geometry and mirror removal', async () => {+ vi.useFakeTimers();+ const { waitForDisplayRestore } = await import('../viewerDisplay');+ let width = 800;+ let released = false;+ mocks.displays.mockImplementation(() => [{ id: 1, size: { width, height: 1080 } }]);+ const settled = vi.fn();+ const pending = waitForDisplayRestore(+ '1',+ { width: 1920, height: 1080 },+ () => {},+ () => released,+ ).then(settled);+ await vi.advanceTimersByTimeAsync(100);+ expect(settled).not.toHaveBeenCalled();+ width = 1920;+ await vi.advanceTimersByTimeAsync(100);+ expect(settled).not.toHaveBeenCalled();+ released = true;+ await vi.advanceTimersByTimeAsync(50);+ await pending;+ expect(settled).toHaveBeenCalledWith(expect.objectContaining({ width: 1920, height: 1080 }));+});++it.each(['unplugged', 'cancelled', 'timeout'] as const)(+ 'settles a %s restoration wait',+ async (reason) => {+ vi.useFakeTimers();+ const { waitForDisplayRestore } = await import('../viewerDisplay');+ mocks.displays.mockReturnValue(+ reason === 'unplugged' ? [] : [{ id: 1, size: { width: 800, height: 600 } }],+ );+ const pending = waitForDisplayRestore('1', { width: 1920, height: 1080 }, () => {+ if (reason === 'cancelled') throw new Error('DESKTOP_LEASE_EXPIRED');+ });+ if (reason === 'unplugged') await expect(pending).resolves.toMatchObject({ id: '1' });+ else {+ const rejected = expect(pending).rejects.toThrow(+ reason === 'cancelled' ? 'DESKTOP_LEASE_EXPIRED' : 'DESKTOP_VIEWER_DISPLAY_UNAVAILABLE',+ );+ await vi.advanceTimersByTimeAsync(5000);+ await rejected;+ }+ expect(vi.getTimerCount()).toBe(0);+ },+);it('probes an existing binary once across concurrent capability requests', async () => {const { viewerDisplaySupported } = await import('../viewerDisplay');diff --git a/apps/desktop/src/main/remote-desktop/controller.ts b/apps/desktop/src/main/remote-desktop/controller.tsindex 543b7ef7df..6d0be8433f 100644--- a/apps/desktop/src/main/remote-desktop/controller.ts+++ b/apps/desktop/src/main/remote-desktop/controller.ts@@ -49,7 +49,20 @@ export interface DesktopControllerDeps {): Promise<string>;ice?(request: RemoteDesktopIceRequest): Promise<RemoteDesktopIceReply>;displayModes?(displayId: string): Promise<RemoteDesktopDisplayMode[]>;- resolution?(displayId: string, modeId: string, beforeChange: () => void): Promise<void>;+ /** Local hardware presence; must not hide displays when remote access is revoked. */+ displayPresent?(displayId: string): boolean;+ resolution?(+ displayId: string,+ modeId: string,+ beforeChange: () => void,+ expected?: { width: number; height: number },+ ): Promise<void>;+ restoreResolution?(+ displayId: string,+ modeId: string,+ beforeChange: () => void,+ expected: { width: number; height: number },+ ): Promise<void>;createViewerDisplay?(displayId: string,isCurrent: () => boolean,@@ -84,6 +97,13 @@ export class RemoteDesktopController {private starting = false;private viewerDisplay: ViewerDisplayHandle | null = null;private displayRestoring: Promise<void> | null = null;+ private originalResolution: {+ displayId: string;+ modeId: string;+ width: number;+ height: number;+ } | null = null;+ private resolutionWrite: Promise<void> | null = null;private displayChanging = false;private viewerGeometryManaged = false;private locking = false;@@ -169,17 +189,103 @@ export class RemoteDesktopController {// Retain the handle until restoration completes (or can be retried after failure).// EOF releases it asynchronously; a new lease must not bind stale geometry.if (!this.viewerDisplay?.restore) this.viewerDisplay = null;- if (this.viewerDisplay) void this.restoreStoppedDisplay().catch(() => {});+ if (this.viewerDisplay || this.originalResolution)+ void this.restoreStoppedDisplay().catch(() => {});this.viewerGeometryManaged = false;this.deps.changed();}+ private async temporaryResolution(+ peer: string,+ active: NonNullable<RemoteDesktopController['active']>,+ modeId: string,+ ): Promise<RemoteDesktopLease> {+ if (!active.controlling) throw new Error('DESKTOP_VIEW_ONLY');+ if (!this.deps.resolution || !this.deps.displayModes)+ throw new Error('DESKTOP_DISPLAY_MODES_UNAVAILABLE');+ if (this.inputStarting || this.clipboardPending || this.locking || this.starting)+ throw new Error('DESKTOP_DISPLAY_BUSY');+ const generation = this.controlGeneration;+ const current = () => {+ this.tick();+ return this.active === active && active.controlling && this.controlGeneration === generation;+ };+ const requireCurrent = () => {+ if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');+ };+ this.displayChanging = true;+ try {+ this.deps.stopInput();+ this.deps.stopVideo();+ await this.deps.releaseInput?.();+ requireCurrent();+ // Remove the temporary mirror before enumerating the physical monitor.+ if (this.viewerDisplay) {+ if (!this.viewerDisplay.restore) throw new Error('DESKTOP_VIEWER_DISPLAY_UNAVAILABLE');+ await this.viewerDisplay.restore(current);+ requireCurrent();+ this.viewerDisplay = null;+ }+ const modes = await this.deps.displayModes(active.sourceDisplayId);+ requireCurrent();+ const original = modes.find((mode) => mode.current);+ const selected = modes.find((mode) => mode.id === modeId);+ if (!original || !selected) throw new Error('DESKTOP_DISPLAY_MODE_MISSING');+ this.originalResolution ??= {+ displayId: active.sourceDisplayId,+ modeId: original.id,+ width: original.width,+ height: original.height,+ };+ this.resolutionWrite = this.deps.resolution(+ active.sourceDisplayId,+ modeId,+ requireCurrent,+ selected,+ );+ await this.resolutionWrite;+ requireCurrent();+ active.display = {+ id: active.sourceDisplayId,+ name: active.display.name,+ width: selected.width,+ height: selected.height,+ };+ this.viewerGeometryManaged = true;+ active.controlling = false;+ this.controlGeneration++;+ this.deps.changed();+ return { lease: active.lease, display: active.display, controlling: false };+ } catch (error) {+ if (this.active === active) this.stop(peer);+ throw error;+ } finally {+ this.resolutionWrite = null;+ this.displayChanging = false;+ }+ }private restoreStoppedDisplay(): Promise<void> {if (this.displayRestoring) return this.displayRestoring;- if (this.active || !this.viewerDisplay) return Promise.resolve();+ if (this.active || (!this.viewerDisplay && !this.originalResolution)) return Promise.resolve();const handle = this.viewerDisplay;const pending = (async () => {- await handle.restore?.(() => !this.active && this.viewerDisplay === handle);+ // A disconnect can arrive while the native write is still in flight.+ if (this.resolutionWrite) await this.resolutionWrite.catch(() => {});+ await handle?.restore?.(() => !this.active && this.viewerDisplay === handle);if (this.viewerDisplay === handle) this.viewerDisplay = null;+ const original = this.originalResolution;+ if (original) {+ if (this.deps.displayPresent?.(original.displayId) !== false)+ await (this.deps.restoreResolution ?? this.deps.resolution)!(+ original.displayId,+ original.modeId,+ () => {+ if (this.active || this.originalResolution !== original)+ throw new Error('DESKTOP_LEASE_EXPIRED');+ },+ original,+ );+ if (this.originalResolution === original) this.originalResolution = null;+ }})();this.displayRestoring = pending;void pending@@ -189,6 +295,11 @@ export class RemoteDesktopController {.catch(() => {});return pending;}+ /** Join the same restoration used by disconnects before the process exits. */+ async stopAndRestore(): Promise<void> {+ this.stop();+ await this.restoreStoppedDisplay();+ }/*** Input injection failed while the lease is still valid. Input belongs to the* control bit, so release control and keep everything else: ending the lease@@ -268,6 +379,9 @@ export class RemoteDesktopController {displays: publicDisplays,automaticReconnect: true,connectionTakeover: true,+ resolutionRestore: Boolean(+ caps.displayModes && this.deps.resolution && this.deps.displayModes,+ ),};}if (!this.deps.authorized(peer)) throw new Error('DESKTOP_DISABLED');@@ -297,7 +411,8 @@ export class RemoteDesktopController {this.startingPeer = peer;const generation = this.controlGeneration;try {- if (!this.active && this.viewerDisplay) await this.restoreStoppedDisplay();+ if (!this.active && (this.viewerDisplay || this.originalResolution))+ await this.restoreStoppedDisplay();const caps = await this.deps.capabilities();if (!this.authenticationCurrent(peer, authenticationSession))throw new Error('DESKTOP_AUTHENTICATION_REQUIRED');@@ -316,7 +431,7 @@ export class RemoteDesktopController {// A lost start reply can leave our own lease alive. Rotate it using the// existing cleanup so the new viewer can restart its input sequence at 0.else if (resumesActive) this.stop(peer);- if (this.viewerDisplay) {+ if (this.viewerDisplay || this.originalResolution) {const restorationGeneration = this.controlGeneration;await this.restoreStoppedDisplay();const restored = await this.deps.capabilities();@@ -383,7 +498,7 @@ export class RemoteDesktopController {}this.viewerDisplay = handle;}- const display =+ let display =request.op === 'restoreViewerDisplay'? await this.viewerDisplay.restore!(current): await this.viewerDisplay.resize(request.width, request.height, current);@@ -394,7 +509,24 @@ export class RemoteDesktopController {))throw new Error('DESKTOP_DISPLAY_MISSING');- if (request.op === 'restoreViewerDisplay') this.viewerDisplay = null;+ if (request.op === 'restoreViewerDisplay') {+ this.viewerDisplay = null;+ const original = this.originalResolution;+ if (original) {+ this.resolutionWrite = (this.deps.restoreResolution ?? this.deps.resolution)!(+ original.displayId,+ original.modeId,+ () => {+ if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');+ },+ original,+ );+ await this.resolutionWrite;+ if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');+ this.originalResolution = null;+ display = { ...display, width: original.width, height: original.height };+ }+ }if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');this.viewerGeometryManaged = true;active.display = display;@@ -406,6 +538,7 @@ export class RemoteDesktopController {if (this.active === active) this.stop(peer);throw error;} finally {+ this.resolutionWrite = null;this.displayChanging = false;}}@@ -552,6 +685,7 @@ export class RemoteDesktopController {return modes;}case 'resolution': {+ if (request.temporary) return this.temporaryResolution(peer, active, request.modeId);if (!active.controlling) throw new Error('DESKTOP_VIEW_ONLY');if (!this.deps.resolution) throw new Error('DESKTOP_DISPLAY_MODES_UNAVAILABLE');if (this.inputStarting || this.clipboardPending || this.locking || this.starting)diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.tsindex 52aa5fe12e..24be77ef7f 100644--- a/apps/desktop/src/main/remote-desktop/index.ts+++ b/apps/desktop/src/main/remote-desktop/index.ts@@ -1,5 +1,4 @@import {- app,desktopCapturer,ipcMain,nativeImage,@@ -35,7 +34,12 @@ import { denyAppDesktopCapture } from './capturePermissions';import { readDeviceLinkSettings, writeDeviceLinkSetting } from '../device-link/settings-store';import { throwIpcError } from '../utils/ipcValidate';import { RemoteDesktopController } from './controller';-import { createViewerDisplay, viewerDisplaySupported } from './viewerDisplay';+import { onQuit } from '../lifecycle';+import {+ createViewerDisplay,+ viewerDisplaySupported,+ waitForDisplayRestore,+} from './viewerDisplay';import { desktopCaptureSource, enumerateDesktopSources } from './captureSource';import { encodeDesktopFrame, encodeNativeRelayFrame } from './frame';import { transferDesktopClipboard, transferDesktopClipboardContent } from './clipboard';@@ -398,7 +402,21 @@ export const remoteDesktop = new RemoteDesktopController({clipboardContent: (action, content, isCurrent) =>transferDesktopClipboardContent(action, content, isCurrent, (events) => input.input(events)),displayModes: readDesktopDisplayModes,- resolution: setDesktopDisplayMode,+ displayPresent: (displayId) =>+ screen.getAllDisplays().some((display) => String(display.id) === displayId),+ resolution: async (displayId, modeId, beforeChange, expected) => {+ await setDesktopDisplayMode(displayId, modeId, beforeChange);+ if (expected)+ await waitForDisplayRestore(displayId, expected, beforeChange, (displays) =>+ // Restoration may retire an unplugged monitor; selection must not+ // publish usable geometry for a monitor that no longer exists.+ displays.some((display) => String(display.id) === displayId),+ );+ },+ restoreResolution: async (displayId, modeId, beforeChange, expected) => {+ await setDesktopDisplayMode(displayId, modeId, beforeChange, true);+ await waitForDisplayRestore(displayId, expected, beforeChange);+ },createViewerDisplay,startInput: (displayId) => input.start(displayId),input: (events) => {@@ -444,23 +462,27 @@ export function registerRemoteDesktopIpc(denyAppDesktopCapture(session.defaultSession, isVoiceInputOwner);const timer = setInterval(() => remoteDesktop.tick(), 1000);timer.unref();- app.on('before-quit', () => {+ onQuit('remote-desktop-stop', () => {clearInterval(timer);permissions.dismiss();remoteDesktop.stop();});+ onQuit('remote-desktop-restore', () => remoteDesktop.stopAndRestore(), 'async');screen.on('display-removed', (_event, display) => {if (remoteDesktop.changingDisplay) return;if (String(display.id) === remoteDesktop.displayId) remoteDesktop.stop();});screen.on('display-metrics-changed', (_event, display, metrics) => {if (remoteDesktop.changingDisplay) return;- // Work-area changes (lock screen, Dock/menu bar, display wake) do not- // change whole-screen input coordinates and must not terminate the lease.+ // Managed resolution changes can deliver scaleFactor after preparation+ // finishes. Matching logical geometry keeps input coordinates valid;+ // rotation still invalidates the lease, even for an unchanged size.if (String(display.id) === remoteDesktop.displayId &&!(- metrics.every((metric) => metric === 'bounds' || metric === 'workArea') &&+ metrics.every(+ (metric) => metric === 'bounds' || metric === 'workArea' || metric === 'scaleFactor',+ ) &&remoteDesktop.displayGeometryMatches(String(display.id),display.size.width,diff --git a/apps/desktop/src/main/remote-desktop/inputHost.ts b/apps/desktop/src/main/remote-desktop/inputHost.tsindex 9bc3f067ea..9b060a5de5 100644--- a/apps/desktop/src/main/remote-desktop/inputHost.ts+++ b/apps/desktop/src/main/remote-desktop/inputHost.ts@@ -437,12 +437,24 @@ export async function setDesktopDisplayMode(displayId: string,modeId: string,beforeChange: () => void,+ restoringOriginal = false,): Promise<void> {if (changingResolution) throw new Error('DESKTOP_DISPLAY_BUSY');changingResolution = true;try {- const modes = await readDesktopDisplayModes(displayId);- if (!modes.some((mode) => mode.id === modeId)) throw new Error('DESKTOP_DISPLAY_MODE_MISSING');+ if (+ process.platform !== 'darwin' ||+ !/^[0-9]{1,10}$/.test(displayId) ||+ !/^[0-9]{1,10}$/.test(modeId)+ )+ throw new Error('DESKTOP_DISPLAY_MODE_MISSING');+ // The UI list deduplicates equal-size modes; the saved original may no+ // longer be its preferred entry. Native still validates against ALL modes.+ if (!restoringOriginal) {+ const modes = await readDesktopDisplayModes(displayId);+ if (!modes.some((mode) => mode.id === modeId))+ throw new Error('DESKTOP_DISPLAY_MODE_MISSING');+ }const binary = await resolveBinary();// Build/enumeration can finish after disconnect, revocation or view-only.beforeChange();diff --git a/apps/desktop/src/main/remote-desktop/viewerDisplay.ts b/apps/desktop/src/main/remote-desktop/viewerDisplay.tsindex 8d2e89304c..7fb3f47407 100644--- a/apps/desktop/src/main/remote-desktop/viewerDisplay.ts+++ b/apps/desktop/src/main/remote-desktop/viewerDisplay.ts@@ -79,6 +79,35 @@ export interface ViewerDisplayHandle {dispose(): void;}+/** CoreGraphics completion precedes Electron's display projection. */+export async function waitForDisplayRestore(+ displayId: string,+ expected: { width: number; height: number } | undefined,+ requireCurrent: () => void,+ released: (displays: Electron.Display[]) => boolean = () => true,+): Promise<RemoteDesktopDisplay> {+ for (let attempt = 0; attempt < 100; attempt++) {+ requireCurrent();+ const displays = screen.getAllDisplays();+ const display = displays.find((item) => String(item.id) === displayId);+ // An unplugged source has no remaining geometry to restore.+ if (+ released(displays) &&+ (!display ||+ !expected ||+ (display.size.width === expected.width && display.size.height === expected.height))+ )+ return {+ id: displayId,+ name: display?.label || 'Display',+ width: display?.size.width || expected?.width || 0,+ height: display?.size.height || expected?.height || 0,+ };+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ throw new Error('DESKTOP_VIEWER_DISPLAY_UNAVAILABLE');+}+/** The helper owns one temporary mirror, never a global persistent display preference. */export async function createViewerDisplay(sourceDisplayId: string,@@ -162,30 +191,14 @@ export async function createViewerDisplay(},async restore(this: ViewerDisplayHandle, current) {this.dispose();- for (let attempt = 0; attempt < 100; attempt++) {- if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');- const displays = screen.getAllDisplays();- const display = displays.find((item) => String(item.id) === sourceDisplayId);- if (- exited &&- !displays.some((item) => item.id === virtualDisplayId) &&- // If the source was unplugged, virtual-display cleanup is the only- // restoration that remains possible; retire the handle so another- // monitor can be selected on the next lease.- (!display ||- !original ||- (display.size.width === original.size.width &&- display.size.height === original.size.height))- )- return {- id: sourceDisplayId,- name: display?.label || original?.label || 'Display',- width: display?.size.width || original?.size.width || 0,- height: display?.size.height || original?.size.height || 0,- };- await new Promise((resolve) => setTimeout(resolve, 50));- }- throw new Error('DESKTOP_VIEWER_DISPLAY_UNAVAILABLE');+ return waitForDisplayRestore(+ sourceDisplayId,+ original?.size,+ () => {+ if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');+ },+ (displays) => exited && !displays.some((item) => item.id === virtualDisplayId),+ );},dispose() {if (closed) return;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 720f7b4457..27e67ba962 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@@ -29,12 +29,19 @@ afterEach(() => {controller?.dispose();vi.useRealTimers();});-async function fixture(firstControl?: Promise<{ controlling: boolean }>) {+async function fixture(+ firstControl?: Promise<{ controlling: boolean }>,+ resolutionRestore = false,+) {const control = vi.fn(async (enabled: boolean) => ({ controlling: enabled }));if (firstControl) control.mockImplementationOnce(() => firstControl);const heartbeat = vi.fn(async () => ({ controlling: true }));const clipboard = vi.fn(async () => {});- const resolution = vi.fn(async (_modeId: string) => ({}));+ const resolution = vi.fn(async (_modeId: string) => ({+ lease: 'lease',+ controlling: false,+ display: { id: 'one', width: 3840, height: 2160 },+ }));const api = {state: async () => ({generation: 1,@@ -60,6 +67,7 @@ async function fixture(firstControl?: Promise<{ controlling: boolean }>) {canControl: true,viewerDisplay: true,viewerDisplayRestore: true,+ resolutionRestore,clipboardText: true,automaticReconnect: true,displays: [{ id: 'one', name: 'Display', width: 1280, height: 720 }],@@ -105,12 +113,21 @@ const inputEnabled = () =>runtime.receive.mock.calls.filter(([message]) => message.type === 'control').at(-1)?.[0].enabled ?? false;-it('preserves high-resolution system modes through the legacy mode-ID path', async () => {- const f = await fixture();+it('keeps high-resolution system modes on a restorable lease', async () => {+ const f = await fixture(undefined, true);present();await controller.resolution('4k');expect(f.resolution).toHaveBeenCalledWith('4k');- expect(runtime.receive.mock.calls.some(([m]) => m.type === 'videoSettings')).toBe(false);+ expect(+ runtime.receive.mock.calls.some(([m]) => m.type === 'videoSettings' && m.width === 3840),+ ).toBe(true);+});++it('does not silently make a persistent resolution change on an older host', async () => {+ const f = await fixture();+ present();+ await expect(controller.resolution('4k')).rejects.toThrow('DESKTOP_DISPLAY_MODES_UNAVAILABLE');+ expect(f.resolution).not.toHaveBeenCalled();});it('matches the viewer ratio without replacing the lease or resetting input sequence', async () => {diff --git a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts b/apps/desktop/src/renderer/features/remote-desktop/viewerController.tsindex 20a49f261d..e50b8ed419 100644--- a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts@@ -340,23 +340,37 @@ export class DesktopViewerController {async resolution(modeId: string): Promise<void> {const lease = this.session.lease;if (!lease) return;- if (this.state.caps?.viewerDisplay && this.state.caps.viewerDisplayRestore) {+ if (+ this.state.caps?.resolutionRestore ||+ (this.state.caps?.viewerDisplay && this.state.caps.viewerDisplayRestore)+ ) {const mode = (await this.displayModes()).find((item) => item.id === modeId);if (this.session.lease !== lease) return;if (!mode) throw new Error('DESKTOP_DISPLAY_MODE_MISSING');- if ([mode.width, mode.height].every((size) => size >= 320 && size <= 2560)) {- await this.fitDisplay(mode.width, mode.height, true);+ if (+ this.state.caps?.resolutionRestore ||+ [mode.width, mode.height].every((size) => size >= 320 && size <= 2560)+ ) {+ await this.fitDisplay(+ mode.width,+ mode.height,+ true,+ this.state.caps?.resolutionRestore ? mode.id : undefined,+ );return;}}- await this.request({ op: 'resolution', lease: lease.lease, modeId });- this.cancel(true);- this.resuming = false;- void this.connect();+ throw new Error('DESKTOP_DISPLAY_MODES_UNAVAILABLE');}- async fitDisplay(width: number, height: number, exactResolution = false): Promise<void> {+ async fitDisplay(+ width: number,+ height: number,+ exactResolution = false,+ modeId?: string,+ ): Promise<void> {if (exactResolution &&+ !modeId &&![width, height].every((value) => Number.isInteger(value) && value >= 320 && value <= 2560))throw new Error('DESKTOP_DISPLAY_MODE_MISSING');@@ -365,7 +379,7 @@ export class DesktopViewerController {if (!size ||!lease?.controlling ||- !this.state.caps?.viewerDisplay ||+ !(modeId ? this.state.caps?.resolutionRestore : this.state.caps?.viewerDisplay) ||this.state.controlPending)return;@@ -374,7 +388,7 @@ export class DesktopViewerController {this.media.reset();const sourceDisplayId = this.state.displayId;try {- const next = await this.session.fitDisplay(size.width, size.height);+ const next = await this.session.fitDisplay(size.width, size.height, false, modeId);if (this.session.lease !== lease) return;const caps = this.state.caps;this.publish({@@ -389,6 +403,7 @@ export class DesktopViewerController {this.runtime.receive({type: 'videoSettings',...size,+ ...(modeId ? { restore: true } : {}),audio: this.state.settings.audio && this.state.caps?.systemAudio === true,});await this.session.control(true);diff --git a/apps/mobile/src/i18n/locales/en/remoteDesktop.json b/apps/mobile/src/i18n/locales/en/remoteDesktop.jsonindex 1730e08ef1..0b64c4b3e1 100644--- a/apps/mobile/src/i18n/locales/en/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/en/remoteDesktop.json@@ -112,10 +112,10 @@"loadingSettings": "Loading…","retrySettings": "Could not load. Tap to retry.","followComputer": "Follow computer",- "restoreViewerDisplay": "Restore Computer Screen Ratio",- "fitViewerDisplay": "Match Current View",- "fitViewerDisplayHint": "Temporarily adjusts the computer desktop to this view’s aspect ratio, keeping its contents. Disconnect to restore the original resolution.",- "resolutionHint": "Changes the computer’s display resolution and window layout, then briefly reconnects.",+ "restoreViewerDisplay": "Restore Original Resolution",+ "fitViewerDisplay": "Fit to This Screen",+ "fitViewerDisplayHint": "Adjusts the computer resolution to reduce empty space.",+ "resolutionHint": "Resolution changes affect the computer’s window layout. The original resolution is restored on disconnect.","resolutionControlHint": "Take control to change the resolution.","videoSettingsFailed": "Live video is unavailable. Compatibility viewing does not apply frame rate, quality or sound settings. Select a setting again to retry.","settingFailed": "Could not apply the setting. Please retry.",diff --git a/apps/mobile/src/i18n/locales/ja/remoteDesktop.json b/apps/mobile/src/i18n/locales/ja/remoteDesktop.jsonindex 6d09e9e66e..66d79f12d4 100644--- a/apps/mobile/src/i18n/locales/ja/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/ja/remoteDesktop.json@@ -112,10 +112,10 @@"loadingSettings": "読み込み中…","retrySettings": "読み込み失敗。タップして再試行。","followComputer": "パソコンに合わせる",- "restoreViewerDisplay": "パソコン本来の画面比率に戻す",- "fitViewerDisplay": "現在の画面比率に合わせる",- "fitViewerDisplayHint": "デスクトップの内容を保ったまま、パソコンの画面比率を一時的に変更します。切断すると元の解像度に戻ります。",- "resolutionHint": "パソコンの実際の解像度とウィンドウ配置を変更し、一時的に再接続します。",+ "restoreViewerDisplay": "元の解像度に戻す",+ "fitViewerDisplay": "この画面に合わせる",+ "fitViewerDisplayHint": "パソコンの解像度を調整して余白を減らします。",+ "resolutionHint": "解像度の変更はパソコンのウィンドウ配置に影響します。切断すると元の解像度に戻ります。","resolutionControlHint": "解像度を変更するには操作権を取得してください。","videoSettingsFailed": "リアルタイム映像に接続できません。互換表示ではフレームレート・画質・サウンド設定は適用されません。設定を選び直して再試行できます。","settingFailed": "設定を適用できませんでした。再試行してください。",diff --git a/apps/mobile/src/i18n/locales/ko/remoteDesktop.json b/apps/mobile/src/i18n/locales/ko/remoteDesktop.jsonindex 5dd3faedba..cbb04d3e93 100644--- a/apps/mobile/src/i18n/locales/ko/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/ko/remoteDesktop.json@@ -112,10 +112,10 @@"loadingSettings": "불러오는 중…","retrySettings": "불러오지 못했습니다. 눌러서 다시 시도하세요.","followComputer": "컴퓨터에 맞춤",- "restoreViewerDisplay": "컴퓨터의 원래 화면 비율로 복원",- "fitViewerDisplay": "현재 화면 비율에 맞추기",- "fitViewerDisplayHint": "데스크톱 내용을 유지하면서 컴퓨터 화면 비율을 일시적으로 변경합니다. 연결을 종료하면 원래 해상도로 돌아갑니다.",- "resolutionHint": "컴퓨터의 실제 해상도와 창 배치를 변경하고 잠시 다시 연결합니다.",+ "restoreViewerDisplay": "원래 해상도로 복원",+ "fitViewerDisplay": "이 화면에 맞추기",+ "fitViewerDisplayHint": "컴퓨터 해상도를 조정해 여백을 줄입니다.",+ "resolutionHint": "해상도를 변경하면 컴퓨터의 창 배치가 바뀝니다. 연결 종료 시 원래 해상도로 복원됩니다.","resolutionControlHint": "해상도를 변경하려면 제어권을 가져오세요.","videoSettingsFailed": "실시간 영상에 연결하지 못했습니다. 호환 모드에서는 프레임 속도, 화질, 소리가 적용되지 않습니다. 설정을 다시 선택해 재시도하세요.","settingFailed": "설정을 적용하지 못했습니다. 다시 시도하세요.",diff --git a/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json b/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.jsonindex 7632a48280..4f571c56cc 100644--- a/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json@@ -112,10 +112,10 @@"loadingSettings": "读取中…","retrySettings": "读取失败,轻点重试","followComputer": "跟随电脑",- "resolutionHint": "更改电脑实际分辨率,会调整电脑上的窗口布局,并短暂重新连接。",- "restoreViewerDisplay": "恢复电脑原生屏幕比例",- "fitViewerDisplay": "按当前画面比例调整",- "fitViewerDisplayHint": "临时调整电脑桌面比例,保留当前桌面内容。退出连接后恢复原分辨率。",+ "resolutionHint": "调整分辨率会改变电脑上的窗口布局,断开连接后恢复原分辨率。",+ "restoreViewerDisplay": "恢复原分辨率",+ "fitViewerDisplay": "适配此屏幕",+ "fitViewerDisplayHint": "调整电脑分辨率,减少留白。","resolutionControlHint": "接管操作后可以更改分辨率。","videoSettingsFailed": "实时传输未建立,当前使用兼容画面。帧率、画质和声音暂未生效,可重新选择设置重试。","settingFailed": "设置未能应用,请重试。",diff --git a/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json b/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.jsonindex 73e2c51bd0..aaac3ee36e 100644--- a/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json@@ -112,10 +112,10 @@"loadingSettings": "讀取中…","retrySettings": "讀取失敗,輕點重試","followComputer": "跟隨電腦",- "restoreViewerDisplay": "恢復電腦原生螢幕比例",- "fitViewerDisplay": "依目前畫面比例調整",- "fitViewerDisplayHint": "暫時調整電腦桌面比例,保留目前桌面內容。離開連線後恢復原解析度。",- "resolutionHint": "變更電腦實際解析度,會調整電腦上的視窗配置,並短暫重新連線。",+ "restoreViewerDisplay": "恢復原解析度",+ "fitViewerDisplay": "配合此螢幕",+ "fitViewerDisplayHint": "調整電腦解析度,減少留白。",+ "resolutionHint": "調整解析度會改變電腦上的視窗配置,中斷連線後恢復原解析度。","resolutionControlHint": "接管操作後可以變更解析度。","videoSettingsFailed": "即時傳輸未建立,目前使用相容畫面。幀率、畫質與聲音尚未生效,可重新選擇設定重試。","settingFailed": "設定未能套用,請重試。",diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsxindex fde37afe81..4a4df29a39 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx@@ -1,11 +1,14 @@import { Host } from "@expo/ui";-import { Button, RNHostView, VStack } from "@expo/ui/swift-ui";+import type { ComponentProps } from "react";+import { Button, Label, RNHostView, VStack } from "@expo/ui/swift-ui";import {accessibilityAddTraits,accessibilityElement,accessibilityIdentifier,accessibilityLabel,buttonStyle,+ buttonBorderShape,+ controlSize,contentShape,disabled,frame,@@ -13,12 +16,14 @@ import {} from "@expo/ui/swift-ui/modifiers";import { StyleSheet, View } from "react-native";import { useTheme } from "@/theme";+import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";import type { RemoteDesktopActionButtonProps } from "./RemoteDesktopActionButton";export function RemoteDesktopActionButton(props: RemoteDesktopActionButtonProps,) {- const { mode } = useTheme();+ const { mode, colors } = useTheme();+ const liquidGlass = useLiquidGlassAvailable();const state = { pressed: false };const style = StyleSheet.flatten(typeof props.style === "function" ? props.style(state) : props.style,@@ -27,6 +32,41 @@ export function RemoteDesktopActionButton(typeof props.children === "function"? props.children(state): props.children;+ if (props.variant === "glass") {+ // SwiftUI measures its label and glass padding together, without a second+ // padded RNHostView squeezing the text inside a fixed-height button.+ return (+ <Host+ colorScheme={mode}+ seedColor={colors.textPrimary}+ ignoreSafeArea="all"+ matchContents={{ vertical: true }}+ style={{ alignSelf: "stretch", minHeight: 44 }}+ >+ <Button+ onPress={() => {+ if (!props.disabled) props.onPress();+ }}+ modifiers={[+ buttonStyle(liquidGlass ? "glass" : "bordered"),+ buttonBorderShape("capsule"),+ controlSize("large"),+ frame({ maxWidth: Infinity, minHeight: 44 }),+ disabled(Boolean(props.disabled)),+ accessibilityIdentifier(props.testID ?? ""),+ ]}+ >+ <Label+ title={props.accessibilityLabel ?? ""}+ systemImage={+ props.systemImage as ComponentProps<typeof Label>["systemImage"]+ }+ modifiers={[frame({ maxWidth: Infinity, minHeight: 24 })]}+ />+ </Button>+ </Host>+ );+ }return (<View style={style}>{/* Preserve intrinsic text height in Yoga, including larger text and translations. */}diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsxindex 3da114b6d1..7fd407a4b7 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx@@ -10,10 +10,15 @@ export type RemoteDesktopActionButtonProps = Pick<| "accessibilityLabel"| "accessibilityState"| "accessibilityRole"-> & { onPress(): void };+> & { onPress(): void; variant?: "plain" | "glass"; systemImage?: string };export function RemoteDesktopActionButton(props: RemoteDesktopActionButtonProps,) {- return <Pressable {...props} />;+ const {+ variant: _variant,+ systemImage: _systemImage,+ ...pressableProps+ } = props;+ return <Pressable {...pressableProps} />;}diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsxnew file mode 100644index 0000000000..d70e55e613--- /dev/null+++ b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx@@ -0,0 +1,309 @@+import type { ComponentProps } from "react";+import { ScrollView, View, useWindowDimensions } from "react-native";+import { Host } from "@expo/ui";+import {+ BottomSheet,+ Button,+ Group,+ HStack,+ Popover,+ RNHostView,+ Spacer,+ VStack,+} from "@expo/ui/swift-ui";+import {+ accessibilityAddTraits,+ accessibilityElement,+ accessibilityLabel,+ background,+ buttonStyle,+ contentShape,+ disabled,+ frame,+ glassEffect,+ padding,+ presentationDetents,+ presentationDragIndicator,+ shapes,+} from "@expo/ui/swift-ui/modifiers";+import { Keyboard, SlidersHorizontal } from "lucide-react-native";+import { useTranslation } from "react-i18next";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import {+ fontWeight,+ iconSize,+ iconStroke,+ spacing,+ typeScale,+ useTheme,+} from "@/theme";+import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";+import { Text as AppText } from "@/components/AppText";+import { RemoteDesktopPanelButton } from "./RemoteDesktopPanelButton";+import { AllWindowsIcon, ShowDesktopIcon } from "./RemoteDesktopIcons";+import type {+ RemoteDesktopPanel as Panel,+ RemoteDesktopToolbar as Toolbar,+} from "./RemoteDesktopChrome";++// Four 44pt native hit targets with a 4pt inset inside one glass capsule.+const target = 44;+const inset = 4;+const breadth = target + inset * 2;+const length = target * 4 + inset * 2;++export function RemoteDesktopToolbar(props: ComponentProps<typeof Toolbar>) {+ const { colors, mode } = useTheme();+ const { t } = useTranslation();+ const glass = useLiquidGlassAvailable();+ const actions = [+ {+ key: "allWindows",+ Icon: AllWindowsIcon,+ onPress: props.onWindows,+ disabled: !props.canControl,+ selected: false,+ },+ {+ key: "showDesktop",+ Icon: ShowDesktopIcon,+ onPress: props.onDesktop,+ disabled: !props.canControl,+ selected: false,+ },+ {+ key: "keyboard",+ Icon: Keyboard,+ onPress: props.onKeyboard,+ disabled: !props.canControl,+ selected: props.keyboard,+ },+ {+ key: "operations",+ Icon: SlidersHorizontal,+ onPress: props.onOperations,+ disabled: false,+ selected: props.operations,+ },+ ];+ const Stack = props.landscape ? VStack : HStack;+ return (+ <Host+ colorScheme={mode}+ seedColor={colors.textPrimary}+ ignoreSafeArea="all"+ testID="remoteDesktop.toolbar"+ style={{+ width: props.landscape ? breadth : length,+ height: props.landscape ? length : breadth,+ }}+ >+ <Stack+ spacing={0}+ modifiers={[+ padding({ all: inset }),+ ...(glass+ ? [glassEffect({ glass: { variant: "regular" }, shape: "capsule" })]+ : [background(colors.surfaceElevated, shapes.capsule())]),+ ]}+ >+ {(props.landscape ? [...actions].reverse() : actions).map(+ ({ key, Icon, onPress, disabled: unavailable, selected }) => (+ <Button+ key={key}+ onPress={onPress}+ testID={`remoteDesktop.${key}`}+ modifiers={[+ buttonStyle("borderless"),+ disabled(unavailable),+ frame({ width: target, height: target }),+ ...(selected+ ? [background(colors.surfaceChip, shapes.circle())]+ : []),+ accessibilityElement("ignore"),+ accessibilityLabel(t(`remoteDesktop.${key}`)),+ accessibilityAddTraits(+ selected ? ["isButton", "isSelected"] : ["isButton"],+ ),+ ]}+ >+ <VStack+ modifiers={[+ frame({ width: target, height: target }),+ contentShape(shapes.rectangle()),+ ]}+ >+ <RNHostView>+ <View+ pointerEvents="none"+ style={{+ flex: 1,+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <Icon+ size={iconSize.action}+ strokeWidth={iconStroke.regular}+ color={colors.textPrimary}+ />+ </View>+ </RNHostView>+ </VStack>+ </Button>+ ),+ )}+ </Stack>+ </Host>+ );+}++export function RemoteDesktopPanel(props: ComponentProps<typeof Panel>) {+ const { colors, mode } = useTheme();+ const { t } = useTranslation();+ const size = useWindowDimensions();+ const safe = useSafeAreaInsets();+ const visible = props.visible ?? true;+ const toolbarOnLeft = props.toolbarOnLeft ?? false;+ const railTop =+ safe.top + Math.max(0, (size.height - safe.top - safe.bottom - length) / 2);+ // Keep one RN surface for header and body. Changing SwiftUI siblings while+ // it is presented can detach the hosted content; page navigation belongs+ // inside the RN surface, while Sheet/Popover owns presentation only.+ const content = (+ <RNHostView>+ <View+ collapsable={false}+ style={{ flex: 1 }}+ testID="remoteDesktop.panelContentRoot"+ >+ <View+ style={{+ flexDirection: "row",+ alignItems: "center",+ padding: spacing.md,+ gap: spacing.sm,+ }}+ >+ <View style={{ width: target, height: target }}>+ {props.onBack && (+ <RemoteDesktopPanelButton+ back+ label={t("remoteDesktop.back")}+ onPress={props.onBack}+ />+ )}+ </View>+ <View style={{ flex: 1, alignItems: "center" }}>+ <AppText+ accessibilityRole="header"+ style={{+ color: colors.textPrimary,+ fontSize: typeScale.body,+ fontWeight: fontWeight.semibold,+ }}+ >+ {props.title}+ </AppText>+ <AppText+ numberOfLines={1}+ style={{+ color: colors.textPrimary,+ fontSize: typeScale.caption,+ }}+ >+ {props.caption}+ </AppText>+ </View>+ <View style={{ width: target, height: target }} />+ </View>+ <ScrollView+ key={props.page}+ testID="remoteDesktop.panelScroll"+ style={{ flex: 1 }}+ removeClippedSubviews={false}+ keyboardShouldPersistTaps="handled"+ contentContainerStyle={{+ paddingHorizontal: spacing.lg,+ paddingTop: spacing.lg,+ paddingBottom: spacing.lg + (props.landscape ? 0 : safe.bottom),+ gap: spacing.xl,+ }}+ >+ {props.children}+ {props.footer}+ </ScrollView>+ </View>+ </RNHostView>+ );+ const onPresented = (presented: boolean) => {+ if (!presented) props.onClose();+ };+ if (props.landscape)+ return (+ <Host+ key="popover"+ colorScheme={mode}+ seedColor={colors.textPrimary}+ ignoreSafeArea="all"+ pointerEvents="none"+ style={{+ position: "absolute",+ left: toolbarOnLeft ? spacing.lg + inset : undefined,+ right: toolbarOnLeft ? undefined : spacing.lg + inset,+ top: railTop + inset,+ width: target,+ height: target,+ }}+ >+ <Popover+ isPresented={visible}+ onIsPresentedChange={onPresented}+ attachmentAnchor={toolbarOnLeft ? "trailing" : "leading"}+ arrowEdge={toolbarOnLeft ? "leading" : "trailing"}+ >+ <Popover.Trigger>+ <Spacer modifiers={[frame({ width: target, height: target })]} />+ </Popover.Trigger>+ <Popover.Content>+ <Group+ modifiers={[+ frame({+ width: Math.min(+ 360,+ size.width - safe.left - safe.right - breadth - spacing.lg,+ ),+ height: Math.max(+ target,+ size.height - safe.top - safe.bottom - spacing.lg,+ ),+ }),+ ]}+ >+ {content}+ </Group>+ </Popover.Content>+ </Popover>+ </Host>+ );+ return (+ <Host+ key="sheet"+ colorScheme={mode}+ seedColor={colors.textPrimary}+ pointerEvents="none"+ style={{ position: "absolute" }}+ >+ <BottomSheet isPresented={visible} onIsPresentedChange={onPresented}>+ <Group+ modifiers={[+ presentationDetents(["medium", "large"]),+ presentationDragIndicator("visible"),+ ]}+ >+ {content}+ </Group>+ </BottomSheet>+ </Host>+ );+}diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsxindex 3b98f07b58..a63686ef42 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx@@ -126,9 +126,11 @@ export function RemoteDesktopPanel({page,children,footer,+ visible = true,}: {landscape: boolean;topInset: number;+ toolbarOnLeft?: boolean;title: string;caption: string;onClose(): void;@@ -136,10 +138,12 @@ export function RemoteDesktopPanel({page?: string;children: ReactNode;footer?: ReactNode;+ visible?: boolean;}) {const { t } = useTranslation();const { colors } = useTheme();const styles = useThemedStyles(makeStyles);+ if (!visible) return null;return (<Viewstyle={StyleSheet.absoluteFill}@@ -178,10 +182,7 @@ export function RemoteDesktopPanel({{caption}</Text></View>- <RemoteDesktopPanelButton- label={t("remoteDesktop.close")}- onPress={onClose}- />+ <View style={styles.close} /></View><ScrollViewkey={page}diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsxindex 87880a1d83..2cd6d15f8b 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx@@ -526,9 +526,9 @@ const makeStyles = (colors: ThemeColors) =>borderRadius: radius.control,},segment: { flex: 1, minHeight: 44, borderRadius: radius.control },- hint: { color: colors.textTertiary, fontSize: typeScale.caption },+ hint: { color: colors.textPrimary, fontSize: typeScale.caption },group: {- backgroundColor: colors.sheetActionSurface,+ backgroundColor: colors.surfaceTranslucent,borderRadius: radius.container,borderWidth: StyleSheet.hairlineWidth,borderColor: colors.sheetActionBorder,diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsxindex 073ca410ae..815212588a 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx@@ -7,7 +7,7 @@ import {View,} from "react-native";import SegmentedControl from "@expo/ui/community/segmented-control";-import { Check, ChevronDown } from "lucide-react-native";+import { Check, ChevronDown, Maximize, RotateCcw } from "lucide-react-native";import { useTranslation } from "react-i18next";import type {RemoteDesktopDisplayMode,@@ -25,6 +25,7 @@ import {typeScale,iconSize,fontWeight,+ lineHeight,useTheme,} from "@/theme";@@ -81,7 +82,11 @@ export function RemoteDesktopDisplaySettings({}, [connected, video.modesSupported, video.displayGeometry, reload]);const disabled = !connected || !video.supported;const title = { color: colors.textPrimary, fontSize: typeScale.body };- const hint = { color: colors.textTertiary, fontSize: typeScale.caption };+ const hint = {+ color: colors.textPrimary,+ fontSize: typeScale.caption,+ lineHeight: lineHeight.caption,+ };const segment = (label: string, selected: boolean, onPress: () => void) => (<Pressablekey={label}@@ -220,113 +225,157 @@ export function RemoteDesktopDisplaySettings({</Pressable>);return (- <View style={{ gap: spacing.md }}>- <Text style={hint}>{t("remoteDesktop.frameRate")}</Text>- {segmented(- "frameRate",- fpsValues.map((fps) => t("remoteDesktop.fps", { count: fps })),- fpsValues.indexOf(video.settings.fps),- (index) => video.onChange({ fps: fpsValues[index] }),- )}- <Text style={hint}>{t("remoteDesktop.quality")}</Text>- {segmented(- "quality",- ["automatic", "clear", "highDefinition", "original"].map((key) =>- t(`remoteDesktop.${key}`),- ),- qualityValues.indexOf(video.settings.bitrate),- (index) => video.onChange({ bitrate: qualityValues[index] }),- )}- <Text style={hint}>{t("remoteDesktop.qualityHint")}</Text>- <View- style={{- backgroundColor: colors.surfaceChip,- borderRadius: radius.container,- padding: spacing.md,- gap: spacing.sm,- }}- >- {displayControl}- {video.viewerDisplaySupported && (- <View style={{ gap: spacing.xs }}>- <RemoteDesktopActionButton- accessibilityRole="button"- accessibilityLabel={t(- video.viewerDisplayMatched- ? "remoteDesktop.restoreViewerDisplay"- : "remoteDesktop.fitViewerDisplay",- )}- disabled={!connected || !controlling || video.busy}- onPress={() => video.onFitDisplay?.()}- style={[- styles.row,- { opacity: !connected || !controlling || video.busy ? 0.6 : 1 },- ]}- >- <Text style={title}>- {t(+ <View style={{ gap: spacing.xl }}>+ <View style={{ gap: spacing.sm }}>+ <Text style={[title, { fontWeight: fontWeight.medium }]}>+ {t("remoteDesktop.frameRate")}+ </Text>+ {segmented(+ "frameRate",+ fpsValues.map((fps) => t("remoteDesktop.fps", { count: fps })),+ fpsValues.indexOf(video.settings.fps),+ (index) => video.onChange({ fps: fpsValues[index] }),+ )}+ </View>+ <View style={{ gap: spacing.sm }}>+ <Text style={[title, { fontWeight: fontWeight.medium }]}>+ {t("remoteDesktop.quality")}+ </Text>+ {segmented(+ "quality",+ ["automatic", "clear", "highDefinition", "original"].map((key) =>+ t(`remoteDesktop.${key}`),+ ),+ qualityValues.indexOf(video.settings.bitrate),+ (index) => video.onChange({ bitrate: qualityValues[index] }),+ )}+ <Text style={hint}>{t("remoteDesktop.qualityHint")}</Text>+ </View>+ <View style={{ gap: spacing.sm }}>+ <View+ style={{+ backgroundColor: colors.surfaceTranslucent,+ borderRadius: radius.container,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.sheetActionBorder,+ padding: spacing.lg,+ gap: spacing.lg,+ }}+ >+ <View style={{ marginHorizontal: -spacing.md }}>+ {displayControl}+ </View>+ {video.viewerDisplaySupported && (+ <View style={{ gap: spacing.sm }}>+ <RemoteDesktopActionButton+ variant="glass"+ systemImage={+ video.viewerDisplayMatched+ ? "arrow.uturn.backward"+ : "arrow.up.left.and.arrow.down.right"+ }+ accessibilityRole="button"+ accessibilityLabel={t(video.viewerDisplayMatched? "remoteDesktop.restoreViewerDisplay": "remoteDesktop.fitViewerDisplay",)}+ disabled={!connected || !controlling || video.busy}+ onPress={() => video.onFitDisplay?.()}+ style={[+ styles.row,+ {+ backgroundColor:+ Platform.OS === "ios" ? "transparent" : colors.surface,+ borderColor: colors.border,+ borderWidth:+ Platform.OS === "ios" ? 0 : StyleSheet.hairlineWidth,+ borderRadius: radius.pill,+ padding: spacing.md,+ justifyContent: "center",+ opacity: !connected || !controlling || video.busy ? 0.6 : 1,+ },+ ]}+ >+ {video.busy ? (+ <ActivityIndicator size="small" color={colors.textPrimary} />+ ) : video.viewerDisplayMatched ? (+ <RotateCcw size={iconSize.md} color={colors.textPrimary} />+ ) : (+ <Maximize size={iconSize.md} color={colors.textPrimary} />+ )}+ <Text+ style={[+ title,+ { fontWeight: fontWeight.medium, flexShrink: 1 },+ ]}+ >+ {t(+ video.viewerDisplayMatched+ ? "remoteDesktop.restoreViewerDisplay"+ : "remoteDesktop.fitViewerDisplay",+ )}+ </Text>+ </RemoteDesktopActionButton>+ <Text style={hint}>+ {t("remoteDesktop.fitViewerDisplayHint")}</Text>- </RemoteDesktopActionButton>- <Text style={hint}>{t("remoteDesktop.fitViewerDisplayHint")}</Text>- </View>- )}- <View- style={{- height: StyleSheet.hairlineWidth,- backgroundColor: colors.border,- }}- />- {nativeMenu ? (- <NativePullDownMenu- actions={modes.map((mode) => ({- id: mode.id,- title: modeLabel(mode),- state: mode.current ? "on" : "off",- disabled: !controlling || mode.current,- }))}- onAction={chooseMode}- >- {resolutionTrigger}- </NativePullDownMenu>- ) : (- resolutionTrigger- )}- <Text style={hint}>+ </View>+ )}+ <View+ style={{+ height: StyleSheet.hairlineWidth,+ backgroundColor: colors.border,+ }}+ />+ {nativeMenu ? (+ <NativePullDownMenu+ actions={modes.map((mode) => ({+ id: mode.id,+ title: modeLabel(mode),+ state: mode.current ? "on" : "off",+ disabled: !controlling || mode.current,+ }))}+ onAction={chooseMode}+ >+ {resolutionTrigger}+ </NativePullDownMenu>+ ) : (+ resolutionTrigger+ )}+ {!nativeMenu &&+ expanded &&+ modes.map((mode) => (+ <Pressable+ key={mode.id}+ disabled={!controlling || video.busy || mode.current}+ accessibilityRole="radio"+ accessibilityState={{ checked: mode.current }}+ onPress={() => chooseMode(mode.id)}+ style={({ pressed }) => [+ styles.row,+ { opacity: pressed ? 0.6 : !controlling ? 0.4 : 1 },+ ]}+ >+ <Text style={[title, { flex: 1 }]}>{modeLabel(mode)}</Text>+ {mode.current && (+ <Check size={iconSize.md} color={colors.textPrimary} />+ )}+ </Pressable>+ ))}+ {failure && (+ <Text style={hint} accessibilityRole="alert">+ {t("remoteDesktop.retrySettings")}+ </Text>+ )}+ </View>+ <Text style={[hint, { paddingHorizontal: spacing.xs }]}>{t(controlling? "remoteDesktop.resolutionHint": "remoteDesktop.resolutionControlHint",)}</Text>- {!nativeMenu &&- expanded &&- modes.map((mode) => (- <Pressable- key={mode.id}- disabled={!controlling || video.busy || mode.current}- accessibilityRole="radio"- accessibilityState={{ checked: mode.current }}- onPress={() => chooseMode(mode.id)}- style={({ pressed }) => [- styles.row,- { opacity: pressed ? 0.6 : !controlling ? 0.4 : 1 },- ]}- >- <Text style={[title, { flex: 1 }]}>{modeLabel(mode)}</Text>- {mode.current && (- <Check size={iconSize.md} color={colors.textPrimary} />- )}- </Pressable>- ))}- {failure && (- <Text style={hint} accessibilityRole="alert">- {t("remoteDesktop.retrySettings")}- </Text>- )}</View>{!video.supported && (<Text style={hint}>{t("remoteDesktop.settingUnsupported")}</Text>diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsxnew file mode 100644index 0000000000..2dc92a4e15--- /dev/null+++ b/apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx@@ -0,0 +1,144 @@+import { useEffect, useState } from "react";+import { StyleSheet, View, type GestureResponderEvent } from "react-native";+import { GlassView } from "expo-glass-effect";+import Svg, { Path, Rect } from "react-native-svg";+import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";+import { iconStroke, useTheme } from "@/theme";+import { radius } from "@/theme/tokens";+import type { MouseControlsProps } from "./RemoteDesktopMouseControls";++export function RemoteDesktopMouseControls(props: MouseControlsProps) {+ return (+ <View+ pointerEvents="box-none"+ style={[+ StyleSheet.absoluteFill,+ { bottom: props.bottom, right: props.right },+ ]}+ >+ {(["left", "right", "wheel"] as const).map((control) => (+ <MouseControl key={control} {...props} control={control} />+ ))}+ </View>+ );+}++function MouseControl({+ control,+ labels,+ compact,+ send,+}: MouseControlsProps & { control: "left" | "right" | "wheel" }) {+ const { colors, mode } = useTheme();+ const glass = useLiquidGlassAvailable();+ const [pressed, setPressed] = useState(false);+ const wheel = control === "wheel";+ const emit = (event: string, id: number, y: number) =>+ send({ type: "nativeMouse", control, event, id, y });+ // A hidden control must never leave a remote mouse button held down.+ useEffect(+ () => () => {+ send({+ type: "nativeMouse",+ control,+ event: "pointercancel",+ id: 0,+ y: 0,+ });+ },+ [control, send],+ );+ const touch = (event: string) => (e: GestureResponderEvent) => {+ setPressed(event === "pointerdown" || event === "pointermove");+ emit(event, 0, e.nativeEvent.pageY);+ };+ const Surface = glass ? GlassView : View;+ const foreground = pressed ? colors.surface : colors.textPrimary;+ return (+ <View+ accessibilityRole="button"+ accessibilityLabel={labels[control]}+ accessibilityState={{ selected: pressed }}+ accessibilityActions={[{ name: "activate" }]}+ onAccessibilityAction={() => emit("click", 0, 0)}+ onTouchStart={touch("pointerdown")}+ onTouchMove={touch("pointermove")}+ onTouchEnd={touch("pointerup")}+ onTouchCancel={touch("pointercancel")}+ style={[+ styles.control,+ wheel+ ? { right: 12, bottom: compact ? 12 : 80, height: 120 }+ : {+ left: "50%",+ marginLeft: control === "left" ? -96 : 40,+ bottom: 16,+ },+ ]}+ testID={`remoteDesktop.mouse-${control}`}+ >+ <Surface+ {...(glass+ ? {+ glassEffectStyle: "regular" as const,+ isInteractive: true,+ colorScheme: mode,+ }+ : {})}+ pointerEvents="none"+ style={[+ styles.surface,+ {+ backgroundColor: pressed+ ? colors.textPrimary+ : glass+ ? "transparent"+ : colors.surfaceTranslucent,+ },+ ]}+ >+ <Svg+ width={28}+ height={wheel ? 96 : 32}+ viewBox={wheel ? "0 0 24 96" : "0 0 24 32"}+ fill="none"+ stroke={foreground}+ strokeWidth={iconStroke.regular}+ >+ {wheel ? (+ <>+ <Path d="M10 10l2-3 2 3M10 86l2 3 2-3" />+ <Rect x={3} y={31} width={18} height={34} rx={8} />+ <Path d="M5 41h14M4 48h16M5 55h14" />+ </>+ ) : (+ <>+ <Rect x={3} y={2} width={18} height={28} rx={9} />+ <Path d="M12 2v12M3 14h18" />+ <Path+ d={+ control === "left"+ ? "M11 3C6 3 4 6 4 10v3h7Z"+ : "M13 3c5 0 7 3 7 7v3h-7Z"+ }+ fill={foreground}+ stroke="none"+ />+ </>+ )}+ </Svg>+ </Surface>+ </View>+ );+}++const styles = StyleSheet.create({+ control: { position: "absolute", width: 56, height: 56 },+ surface: {+ flex: 1,+ borderRadius: radius.pill,+ overflow: "hidden",+ alignItems: "center",+ justifyContent: "center",+ },+});diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsxnew file mode 100644index 0000000000..ce9a66af88--- /dev/null+++ b/apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx@@ -0,0 +1,11 @@+export type MouseControlsProps = {+ bottom: number;+ right: number;+ compact: boolean;+ labels: Record<"left" | "right" | "wheel", string>;+ send(message: unknown): void;+};++export function RemoteDesktopMouseControls(_props: MouseControlsProps) {+ return null;+}diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsxindex 35ee1ab200..b8387567d3 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx@@ -1,26 +1,22 @@-import { StyleSheet, View } from "react-native";+import { useEffect } from "react";import { useTranslation } from "react-i18next";-import { Text } from "@/components/AppText";-import {- radius,- spacing,- typeScale,- useThemedStyles,- type ThemeColors,-} from "@/theme";+import { spacing, typeScale, useTheme } from "@/theme";import { formatReceiveRate, type DesktopNetworkStats } from "./networkStats";+// Render inside the viewer, between its backdrop and interactive desktop.export function RemoteDesktopNetworkStatus({stats,video,top,+ send,}: {stats: DesktopNetworkStats | null;video: boolean;top: number;+ send: (message: object) => void;}) {const { t } = useTranslation();- const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();const transport = stats?.transport ?? (video ? "video" : "screenshots");const label =!stats && !video@@ -32,37 +28,22 @@ export function RemoteDesktopNetworkStatus({screenshots: "screenshotRelay",}[transport];const latency = stats?.latencyMs;- return (- <View- pointerEvents="none"- style={[styles.badge, { top }]}- testID="remoteDesktop.network"- >- <Text style={styles.text}>{t(`remoteDesktop.${label}`)}</Text>- <Text style={styles.text}>- {`↓ ${formatReceiveRate(stats?.bytesPerSecond ?? null)}`}- {latency != null- ? ` · ${t(`remoteDesktop.${transport === "screenshots" ? "frameTime" : "roundTrip"}`, { ms: Math.round(latency) })}`- : ""}- </Text>- </View>- );-}-const makeStyles = (colors: ThemeColors) =>- StyleSheet.create({- badge: {- position: "absolute",+ const text = `${t(`remoteDesktop.${label}`)}\n${formatReceiveRate(stats?.bytesPerSecond ?? null)}${latency != null ? ` · ${Math.round(latency)} ms` : ""}`;+ useEffect(() => {+ send({+ type: "networkStatus",+ text,+ top,right: spacing.sm,- maxWidth: "75%",- paddingHorizontal: spacing.sm,- paddingVertical: spacing.xs,- borderRadius: radius.control,- backgroundColor: colors.surfaceTranslucent,- },- text: {fontSize: typeScale.caption,- color: colors.textSecondary,- textAlign: "right",- fontVariant: ["tabular-nums"],+ color: colors.textPrimary,+ });+ }, [send, text, top, colors.textPrimary]);+ useEffect(+ () => () => {+ send({ type: "networkStatus", text: "" });},- });+ [send],+ );+ return null;+}diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsxindex 56d28c45bb..73efb9650b 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx@@ -35,6 +35,7 @@ import { controlFailureAction, remoteDesktopErrorCode } from "./controlFailure";import { transferClipboardContent } from "./clipboardTransfer";import * as Clipboard from "expo-clipboard";import { RemoteDesktopClipboardButton } from "./RemoteDesktopClipboardButton";+import { RemoteDesktopMouseControls } from "./RemoteDesktopMouseControls";import { RemoteDesktopPanelButton } from "./RemoteDesktopPanelButton";import { useTranslation } from "react-i18next";import SegmentedControl from "@expo/ui/community/segmented-control";@@ -200,6 +201,12 @@ export default function RemoteDesktopScreen() {});const screenSize = Dimensions.get("screen");const landscape = screenSize.width > screenSize.height;+ const [interfaceAngle, setInterfaceAngle] = useState<number | null>(null);+ const toolbarOnLeft =+ Platform.OS === "ios" &&+ landscape &&+ (interfaceAngle === 270 ||+ (interfaceAngle === null && insets.right > insets.left));const webview = useRef<ComponentRef<typeof WebView>>(null);const html = useRef(remoteDesktopViewerHtml(colors.surface, colors.textPrimary),@@ -302,6 +309,7 @@ export default function RemoteDesktopScreen() {const [nativeKeyboard, setNativeKeyboard] = useState(false);const [nativeKeyboardHeight, setNativeKeyboardHeight] = useState(0);const [keyboardPanelHeight, setKeyboardPanelHeight] = useState(0);+ const [backControlHeight, setBackControlHeight] = useState(44);// Android's system keyboard already resizes the window. Keep its existing// flow layout; only iOS needs an offset above the native keyboard.const landscapeKeyboardOverlay =@@ -1079,6 +1087,7 @@ export default function RemoteDesktopScreen() {useEffect(() => {send({type: "mouseButtons",+ native: Platform.OS === "ios",bottomInset:keyboard && landscapeKeyboardOverlay? keyboardPanelHeight + keyboardBottom@@ -1086,8 +1095,20 @@ export default function RemoteDesktopScreen() {? toolbarSize.height: 0,keyboardOpen: keyboard && landscapeKeyboardOverlay,- rightInset: !keyboard && landscape ? toolbarSize.width : 0,- leftInset: landscape ? insets.left : 0,+ portraitKeyboardTopInset:+ keyboard && !landscape+ ? edgePadding.paddingTop + spacing.xs + backControlHeight + spacing.sm+ : 0,+ rightInset: landscape+ ? !keyboard && !toolbarOnLeft+ ? toolbarSize.width+ : insets.right+ : 0,+ leftInset: landscape+ ? !keyboard && toolbarOnLeft+ ? toolbarSize.width+ : insets.left+ : 0,enabled:showMouseButtons &&focused &&@@ -1102,7 +1123,11 @@ export default function RemoteDesktopScreen() {});}, [showMouseButtons,+ edgePadding.paddingTop,+ backControlHeight,insets.left,+ insets.right,+ toolbarOnLeft,toolbarSize,keyboardPanelHeight,landscapeKeyboardOverlay,@@ -1130,6 +1155,15 @@ export default function RemoteDesktopScreen() {return;}if (!message || typeof message !== "object") return;+ if (+ message.type === "orientation" &&+ typeof message.angle === "number" &&+ Number.isFinite(message.angle)+ ) {+ const angle = ((message.angle % 360) + 360) % 360;+ if ([0, 90, 180, 270].includes(angle)) setInterfaceAngle(angle);+ return;+ }if (message.type === "ready") {ready.current = true;void connectRef.current();@@ -1485,7 +1519,10 @@ export default function RemoteDesktopScreen() {const changeResolution = async (modeId: string) => {const current = active.current;if (!current?.controlling || settingInFlight.current) return;- if (caps?.viewerDisplay && caps.viewerDisplayRestore) {+ if (+ caps?.resolutionRestore ||+ (caps?.viewerDisplay && caps.viewerDisplayRestore)+ ) {try {const modes = await request<import("@cindy/device-link").RemoteDesktopDisplayMode[]@@ -1494,9 +1531,15 @@ export default function RemoteDesktopScreen() {const mode = modes.find((item) => item.id === modeId);if (!mode) throw new Error("DESKTOP_DISPLAY_MODE_MISSING");if (+ caps?.resolutionRestore ||[mode.width, mode.height].every((size) => size >= 320 && size <= 2560)) {- await fitViewerDisplay(mode.width, mode.height, true);+ await fitViewerDisplay(+ mode.width,+ mode.height,+ true,+ caps?.resolutionRestore ? mode.id : undefined,+ );return;}} catch {@@ -1505,33 +1548,18 @@ export default function RemoteDesktopScreen() {return;}}- settingInFlight.current = true;- setSettingBusy(true);- setSettingNotice(null);- try {- await request({ op: "resolution", lease: current.lease, modeId });- if (active.current === current) {- stop(true);- recovery.current.at = Date.now() + 500;- setStatus("reconnecting");- }- } catch (cause) {- // Geometry changes may end the old lease before its reply reaches us.- if (active.current === current)- setSettingNotice(t("remoteDesktop.settingFailed"));- } finally {- settingInFlight.current = false;- setSettingBusy(false);- }+ setSettingNotice(t("remoteDesktop.settingUnsupported"));};const fitViewerDisplay = async (width: number,height: number,exactResolution = false,+ modeId?: string,) => {const current = active.current;if (exactResolution &&+ !modeId &&![width, height].every((value) => Number.isInteger(value) && value >= 320 && value <= 2560,)@@ -1544,7 +1572,7 @@ export default function RemoteDesktopScreen() {: viewerDisplaySize(width, height);if (!current?.controlling ||- !caps?.viewerDisplay ||+ !(modeId ? caps?.resolutionRestore : caps?.viewerDisplay) ||!size ||settingInFlight.current ||settingBusy ||@@ -1561,7 +1589,7 @@ export default function RemoteDesktopScreen() {const restore = Boolean(!exactResolution &&viewerDisplayApplied &&- caps.viewerDisplayRestore &&+ caps?.viewerDisplayRestore &&matchesViewer(current.display, width, height),);const requestGeneration = viewportGeneration.current;@@ -1569,13 +1597,14 @@ export default function RemoteDesktopScreen() {size.width,size.height,restore,+ modeId,);if (active.current !== current) return;// Reconnect the physical source display after the temporary mirror ends.recovery.current.displayId = sourceDisplayId;if (!exactResolution && viewportGeneration.current === requestGeneration)setViewerViewport({ width, height });- setViewerDisplayApplied(!restore);+ setViewerDisplayApplied(!modeId && !restore);setLease({ ...next });streaming.current = false;setCanPip(false);@@ -1583,8 +1612,8 @@ export default function RemoteDesktopScreen() {type: "videoSettings",width: next.display.width,height: next.display.height,- restore,- audio: Boolean(caps.systemAudio && videoSettingsRef.current.audio),+ restore: restore || Boolean(modeId),+ audio: Boolean(caps?.systemAudio && videoSettingsRef.current.audio),});const control = await viewerSession.current.control(true);if (active.current === current)@@ -1766,6 +1795,7 @@ export default function RemoteDesktopScreen() {mediaPlaybackRequiresUserAction={false}allowsPictureInPictureMediaPlaybackscrollEnabled={false}+ contentInsetAdjustmentBehavior="never"bounces={false}allowFileAccess={false}allowUniversalAccessFromFileURLs={false}@@ -1776,6 +1806,30 @@ export default function RemoteDesktopScreen() {style={styles.webview}testID="remoteDesktop.viewer"/>+ {Platform.OS === "ios" &&+ showMouseButtons &&+ focused &&+ !operations &&+ !keyboard &&+ lease?.controlling && (+ <RemoteDesktopMouseControls+ send={send}+ bottom={landscape ? 0 : toolbarSize.height}+ right={+ landscape+ ? !toolbarOnLeft+ ? toolbarSize.width+ : insets.right+ : 0+ }+ compact={screenSize.height <= 400}+ labels={{+ left: t("remoteDesktop.leftClick"),+ right: t("remoteDesktop.rightClick"),+ wheel: t("remoteDesktop.mouseWheel"),+ }}+ />+ )}{(showConnectionStatus ||showExitLockStatus ||(!lease && error)) && (@@ -1859,23 +1913,32 @@ export default function RemoteDesktopScreen() {)}{lease && !showConnectionStatus && !operations && !landscape && (<RemoteDesktopNetworkStatus+ send={send}stats={network}video={status === "live"}top={edgePadding.paddingTop + spacing.sm}/>)}- {operations && (+ {(operations || Platform.OS === "ios") && (<ViewpointerEvents="box-none"style={[StyleSheet.absoluteFill,{- bottom: landscape ? 0 : toolbarSize.height,- right: landscape ? toolbarSize.width : 0,+ bottom:+ Platform.OS === "ios" || landscape ? 0 : toolbarSize.height,+ right:+ Platform.OS === "ios"+ ? 0+ : landscape+ ? toolbarSize.width+ : 0,},]}><RemoteDesktopPanel+ toolbarOnLeft={toolbarOnLeft}+ visible={operations && focused}landscape={landscape}topInset={edgePadding.paddingTop}title={t(@@ -1972,6 +2035,9 @@ export default function RemoteDesktopScreen() {</View>{!keyboard && (<View+ key={landscape ? "landscape-toolbar" : "portrait-toolbar"}+ testID="remoteDesktop.toolbarPosition"+ pointerEvents="box-none"onLayout={({ nativeEvent: { layout } }) => {setToolbarSize((previous) =>previous.width === layout.width &&@@ -1988,6 +2054,31 @@ export default function RemoteDesktopScreen() {paddingLeft: landscape ? 0 : edgePadding.paddingLeft,paddingBottom: keyboard || nativeKeyboard ? 0 : insets.bottom,},+ Platform.OS === "ios" && {+ backgroundColor: "transparent",+ ...(landscape+ ? {+ top: insets.top,+ bottom: insets.bottom,+ left: toolbarOnLeft ? 0 : undefined,+ right: toolbarOnLeft ? undefined : 0,+ justifyContent: "center",+ paddingLeft: toolbarOnLeft ? spacing.lg : 0,+ paddingRight: toolbarOnLeft ? 0 : spacing.lg,+ paddingBottom: 0,+ }+ : {+ left: 0,+ right: 0,+ top: undefined,+ bottom: 0,+ alignItems: "center",+ justifyContent: "center",+ paddingLeft: 0,+ paddingRight: 0,+ paddingBottom: Math.max(spacing.sm, insets.bottom),+ }),+ },]}><RemoteDesktopToolbar@@ -2025,22 +2116,33 @@ export default function RemoteDesktopScreen() {</View>)}</View>- {!landscape && (- <View- style={[- styles.back,- {- top: edgePadding.paddingTop + spacing.xs,- left: edgePadding.paddingLeft + spacing.lg,- },- ]}- >- <RemoteDesktopBackButton- label={t("remoteDesktop.back")}- onPress={leave}- />- </View>- )}+ <View+ testID="remoteDesktop.backPosition"+ pointerEvents="auto"+ onLayout={({ nativeEvent: { layout } }) =>+ setBackControlHeight(layout.height)+ }+ style={[+ styles.back,+ {+ top: landscape+ ? insets.top + spacing.lg+ : edgePadding.paddingTop + spacing.xs,+ // Keep the 44pt control out of the island: follow the rail when it+ // is on the left, otherwise start after the left safe inset.+ left: landscape+ ? (toolbarOnLeft ? 0 : insets.left) ++ spacing.lg ++ (Platform.OS === "ios" ? spacing.xs : 0)+ : edgePadding.paddingLeft + spacing.lg,+ },+ ]}+ >+ <RemoteDesktopBackButton+ label={t("remoteDesktop.back")}+ onPress={leave}+ />+ </View>{keyboard && (<ViewtestID="remoteDesktop.keyboardPanel"diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsxindex 7e788a29c5..af71932a26 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx@@ -34,7 +34,7 @@ export function RemoteDesktopSecuritySettings() {const { t } = useTranslation();const { colors } = useTheme();- const hint = { color: colors.textTertiary, fontSize: typeScale.caption };+ const hint = { color: colors.textPrimary, fontSize: typeScale.caption };const switchSlot = {width: 56,minHeight: 44,@@ -63,7 +63,7 @@ export function RemoteDesktopSecuritySettings(<><Viewstyle={{- backgroundColor: colors.sheetActionSurface,+ backgroundColor: colors.surfaceTranslucent,borderColor: colors.sheetActionBorder,borderWidth: StyleSheet.hairlineWidth,borderRadius: radius.container,@@ -165,7 +165,7 @@ export function RemoteDesktopSecuritySettings(<Viewstyle={{...row,- backgroundColor: colors.sheetActionSurface,+ backgroundColor: colors.surfaceTranslucent,borderColor: colors.sheetActionBorder,borderWidth: StyleSheet.hairlineWidth,borderRadius: radius.container,diff --git a/apps/mobile/src/remote-desktop/__tests__/nativeChrome.test.tsx b/apps/mobile/src/remote-desktop/__tests__/nativeChrome.test.tsxnew file mode 100644index 0000000000..7484563b7a--- /dev/null+++ b/apps/mobile/src/remote-desktop/__tests__/nativeChrome.test.tsx@@ -0,0 +1,271 @@+// @vitest-environment jsdom+import { act, type ReactNode } from "react";+import { createRoot } from "react-dom/client";+import { expect, it, vi } from "vitest";+import {+ RemoteDesktopPanel,+ RemoteDesktopToolbar,+} from "../RemoteDesktopChrome.ios";++const state = vi.hoisted(() => ({+ presentation: null as any,+ glass: true,+ safe: { top: 0, bottom: 21, left: 62, right: 0 },+}));+vi.mock("react-native", async () => {+ const { createElement } = await import("react");+ const View = ({ children, testID, style }: any) =>+ createElement("div", { "data-testid": testID, style }, children);+ return {+ View,+ ScrollView: View,+ useWindowDimensions: () => ({ width: 874, height: 402 }),+ };+});+vi.mock("@expo/ui", async () => ({+ Host: (await import("react-native")).View,+}));+vi.mock("@/components/AppText", async () => ({+ Text: (await import("react-native")).View,+}));+vi.mock("../RemoteDesktopPanelButton", () => ({+ RemoteDesktopPanelButton: ({ label, onPress }: any) => (+ <button onClick={onPress}>{label}</button>+ ),+}));+vi.mock("@expo/ui/swift-ui", async () => {+ const { createElement } = await import("react");+ const View = (await import("react-native")).View;+ const presentation = (kind: string) => (props: any) => {+ state.presentation = { ...props, kind };+ return props.isPresented ? createElement(View, null, props.children) : null;+ };+ return {+ HStack: View,+ VStack: View,+ Group: View,+ Spacer: () => null,+ Text: View,+ RNHostView: View,+ Button: ({ children, label, onPress, testID, modifiers = [] }: any) =>+ createElement(+ "button",+ {+ onClick: onPress,+ "data-testid": testID,+ "aria-label": label,+ disabled: modifiers.some(+ (m: any) => m.name === "disabled" && m.value,+ ),+ },+ children,+ ),+ BottomSheet: presentation("sheet"),+ Popover: Object.assign(presentation("popover"), {+ Trigger: () => null,+ Content: View,+ }),+ };+});+vi.mock("@expo/ui/swift-ui/modifiers", () =>+ Object.fromEntries(+ [+ "accessibilityAddTraits",+ "accessibilityElement",+ "accessibilityLabel",+ "background",+ "buttonBorderShape",+ "buttonStyle",+ "contentShape",+ "disabled",+ "font",+ "foregroundStyle",+ "frame",+ "glassEffect",+ "labelStyle",+ "onGeometryChange",+ "padding",+ "presentationDetents",+ "presentationDragIndicator",+ ]+ .map((name) => [name, (value: unknown) => ({ name, value })])+ .concat([+ ["shapes", { capsule: vi.fn(), circle: vi.fn(), rectangle: vi.fn() }],+ ] as any),+ ),+);+vi.mock("lucide-react-native", () => ({+ Keyboard: () => null,+ SlidersHorizontal: () => null,+}));+vi.mock("../RemoteDesktopIcons", () => ({+ AllWindowsIcon: () => null,+ ShowDesktopIcon: () => null,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("react-native-safe-area-context", () => ({+ useSafeAreaInsets: () => state.safe,+}));+vi.mock("@/theme", () => ({+ iconSize: { action: 24 },+ typeScale: { body: 16, caption: 12 },+ iconStroke: { regular: 2 },+ fontWeight: { semibold: "600" },+ spacing: { xs: 4, sm: 8, md: 12, lg: 16, xl: 24 },+ useTheme: () => ({+ mode: "dark",+ colors: {+ textPrimary: "#fff",+ textSecondary: "#aaa",+ surfaceElevated: "#222",+ surfaceChip: "#333",+ },+ }),+}));+vi.mock("@/session/useLiquidGlassAvailable", () => ({+ useLiquidGlassAvailable: () => state.glass,+}));++function mount(element: ReactNode) {+ const host = document.createElement("div");+ const root = createRoot(host);+ act(() => root.render(element));+ return {+ host,+ render: (next: ReactNode) => act(() => root.render(next)),+ close: () => act(() => root.unmount()),+ };+}++it("keeps operations usable without control, with compact landscape order", () => {+ const operations = vi.fn();+ const desktop = vi.fn();+ const v = mount(+ <RemoteDesktopToolbar+ landscape+ canControl={false}+ keyboard={false}+ operations={false}+ onWindows={vi.fn()}+ onDesktop={desktop}+ onKeyboard={vi.fn()}+ onOperations={operations}+ />,+ );+ const buttons = [...v.host.querySelectorAll("button")];+ expect(buttons.map((b) => b.dataset.testid)).toEqual([+ "remoteDesktop.operations",+ "remoteDesktop.keyboard",+ "remoteDesktop.showDesktop",+ "remoteDesktop.allWindows",+ ]);+ act(() => {+ buttons[0].click();+ buttons[2].click();+ });+ expect(operations).toHaveBeenCalledOnce();+ expect(desktop).not.toHaveBeenCalled();+ v.close();+});++it.each([false, true])(+ "keeps one hosted surface while navigating and updating the header (landscape=%s)",+ (landscape) => {+ const props = {+ landscape,+ visible: true,+ topInset: 0,+ title: "Settings",+ caption: "Computer",+ onClose: vi.fn(),+ };+ const v = mount(+ <RemoteDesktopPanel {...props} page="controls">+ <span>Controls</span>+ </RemoteDesktopPanel>,+ );+ let root = v.host.querySelector(+ '[data-testid="remoteDesktop.panelContentRoot"]',+ );+ expect(root).not.toBeNull();+ const presentation = v.host.firstElementChild;+ const scroll = v.host.querySelector(+ '[data-testid="remoteDesktop.panelScroll"]',+ );+ for (const page of ["display", "security", "controls"]) {+ v.render(+ <RemoteDesktopPanel+ {...props}+ page={page}+ onBack={page === "controls" ? undefined : vi.fn()}+ >+ <span>{page}</span>+ </RemoteDesktopPanel>,+ );+ const next = v.host.querySelector(+ '[data-testid="remoteDesktop.panelContentRoot"]',+ );+ expect(next).toBe(root);+ root = next;+ expect(root?.textContent).toContain(page);+ expect(v.host.firstElementChild).toBe(presentation);+ expect(state.presentation.isPresented).toBe(true);+ expect(props.onClose).not.toHaveBeenCalled();+ }+ expect(+ v.host.querySelector('[data-testid="remoteDesktop.panelScroll"]'),+ ).not.toBe(scroll);+ v.close();+ },+);++it("switches presentation on rotation and routes system dismissal to the owner", () => {+ const onClose = vi.fn();+ const props = {+ topInset: 0,+ title: "Operations",+ caption: "Computer",+ onClose,+ children: <span>Settings</span>,+ };+ const v = mount(<RemoteDesktopPanel {...props} visible landscape={false} />);+ expect(state.presentation.kind).toBe("sheet");+ expect(v.host.textContent).toContain("Settings");+ v.render(<RemoteDesktopPanel {...props} visible landscape />);+ expect(state.presentation.kind).toBe("popover");+ act(() => state.presentation.onIsPresentedChange(false));+ expect(onClose).toHaveBeenCalledOnce();+ v.render(<RemoteDesktopPanel {...props} visible={false} landscape />);+ expect(v.host.textContent).not.toContain("Settings");+ v.close();+});++it("anchors the popover to the centered rail and opens inward after either rotation", () => {+ const props = {+ landscape: true,+ visible: true,+ topInset: 0,+ title: "Operations",+ caption: "Computer",+ onClose: vi.fn(),+ children: <span>Controls</span>,+ };+ const v = mount(<RemoteDesktopPanel {...props} />);+ for (const islandRight of [false, true, false]) {+ state.safe = { top: 0, bottom: 21, left: 62, right: 62 };+ v.render(<RemoteDesktopPanel {...props} toolbarOnLeft={islandRight} />);+ const anchor = v.host.firstElementChild as HTMLElement;+ expect(anchor.style.top).toBe("102.5px");+ expect(anchor.style.left).toBe(islandRight ? "20px" : "");+ expect(anchor.style.right).toBe(islandRight ? "" : "20px");+ expect(state.presentation.attachmentAnchor).toBe(+ islandRight ? "trailing" : "leading",+ );+ expect(state.presentation.arrowEdge).toBe(+ islandRight ? "leading" : "trailing",+ );+ }+ v.close();+});diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex 5b9d9b0fc8..ff09947576 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -39,6 +39,7 @@ vi.mock("../useLockOnExitPreference", () => ({const fixture = vi.hoisted(() => ({nativeMenus: false,+ safe: { top: 59, bottom: 34, left: 0, right: 0 },securityAutoUnlock: false,securityBusy: false,themeMode: "light",@@ -144,7 +145,7 @@ vi.mock("expo-router", () => ({}));vi.mock("@/utils/backGuard", () => ({ goBackGuarded: vi.fn() }));vi.mock("react-native-safe-area-context", () => ({- useSafeAreaInsets: () => ({ top: 59, bottom: 34, left: 0, right: 0 }),+ useSafeAreaInsets: () => fixture.safe,}));vi.mock("react-i18next", () => {const t = (key: string) => key;@@ -217,6 +218,7 @@ vi.mock("lucide-react-native", () => ({Check: () => null,ClipboardList: () => null,ChevronDown: () => null,+ RotateCcw: () => null,ChevronRight: () => null,Eye: () => null,LogOut: () => null,@@ -306,6 +308,7 @@ beforeEach(() => {(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;vi.clearAllMocks();fixture.platform = "ios";+ fixture.safe = { top: 59, bottom: 34, left: 0, right: 0 };fixture.hostPlatform = "darwin";fixture.deviceId = "computer";fixture.securityAutoUnlock = false;@@ -604,7 +607,7 @@ describe("remote desktop controls", () => {act(() => button()?.click());expect(onFitDisplay).toHaveBeenCalledOnce();});- it("keeps 4K system resolution selectable on viewer-display hosts", async () => {+ it("changes 4K system resolution on a restorable lease without reconnecting", async () => {const original = fixture.invoke.getMockImplementation()!;fixture.invoke.mockImplementation(async (...args) => {const request = args[2][0];@@ -613,11 +616,18 @@ describe("remote desktop controls", () => {...(await original(...args)),viewerDisplay: true,viewerDisplayRestore: true,+ resolutionRestore: true,videoSettings: true,displayModes: true,};if (request.op === "displayModes")return [{ id: "4k", width: 3840, height: 2160, current: false }];+ if (request.op === "resolution")+ return {+ lease: "lease",+ display: { id: "display", width: 3840, height: 2160 },+ controlling: false,+ };return original(...args);});await connect();@@ -633,10 +643,19 @@ describe("remote desktop controls", () => {op: "resolution",lease: "lease",modeId: "4k",+ temporary: true,});expect(requests().some((request) => request.op === "viewerDisplay")).toBe(false,);+ expect(requests().some((request) => request.op === "stop")).toBe(false);+ expect(sent()).toContainEqual(+ expect.objectContaining({+ type: "videoSettings",+ width: 3840,+ restore: true,+ }),+ );});it("changes portrait resolution without stopping the temporary display and stops it on exit", async () => {@@ -1324,6 +1343,118 @@ describe("remote desktop controls", () => {).toMatchObject({ audio: true });expect(host.textContent).not.toContain("remoteDesktop.audioUnavailable");});+ it("moves the centered rail opposite the island in both landscape directions", async () => {+ fixture.size = { width: 874, height: 402 };+ for (const islandRight of [false, true, false]) {+ fixture.safe = { top: 0, bottom: 21, left: 62, right: 62 };+ act(() => root.render(<RemoteDesktopScreen />));+ act(() =>+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "orientation",+ angle: islandRight ? -90 : 90,+ }),+ },+ }),+ );+ const rail = fixture.views["remoteDesktop.toolbarPosition"];+ const style = Object.assign(+ {},+ ...rail.style.flat(Infinity).filter(Boolean),+ );+ expect(style).toMatchObject({+ top: 0,+ bottom: 21,+ justifyContent: "center",+ paddingBottom: 0,+ });+ expect(style.left).toBe(islandRight ? 0 : undefined);+ expect(style.right).toBe(islandRight ? undefined : 0);+ expect(style.paddingLeft).toBe(islandRight ? 16 : 0);+ expect(style.paddingRight).toBe(islandRight ? 0 : 16);+ act(() =>+ rail.onLayout({ nativeEvent: { layout: { width: 68, height: 381 } } }),+ );+ expect(+ sent()+ .filter((m) => m.type === "mouseButtons")+ .at(-1),+ ).toMatchObject({+ leftInset: islandRight ? 68 : 62,+ rightInset: islandRight ? 62 : 68,+ });+ }+ });+ it("keeps the landscape back button clear of the left safe area", async () => {+ fixture.size = { width: 874, height: 402 };+ fixture.safe = { top: 0, bottom: 21, left: 62, right: 62 };+ for (const islandRight of [false, true]) {+ act(() => root.render(<RemoteDesktopScreen />));+ act(() =>+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "orientation",+ angle: islandRight ? -90 : 90,+ }),+ },+ }),+ );+ const style = Object.assign(+ {},+ ...fixture.views["remoteDesktop.backPosition"].style+ .flat(Infinity)+ .filter(Boolean),+ );+ expect(style.left).toBe(islandRight ? 20 : 82);+ }+ });+ it("restores a centered bottom toolbar after a full rotation without remounting the viewer", async () => {+ await connect();+ const viewer = host.querySelector('[data-testid="remoteDesktop.viewer"]');+ const firstToolbar = host.querySelector(+ '[data-testid="remoteDesktop.toolbarPosition"]',+ );+ for (const angle of [90, 180, 270, 0]) {+ const landscape = angle === 90 || angle === 270;+ fixture.size = landscape+ ? { width: 874, height: 402 }+ : { width: 402, height: 874 };+ fixture.safe = landscape+ ? { top: 0, bottom: 21, left: 62, right: 62 }+ : { top: 59, bottom: 34, left: 0, right: 0 };+ act(() => {+ root.render(<RemoteDesktopScreen />);+ fixture.message!({+ nativeEvent: { data: JSON.stringify({ type: "orientation", angle }) },+ });+ });+ if (!landscape) {+ const style = Object.assign(+ {},+ ...fixture.views["remoteDesktop.toolbarPosition"].style+ .flat(Infinity)+ .filter(Boolean),+ );+ expect(style).toMatchObject({+ left: 0,+ right: 0,+ bottom: 0,+ alignItems: "center",+ paddingLeft: 0,+ paddingRight: 0,+ });+ expect(style.top).toBeUndefined();+ }+ expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).toBe(+ viewer,+ );+ }+ expect(+ host.querySelector('[data-testid="remoteDesktop.toolbarPosition"]'),+ ).not.toBe(firstToolbar);+ });it("overlays landscape keyboards and includes their measured occlusion", async () => {fixture.size = { width: 844, height: 390 };act(() => root.render(<RemoteDesktopScreen />));@@ -1615,10 +1746,13 @@ describe("remote desktop controls", () => {latencyMs: 42,});const badge = () =>- host.querySelector('[data-testid="remoteDesktop.network"]')!.textContent;+ sent()+ .filter((m) => m.type === "networkStatus")+ .at(-1)?.text;expect(badge()).toContain("remoteDesktop.directConnection");expect(badge()).toContain("125 KB/s");- expect(badge()).toContain("remoteDesktop.roundTrip");+ expect(badge()).toContain("42 ms");+ expect(badge()).not.toContain("↓");message({type: "network",epoch: "old-lease",@@ -1628,7 +1762,7 @@ describe("remote desktop controls", () => {expect(badge()).toContain("remoteDesktop.directConnection");await act(async () => vi.advanceTimersByTimeAsync(6000));expect(badge()).toContain("— KB/s");- expect(badge()).not.toContain("remoteDesktop.roundTrip");+ expect(badge()).not.toContain("roundTrip");message({ type: "fallback", epoch: "lease" });message({type: "network",@@ -1650,15 +1784,27 @@ describe("remote desktop controls", () => {await act(async () => vi.advanceTimersByTimeAsync(8000));expect(requests().filter((r) => r.op === "start")).toHaveLength(1);expect(requests().some((r) => r.op === "stop")).toBe(false);- expect(host.textContent).toContain("remoteDesktop.connecting");- expect(host.textContent).not.toContain("remoteDesktop.screenshotRelay");+ expect(+ sent()+ .filter((m) => m.type === "networkStatus")+ .at(-1)?.text,+ ).toContain("remoteDesktop.connecting");+ expect(+ sent()+ .filter((m) => m.type === "networkStatus")+ .at(-1)?.text,+ ).not.toContain("remoteDesktop.screenshotRelay");fixture.invoke.mockImplementation((...args) =>args[2][0].op === "frame"? Promise.resolve({ jpeg: "a".repeat(4000) }): original(...args),);await act(async () => vi.advanceTimersByTimeAsync(1000));- expect(host.textContent).toContain("remoteDesktop.screenshotRelay");+ expect(+ sent()+ .filter((m) => m.type === "networkStatus")+ .at(-1)?.text,+ ).toContain("remoteDesktop.screenshotRelay");expect(requests().filter((r) => r.op === "start")).toHaveLength(1);});it.each([false, true])(@@ -1701,11 +1847,13 @@ describe("remote desktop controls", () => {await connect();await act(async () => vi.advanceTimersByTimeAsync(1000));const badge = () =>- host.querySelector('[data-testid="remoteDesktop.network"]')!.textContent;+ sent()+ .filter((m) => m.type === "networkStatus")+ .at(-1)?.text;expect(badge()).toContain("remoteDesktop.screenshotRelay");expect(badge()).toContain("6 KB/s");- expect(badge()).toContain("remoteDesktop.frameTime");- expect(badge()).not.toContain("remoteDesktop.roundTrip");+ expect(badge()).toMatch(/ · \d+ ms/);+ expect(badge()).not.toContain("roundTrip");fixture.invoke.mockImplementation((...args) =>args[2][0].op === "frame"? Promise.resolve({ jpeg: null })@@ -2308,7 +2456,15 @@ describe("remote desktop controls", () => {const viewer = host.querySelector('[data-testid="remoteDesktop.viewer"]');fixture.size = { width: 844, height: 390 };act(() => root.render(<RemoteDesktopScreen />));- expect(button("back")).toBeNull();+ expect(button("back")).not.toBeNull();+ for (const angle of [90, -90]) {+ act(() =>+ fixture.message!({+ nativeEvent: { data: JSON.stringify({ type: "orientation", angle }) },+ }),+ );+ expect(button("back").disabled).toBe(false);+ }fixture.size = { width: 390, height: 844 };act(() => root.render(<RemoteDesktopScreen />));expect(button("back")).not.toBeNull();diff --git a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewer.test.tsindex f2aca442f0..bcbc06f0ce 100644--- a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts+++ b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts@@ -16,7 +16,7 @@ const desktopTransform = vm.runInNewContext(fillHeight?: boolean,) => { x: number; y: number; width: number; height: number; scale: number };-function viewer() {+function viewer(rtc = false, frameCallback = true) {const messages: Array<{type: string;epoch: string;@@ -32,6 +32,9 @@ function viewer() {"keyboard-input","image","video",+ "bg",+ "bg-canvas",+ "network-status","cursor","cursor-image","mouse-buttons",@@ -45,12 +48,14 @@ function viewer() {].map((id) => [id,{+ id,clientWidth: 400,clientHeight: 600,style: {} as Record<string, string>,addEventListener: (name: string, handler: (e: unknown) => void) => {listeners[`${id}:${name}`] = handler;},+ textContent: "",value: "",focus() {},blur() {},@@ -62,14 +67,80 @@ function viewer() {},]),);+ const bgDraws: unknown[][] = [];+ const bgContext = {+ setTransform() {},+ clearRect() {},+ drawImage: (...args: unknown[]) => {+ bgDraws.push(args);+ },+ };+ (+ elements as unknown as Record<+ string,+ {+ getContext?: () => unknown;+ naturalWidth?: number;+ naturalHeight?: number;+ }+ >+ )["bg-canvas"].getContext = () => bgContext;+ (+ elements as unknown as Record<+ string,+ {+ getContext?: () => unknown;+ naturalWidth?: number;+ naturalHeight?: number;+ }+ >+ )["image"].naturalWidth = 1920;+ (+ elements as unknown as Record<+ string,+ {+ getContext?: () => unknown;+ naturalWidth?: number;+ naturalHeight?: number;+ }+ >+ )["image"].naturalHeight = 1080;const intervals: Array<() => void> = [];const frames = new Map<number, () => void>();+ const videoFrames = new Map<number, () => void>();let id = 0;+ const video = Object.assign(elements.video, {+ videoWidth: 1920,+ videoHeight: 1080,+ readyState: 2,+ onplaying: null as null | (() => void),+ requestVideoFrameCallback: frameCallback+ ? (fn: () => void) => {+ videoFrames.set(++id, fn);+ return id;+ }+ : undefined,+ cancelVideoFrameCallback: (key: number) => videoFrames.delete(key),+ });+ class Peer {+ localDescription = { sdp: "offer" };+ createDataChannel() {+ return { close() {} };+ }+ addTransceiver() {}+ async createOffer() {+ return { sdp: "offer" };+ }+ async setLocalDescription() {}+ close() {}+ }let now = 0;+ let orientation: number | undefined;const source = remoteDesktopViewerHtml("#fff", "#111").match(/<script>([\s\S]*)<\/script>/,)![1];vm.runInNewContext(source, {+ RTCPeerConnection: Peer,Date: { now: () => now },performance: { now: () => now },matchMedia: () => ({ matches: false }),@@ -82,6 +153,10 @@ function viewer() {documentElement: { style: { setProperty() {} } },},window: {+ RTCPeerConnection: rtc ? Peer : undefined,+ get orientation() {+ return orientation;+ },ReactNativeWebView: {postMessage: (text: string) => messages.push(JSON.parse(text)),},@@ -105,6 +180,21 @@ function viewer() {return {messages,elements,+ bgDraws,+ videoFrames,+ playVideo: () => {+ const config = messages.findLast((m) => m.type === "iceConfig");+ windowListeners.message({+ data: JSON.stringify({ ...config, iceServers: [] }),+ });+ video.onplaying!();+ },+ videoFrame: () => {+ const pending = [...videoFrames.values()];+ videoFrames.clear();+ pending.forEach((fn) => fn());+ },+ timeupdate: () => listeners["video:timeupdate"]({}),send: (message: object) =>windowListeners.message({ data: JSON.stringify(message) }),flush: () => intervals.forEach((fn) => fn()),@@ -142,6 +232,10 @@ function viewer() {}),});},+ rotate: (angle: number) => {+ orientation = angle;+ windowListeners.orientationchange({});+ },blur: () => windowListeners.blur({}),key: (type: string, code: string) =>documentListeners[type]({ code, preventDefault() {} }),@@ -245,6 +339,28 @@ describe("remote desktop viewport", () => {expect(v.messages).toHaveLength(count);expect(v.elements["mouse-buttons"].style.display).toBe("none");});+ it("shares held-button and wheel input with native glass controls", () => {+ const v = viewer();+ v.send({ type: "control", enabled: true });+ v.send({ type: "mouseButtons", enabled: true, native: true });+ const input = (control: string, event: string, y = 100) =>+ v.send({ type: "nativeMouse", control, event, id: 0, y });+ expect(v.elements["mouse-buttons"].style.display).toBe("none");+ input("left", "pointerdown");+ v.ack();+ input("left", "pointercancel");+ v.ack();+ input("wheel", "pointerdown");+ input("wheel", "pointermove", 80);+ v.flush();+ v.ack();+ input("wheel", "pointercancel");+ expect(v.messages.flatMap((m) => m.events ?? [])).toEqual([+ { kind: "button", button: 0, down: true, x: 0.5, y: 0.5 },+ { kind: "button", button: 0, down: false, x: 0.5, y: 0.5 },+ { kind: "scroll", dx: 0, dy: -24 },+ ]);+ });it("scrolls by dragging the wheel and cancels without an extra step", () => {const v = viewer();v.send({ type: "control", enabled: true });@@ -663,3 +779,302 @@ describe("remote desktop viewport", () => {).toBe(true);});});++it("reports both landscape directions even when viewport dimensions stay identical", () => {+ const v = viewer();+ v.elements.stage.clientWidth = 874;+ v.elements.stage.clientHeight = 402;+ for (const angle of [90, -90, 90]) {+ v.rotate(angle);+ expect(v.messages.at(-1)).toMatchObject({ type: "orientation", angle });+ }+});++describe("portrait keyboard positioning", () => {+ it.each([48, 96, 128])(+ "centers below %s points of top controls and restores after closing",+ (topInset) => {+ const v = viewer();+ v.send({ type: "init", epoch: "keyboard", width: 1920, height: 1080 });+ v.frame();+ const originalTop = parseFloat(v.elements.image.style.top);+ const originalWidth = v.elements.image.style.width;+ v.send({ type: "mouseButtons", portraitKeyboardTopInset: topInset });+ for (let i = 0; i < 30; i++) v.frame(20);+ expect(parseFloat(v.elements.image.style.top)).toBeCloseTo(+ originalTop + topInset / 2,+ );+ expect(v.elements.image.style.width).toBe(originalWidth);+ v.send({ type: "mouseButtons", portraitKeyboardTopInset: 0 });+ for (let i = 0; i < 30; i++) v.frame(20);+ expect(parseFloat(v.elements.image.style.top)).toBeCloseTo(originalTop);+ },+ );+ it("limits the offset to available space below the desktop", () => {+ const v = viewer();+ v.elements.stage.clientHeight = 240;+ v.send({ type: "init", epoch: "keyboard", width: 1920, height: 1080 });+ v.send({ type: "mouseButtons", portraitKeyboardTopInset: 96 });+ for (let i = 0; i < 30; i++) v.frame(20);+ expect(+ parseFloat(v.elements.image.style.top) ++ parseFloat(v.elements.image.style.height),+ ).toBeCloseTo(240);+ });+});++describe("remote desktop network status layer", () => {+ it("updates plain text and theme styling and clears when dismissed", () => {+ const v = viewer();+ v.send({+ type: "networkStatus",+ text: "Direct\n11 KB/s · 1 ms",+ top: 60,+ right: 8,+ fontSize: 12,+ color: "#737373",+ });+ const status = v.elements["network-status"];+ expect(status.textContent).toBe("Direct\n11 KB/s · 1 ms");+ expect(status.style).toMatchObject({+ display: "block",+ top: "60px",+ right: "8px",+ fontSize: "12px",+ color: "#737373",+ });+ v.send({ type: "networkStatus", text: "<img src=x>", color: "#a3a3a3" });+ expect(status.textContent).toBe("<img src=x>");+ expect(status.style.color).toBe("#a3a3a3");+ v.send({ type: "networkStatus", text: "" });+ expect(status.style.display).toBe("none");+ });++ it("places transparent status above the backdrop but below the desktop", () => {+ const html = remoteDesktopViewerHtml("#fff", "#111");+ const rule = html.match(/#network-status\{([^}]+)\}/)![1];+ expect(rule).toContain("z-index:1");+ expect(rule).toContain("pointer-events:none");+ expect(rule).not.toContain("background");+ expect(html).toContain("#image{z-index:2}");+ expect(html).toContain('id="network-status"');+ });+});++describe("remote desktop three-segment backdrop", () => {+ it.each([true, false])(+ "only repaints live video on media progress (frame callbacks: %s)",+ (callback) => {+ const v = viewer(true, callback);+ v.send({+ type: "init",+ epoch: "bg",+ width: 1920,+ height: 1080,+ trickleIce: true,+ });+ v.playVideo();+ v.videoFrame();+ v.frame();+ v.frame();+ v.frame();+ v.bgDraws.length = 0;+ for (let i = 0; i < 120; i++) v.frame();+ expect(v.bgDraws).toHaveLength(0);+ if (callback) v.videoFrame();+ else {+ v.timeupdate();+ v.frame();+ }+ expect(v.bgDraws).toHaveLength(3);+ expect(v.bgDraws[0][0]).toBe(v.elements.video);+ const stale = [...v.videoFrames.values()][0];+ v.send({ type: "stop" });+ v.frame();+ v.bgDraws.length = 0;+ stale?.();+ v.timeupdate();+ v.frame();+ expect(v.videoFrames.size).toBe(0);+ expect(v.bgDraws).toHaveLength(0);+ },+ );++ it("cancels hidden background callbacks and resumes after the stage changes", () => {+ const v = viewer(true);+ v.send({+ type: "init",+ epoch: "bg",+ width: 1920,+ height: 1080,+ trickleIce: true,+ });+ v.playVideo();+ v.videoFrame();+ v.frame();+ v.frame();+ v.frame();+ expect(v.videoFrames.size).toBe(1);+ const stale = [...v.videoFrames.values()][0];+ v.elements.stage.clientWidth = 1920;+ v.elements.stage.clientHeight = 1080;+ v.send({ type: "viewport", fillHeight: false });+ v.bgDraws.length = 0;+ stale();+ v.frame();+ expect(v.bgDraws).toHaveLength(0);+ expect(v.videoFrames.size).toBe(0);+ v.elements.stage.clientWidth = 400;+ v.send({ type: "viewport", fillHeight: false });+ v.frame();+ expect(v.bgDraws).toHaveLength(3);+ expect(v.videoFrames.size).toBe(1);+ v.send({ type: "stop" });+ });+ function landscapeViewer() {+ const v = viewer();+ v.elements.stage.clientWidth = 874;+ v.elements.stage.clientHeight = 402;+ v.send({ type: "init", epoch: "bg", width: 1920, height: 1080 });+ v.frame();+ return v;+ }+ type Draw = [+ unknown,+ number,+ number,+ number,+ number,+ number,+ number,+ number,+ number,+ ];+ const drawsOf = (v: ReturnType<typeof viewer>) => v.bgDraws as Draw[];+ const expectDest = (+ draw: Draw,+ x: number,+ y: number,+ w: number,+ h: number,+ ) => {+ expect(draw[5]).toBeCloseTo(x, 6);+ expect(draw[6]).toBeCloseTo(y, 6);+ expect(draw[7]).toBeCloseTo(w, 6);+ expect(draw[8]).toBeCloseTo(h, 6);+ };+ const expectSrc = (+ draw: Draw,+ x: number,+ y: number,+ w: number,+ h: number,+ ) => {+ expect(draw[1]).toBeCloseTo(x, 6);+ expect(draw[2]).toBeCloseTo(y, 6);+ expect(draw[3]).toBeCloseTo(w, 6);+ expect(draw[4]).toBeCloseTo(h, 6);+ };+ const px = (id: string, prop: string, v: ReturnType<typeof viewer>) =>+ parseFloat(v.elements[id].style[prop]);++ it("fills side bars with stretched edges around an undistorted center", () => {+ const v = landscapeViewer();+ expect(v.elements.bg.style.display).toBe("block");+ const scale = 402 / 1080;+ const fitWidth = 1920 * scale;+ const centerW = fitWidth * 0.9;+ const side = 874 / 2 - centerW / 2;+ expect(px("image", "width", v)).toBeCloseTo(fitWidth, 2);+ expect(px("image", "left", v)).toBeCloseTo((874 - fitWidth) / 2, 2);+ expect(drawsOf(v)).toHaveLength(3);+ expectDest(drawsOf(v)[0], 0, 0, side, 402);+ expectSrc(drawsOf(v)[0], 0, 0, 96, 1080);+ expectDest(drawsOf(v)[1], side, 0, centerW, 402);+ expectSrc(drawsOf(v)[1], 96, 0, 1728, 1080);+ expectDest(drawsOf(v)[2], side + centerW, 0, side, 402);+ expectSrc(drawsOf(v)[2], 1824, 0, 96, 1080);+ expect(side + centerW + side).toBeCloseTo(874, 2);+ });++ it("fills both safe areas and the toolbar while the picture respects side insets", () => {+ const v = landscapeViewer();+ v.bgDraws.length = 0;+ v.send({ type: "viewport", fillHeight: true });+ v.send({+ type: "mouseButtons",+ enabled: true,+ leftInset: 56,+ rightInset: 68,+ });+ v.frame();+ const fitWidth = 1920 * (402 / 1080);+ const vw = 874 - 56 - 68;+ const centerW = fitWidth * 0.9;+ const side = 874 / 2 - centerW / 2;+ expect(px("image", "left", v)).toBeCloseTo(56 + (vw - fitWidth) / 2, 2);+ expect(drawsOf(v)).toHaveLength(3);+ expectDest(drawsOf(v)[0], 0, 0, side, 402);+ expectDest(drawsOf(v)[1], side, 0, centerW, 402);+ expect(drawsOf(v)[2][5]).toBeCloseTo(side + centerW, 6);+ expect(drawsOf(v)[2][8]).toBeCloseTo(402, 6);+ expect(side + centerW + side).toBeCloseTo(874, 2);+ });++ it("stretches top and bottom bars around an undistorted center in portrait", () => {+ const v = viewer();+ v.send({ type: "init", epoch: "bg", width: 1920, height: 1080 });+ v.frame();+ expect(v.elements.bg.style.display).toBe("block");+ const scale = 400 / 1920;+ const fitHeight = 1080 * scale;+ const centerH = fitHeight * 0.9;+ const side = 600 / 2 - centerH / 2;+ expect(px("image", "height", v)).toBeCloseTo(fitHeight, 2);+ expect(px("image", "top", v)).toBeCloseTo((600 - fitHeight) / 2, 2);+ expect(drawsOf(v)).toHaveLength(3);+ expectDest(drawsOf(v)[0], 0, 0, 400, side);+ expectSrc(drawsOf(v)[0], 0, 0, 1920, 54);+ expectDest(drawsOf(v)[1], 0, side, 400, centerH);+ expectSrc(drawsOf(v)[1], 0, 54, 1920, 972);+ expectDest(drawsOf(v)[2], 0, side + centerH, 400, side);+ expectSrc(drawsOf(v)[2], 0, 1026, 1920, 54);+ expect(side + centerH + side).toBeCloseTo(600, 2);+ });++ it("hides the backdrop when the fitted picture covers the whole stage", () => {+ const v = landscapeViewer();+ v.bgDraws.length = 0;+ v.send({ type: "init", epoch: "bg-wide", width: 2560, height: 1080 });+ v.send({ type: "viewport", fillHeight: true });+ v.frame();+ expect(v.elements.bg.style.display).toBe("none");+ expect(drawsOf(v)).toHaveLength(0);+ });++ it("draws JPEG fallback frames into the backdrop canvas", () => {+ const v = landscapeViewer();+ v.bgDraws.length = 0;+ v.send({ type: "frame", jpeg: "QUJD" });+ (v.elements.image as unknown as { onload?: () => void }).onload?.();+ v.frame();+ expect(v.messages.at(-1)?.type).toBe("framePresented");+ expect(drawsOf(v)).toHaveLength(3);+ for (const draw of drawsOf(v)) expect(draw[0]).toBe(v.elements.image);+ });++ it("fills side bars for a portrait desktop on a landscape stage", () => {+ const v = viewer();+ v.elements.stage.clientWidth = 800;+ v.elements.stage.clientHeight = 400;+ v.send({ type: "init", epoch: "bg", width: 1080, height: 1920 });+ v.frame();+ const fitWidth = 1080 * (400 / 1920);+ const centerW = fitWidth * 0.9;+ const side = 800 / 2 - centerW / 2;+ expect(v.elements.bg.style.display).toBe("block");+ expect(drawsOf(v)).toHaveLength(3);+ expectDest(drawsOf(v)[1], side, 0, centerW, 400);+ expect(side + centerW + side).toBeCloseTo(800, 2);+ });+});diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex f3bce5ed5b..4f57fb8b82 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -9,7 +9,7 @@本区块由 `scripts/design-inventory.mjs` 生成,请勿手改。重新生成:`pnpm design:inventory`;校验:`pnpm check:design-inventory`。-计数快照日期:2026-09-16。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。+计数快照日期:2026-09-17。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。登记 surface 数:50。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。@@ -62,7 +62,7 @@| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HtmlFileReader, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 202 | 36 || `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 56 || `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, DeviceLinkContext, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 13 |-| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopIcons, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 41 |+| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 42 || `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 18 || `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 22 |diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex fe9b2e2cf4..eee1c96bfe 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -11,6 +11,18 @@> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。+## 远程桌面临时分辨率++被控端以可选能力 `resolutionRestore` 声明系统分辨率的连接级恢复支持。+新版控制端仅在该能力为真时发送 `resolution { temporary: true }`;响应为原 lease+及更新后的显示器尺寸、`controlling: false`,控制端刷新画面并重新取得操作权,不结束连接。+被控端在首次调整前保存原模式,多次调整不覆盖;结束、超时、撤权或接管后先恢复,+恢复失败保留原值,下次连接前重试。在途原生写入完成前不得开始恢复。++旧被控端缺少该能力时,新控制端只允许已有 `viewerDisplayRestore` 能力覆盖的临时调整,+不得退回会留下系统分辨率变化的旧路径;不支持的选择返回“不支持”。旧控制端的无+`temporary` 请求及响应保持兼容,其旧行为不代表新恢复能力已生效。此扩展不修改 relay。+## 自动化检查恢复投影运行状态和已读回执保留历史事实。当前警告只保留未被**同一自动化**更新成功运行恢复的失败;@@ -25,14 +37,14 @@## 事实来源-| 内容 | 权威来源 |-|---|---|-| hook 双工任务协议 | 客户端 `packages/slack-hook-protocol`;服务端仓同名本地 package,desktop hook-control 与 slack/telegram/x hook server 分别消费本仓实现 |-| device-link relay 层定义 | 客户端 `packages/device-link-protocol`;服务端仓同名本地 package,客户端重连、IPC allowlist、隧道 payload 在 `packages/device-link` |-| Plugin 交付与 manifest | 客户端 `packages/plugin-protocol`;服务端仓同名本地 package,desktop、`packages/cindy-tools` 与 plugin-server 分别消费本仓实现 |-| 模型目录 | 客户端由 `packages/model-providers/src/modelAccessBean.ts` 与 `modelAccessValidator.ts` 维护;model-access-server 在服务端仓维护对应 Bean/validator,双方只共享稳定 wire 语义,不共享实现 |-| Skill Hub | Desktop 的 `apps/desktop/src/main/skillhub` 与 `shared/skillhubCatalog.ts`;服务端仓 `packages/skill-hub-protocol` 与 `cindy-skill-hub-server` |-| 插件来源 | 客户端不预装插件;一律通过 SkillHub 或用户手动安装 `.cindy` 包 |+| 内容 | 权威来源 |+| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| hook 双工任务协议 | 客户端 `packages/slack-hook-protocol`;服务端仓同名本地 package,desktop hook-control 与 slack/telegram/x hook server 分别消费本仓实现 |+| device-link relay 层定义 | 客户端 `packages/device-link-protocol`;服务端仓同名本地 package,客户端重连、IPC allowlist、隧道 payload 在 `packages/device-link` |+| Plugin 交付与 manifest | 客户端 `packages/plugin-protocol`;服务端仓同名本地 package,desktop、`packages/cindy-tools` 与 plugin-server 分别消费本仓实现 |+| 模型目录 | 客户端由 `packages/model-providers/src/modelAccessBean.ts` 与 `modelAccessValidator.ts` 维护;model-access-server 在服务端仓维护对应 Bean/validator,双方只共享稳定 wire 语义,不共享实现 |+| Skill Hub | Desktop 的 `apps/desktop/src/main/skillhub` 与 `shared/skillhubCatalog.ts`;服务端仓 `packages/skill-hub-protocol` 与 `cindy-skill-hub-server` |+| 插件来源 | 客户端不预装插件;一律通过 SkillHub 或用户手动安装 `.cindy` 包 |## 1. 两仓本地协议演进@@ -217,7 +229,6 @@ X 快照有请求正文时,按原始 triggerMessageId 排除引用列表中的协议改动按 [`desktop-development.md`](desktop-development.md) 跑相关测试,并与服务端确认兼容。-## Model Registry V3:权威协议与旧端下发- 权威协议位于 `model-registry.json` 的逐模型 `nativeApi`,与窗口、参考价和输出上限同目录维护。`nativeApiRules` 仅按指定 providerId + modelIdPrefix 覆盖未来家族成员;精确声明优先,显式 null 表示待核实,退役项禁止继承家族规则。跨厂商不根据同名猜测。@@ -235,14 +246,14 @@ X 快照有请求正文时,按原始 triggerMessageId 排除引用列表中的核实后写入 Registry,不在 UI 中反推 Pi 配置。Gateway 的 `perAgent.pi.wireProtocol`仅是末级执行提示,不能覆盖本地已声明的原生协议,也不能填充 UI 的原生协议字段。-| 已核对的本地模型家族 | Cindy 原生协议基线 | 本地参考 |-| --- | --- | --- |-| Claude、MiniMax | Anthropic Messages | Pi 原生 provider 表、现有 Cindy 直连配置 |-| GPT、Grok | OpenAI Responses | Pi 原生 provider 表、现有 Cindy 直连配置 |-| Gemini | Google Gemini | Pi 原生 Google provider 表 |-| DeepSeek、Qwen、Kimi、GLM | Chat Completions | Pi 本地目录对应 provider;不使用同名聚合商条目 |-| 腾讯 HY | Chat Completions | Cindy 原有 HY3 协议声明;Pi HY4 的协议记录交叉核对 |-| Muse Spark | OpenAI Responses | Cindy 原有 Muse Spark 1.2 声明;Pi 同型号协议记录交叉核对 |+| 已核对的本地模型家族 | Cindy 原生协议基线 | 本地参考 |+| ------------------------- | ------------------ | --------------------------------------------------------- |+| Claude、MiniMax | Anthropic Messages | Pi 原生 provider 表、现有 Cindy 直连配置 |+| GPT、Grok | OpenAI Responses | Pi 原生 provider 表、现有 Cindy 直连配置 |+| Gemini | Google Gemini | Pi 原生 Google provider 表 |+| DeepSeek、Qwen、Kimi、GLM | Chat Completions | Pi 本地目录对应 provider;不使用同名聚合商条目 |+| 腾讯 HY | Chat Completions | Cindy 原有 HY3 协议声明;Pi HY4 的协议记录交叉核对 |+| Muse Spark | OpenAI Responses | Cindy 原有 Muse Spark 1.2 声明;Pi 同型号协议记录交叉核对 |新增家族规则仅匹配指定 provider 路由与命名空间,不能扩到任意 BYOM 或同名聚合商。精确条目可覆盖家族规则。当前本地维护的 Registry 条目均有显式协议声明;diff --git a/packages/device-link/src/__tests__/viewerDisplay.test.ts b/packages/device-link/src/__tests__/viewerDisplay.test.tsindex 4b98889626..5fa65ed8b9 100644--- a/packages/device-link/src/__tests__/viewerDisplay.test.ts+++ b/packages/device-link/src/__tests__/viewerDisplay.test.ts@@ -66,6 +66,29 @@ describe("viewer display dimensions", () => {}),).toEqual({ op: "resolution", lease: "lease", modeId: "123" });});+ it("validates the opt-in flag without changing legacy resolution requests", () => {+ expect(+ parseRemoteDesktopRequest({+ op: "resolution",+ lease: "lease",+ modeId: "1",+ temporary: true,+ }),+ ).toEqual({+ op: "resolution",+ lease: "lease",+ modeId: "1",+ temporary: true,+ });+ expect(() =>+ parseRemoteDesktopRequest({+ op: "resolution",+ lease: "lease",+ modeId: "1",+ temporary: "true",+ }),+ ).toThrow("INVALID_REQUEST");+ });it("updates the existing viewer lease and starts control on the new display", async () => {const request = vi.fn(async (value) => {if (value.op === "capabilities")@@ -89,6 +112,12 @@ describe("viewer display dimensions", () => {display: { id: "2", width: value.width, height: value.height },controlling: false,};+ if (value.op === "resolution")+ return {+ lease: "lease",+ display: { id: "1", width: 3840, height: 2160 },+ controlling: false,+ };return {};});const session = new RemoteDesktopViewerSession(@@ -115,5 +144,13 @@ describe("viewer display dimensions", () => {height: 1440,});expect(session.lease?.controlling).toBe(false);+ await session.control(true);+ await session.fitDisplay(3840, 2160, false, "123");+ expect(request).toHaveBeenLastCalledWith(+ { op: "resolution", lease: "lease", modeId: "123", temporary: true },+ expect.any(Function),+ );+ expect(session.lease).toBe(previous);+ expect(session.lease?.display.width).toBe(3840);});});diff --git a/packages/device-link/src/remoteDesktop.ts b/packages/device-link/src/remoteDesktop.tsindex 88ee2b19a3..7661d7ea8b 100644--- a/packages/device-link/src/remoteDesktop.ts+++ b/packages/device-link/src/remoteDesktop.ts@@ -131,6 +131,8 @@ export interface RemoteDesktopCapabilities {trickleIce?: boolean;systemAudio?: boolean;displayModes?: boolean;+ /** System mode changes can keep the lease and restore on disconnect. */+ resolutionRestore?: boolean;/** Can temporarily lay out the desktop at the viewer's requested dimensions. */viewerDisplay?: boolean;viewerDisplayRestore?: boolean;@@ -185,7 +187,7 @@ export type RemoteDesktopRequest =| { op: "displayModes"; lease: string }| { op: "viewerDisplay"; lease: string; width: number; height: number }| { op: "restoreViewerDisplay"; lease: string }- | { op: "resolution"; lease: string; modeId: string };+ | { op: "resolution"; lease: string; modeId: string; temporary?: boolean };export function parseRemoteDesktopRequest(value: unknown,@@ -289,8 +291,16 @@ export function parseRemoteDesktopRequest(v.op === "resolution" &&typeof v.modeId === "string" &&/^[0-9]{1,10}$/.test(v.modeId)- )- return { op: v.op, lease, modeId: v.modeId };+ ) {+ if (v.temporary !== undefined && typeof v.temporary !== "boolean")+ throw new Error("INVALID_REQUEST");+ return {+ op: v.op,+ lease,+ modeId: v.modeId,+ ...(v.temporary === true ? { temporary: true } : {}),+ };+ }if (v.op === "offer" && typeof v.sdp === "string" && v.sdp.length <= 64_000) {if (v.cursorOverlay !== undefined && typeof v.cursorOverlay !== "boolean")throw new Error("INVALID_REQUEST");diff --git a/packages/device-link/src/remoteDesktopViewerSession.ts b/packages/device-link/src/remoteDesktopViewerSession.tsindex be70efd11e..c0b32a5110 100644--- a/packages/device-link/src/remoteDesktopViewerSession.ts+++ b/packages/device-link/src/remoteDesktopViewerSession.ts@@ -164,6 +164,7 @@ export class RemoteDesktopViewerSession {width: number,height: number,restore = false,+ modeId?: string,): Promise<RemoteDesktopLease> {const lease = this.active;if (!lease?.controlling) throw new Error("DESKTOP_VIEW_ONLY");@@ -173,9 +174,11 @@ export class RemoteDesktopViewerSession {if (this.active !== lease) throw new Error("DESKTOP_LEASE_EXPIRED");};const operation = this.request<RemoteDesktopLease>(- restore- ? { op: "restoreViewerDisplay", lease: lease.lease }- : { op: "viewerDisplay", lease: lease.lease, width, height },+ modeId+ ? { op: "resolution", lease: lease.lease, modeId, temporary: true }+ : restore+ ? { op: "restoreViewerDisplay", lease: lease.lease }+ : { op: "viewerDisplay", lease: lease.lease, width, height },check,);this.controlPending = operation;diff --git a/packages/maker-shared/src/remote-desktop/mobileHtml.ts b/packages/maker-shared/src/remote-desktop/mobileHtml.tsindex 0f2a5a320c..50bec4ffa8 100644--- a/packages/maker-shared/src/remote-desktop/mobileHtml.ts+++ b/packages/maker-shared/src/remote-desktop/mobileHtml.ts@@ -9,10 +9,16 @@ export function remoteDesktopViewerHtml(const color = (v: string) =>/^#[0-9a-f]{3,8}$/i.test(v) ? v : "transparent";return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; media-src blob:; connect-src 'none'"><style>- *{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:${color(surface)};touch-action:none;overscroll-behavior:none}#stage{position:absolute;inset:0;overflow:hidden;z-index:0}video,img{position:absolute;max-width:none;pointer-events:none;transform-origin:0 0}video{display:none;z-index:0}#cursor{position:absolute;z-index:3;width:18px;height:18px;border:2px solid ${color(foreground)};border-radius:50%;pointer-events:none;display:none;transform:translate(-50%,-50%)}+ *{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:${color(surface)};touch-action:none;overscroll-behavior:none}#stage{position:absolute;inset:0;overflow:hidden;z-index:0}#bg{position:absolute;inset:0;overflow:hidden;z-index:0;display:none}#bg-canvas{position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none}video,img{position:absolute;max-width:none;pointer-events:none;transform-origin:0 0}video{display:none;z-index:0}#cursor{position:absolute;z-index:3;width:18px;height:18px;border:2px solid ${color(foreground)};border-radius:50%;pointer-events:none;display:none;transform:translate(-50%,-50%)}+ /* Overscan the ambient layer so blur cannot expose a clear strip at screen edges. */+ #bg-canvas{filter:blur(16px);transform:scale(1.12);transform-origin:center;opacity:.72}+ #network-status{position:absolute;z-index:1;display:none;pointer-events:none;max-width:75%;white-space:pre-line;text-align:right;font-family:-apple-system,BlinkMacSystemFont,sans-serif;font-variant-numeric:tabular-nums;font-weight:400;color:var(--foreground)}#cursor-image{position:absolute;inset:0;width:100%;height:100%}#stage,#stage *{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-user-drag:none}- video,img{border:0;outline:0}#image{z-index:1}img:not([src]){visibility:hidden}+ video,img{border:0;outline:0}#image{z-index:2}img:not([src]){visibility:hidden}+ /* The JPEG stays beneath live video; cast one soft shadow, never two. */+ :root{--desktop-picture-shadow:0 0 10px rgba(0,0,0,.16)}+ #image,#image:not([src])~#video{box-shadow:var(--desktop-picture-shadow)}:root{--surface:${color(surface)};--foreground:${color(foreground)}}#keyboard-input{position:absolute;left:0;bottom:0;width:1px;height:1px;opacity:.01;font-size:16px;pointer-events:none;border:0;padding:0;resize:none}#mouse-buttons{position:absolute;inset:0;pointer-events:none;display:none;color:var(--foreground);opacity:.85}@@ -26,7 +32,7 @@ export function remoteDesktopViewerHtml(#mouse-wheel>*{pointer-events:none}#mouse-wheel-grip{width:20px;height:34px}@media(max-height:400px){#mouse-wheel{bottom:12px}}- </style></head><body><div id="stage"><img id="image" alt=""><video id="video" autoplay muted playsinline></video><div id="cursor"><img id="cursor-image" alt=""></div></div>+ </style></head><body><div id="stage"><div id="bg"><canvas id="bg-canvas"></canvas></div><div id="network-status"></div><img id="image" alt=""><video id="video" autoplay muted playsinline></video><div id="cursor"><img id="cursor-image" alt=""></div></div><div id="mouse-buttons">${(["left", "right"] as const).map((button) => `<button type="button" id="mouse-${button}" class="mouse-button" aria-pressed="false"><svg viewBox="0 0 24 32" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="2" width="18" height="28" rx="9"/><path d="M12 2v12M3 14h18"/><path d="${button === "left" ? "M11 3C6 3 4 6 4 10v3h7Z" : "M13 3c5 0 7 3 7 7v3h-7Z"}" fill="currentColor" stroke="none"/></svg></button>`).join("")}<button type="button" id="mouse-wheel"><span aria-hidden="true">▴</span><svg id="mouse-wheel-grip" viewBox="0 0 20 34" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="1" y="1" width="18" height="32" rx="8"/><path d="M3 10h14M2 17h16M3 24h14"/></svg><span aria-hidden="true">▾</span></button>diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.jsindex d169e93d4f..0edf6d182d 100644--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.js+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js@@ -105,6 +105,12 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {image = find("image"),video = find("video"),cursor = find("cursor");+ // Ambient three-segment backdrop (mobile markup only; desktop keeps its+ // solid surface because its stage has no #bg subtree, so every entry may+ // be missing and all backdrop work below must tolerate that).+ const bg = find("bg") || null,+ bgCanvas = find("bg-canvas") || null,+ bgContext = bgCanvas ? bgCanvas.getContext("2d") : null;let dw = 1920,dh = 1080,viewerSized = false,@@ -144,6 +150,12 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {const mouseButtons = find("mouse-buttons"),wheel = find("mouse-wheel"),wheelGrip = find("mouse-wheel-grip");+ let nativeMouseControls = false;+ const mouseControlHandlers = new Map();+ function listenMouse(el, type, handler) {+ listen(el, type, handler);+ mouseControlHandlers.set(el.id + ":" + type, handler);+ }const keyboardInput = find("keyboard-input");let keyboardEnabled = false,composing = false;@@ -225,7 +237,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {viewportRightInset = 0,viewportLeftInset = 0,viewportBottomInset = 0,- keyboardViewportInset = 0;+ keyboardViewportInset = 0,+ portraitKeyboardTopInset = 0;let keyboardViewportOpen = false;let cursorNeedsEntry = true,manualViewMoved = false,@@ -242,6 +255,16 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {viewportLeft() -(fillHeight ? viewportRightInset : 0),);+ // Center between the measured top controls and the keyboard edge (stage bottom).+ // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.+ // Keep the fitted size and cap the shift when the desktop is too tall to fit.+ const verticalOffset = (height) =>+ fillHeight+ ? 0+ : Math.min(+ portraitKeyboardTopInset / 2,+ Math.max(0, (viewportHeight() - height) / 2),+ );const layout = () => {const r = transform(viewportWidth(),@@ -256,9 +279,197 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {return {...r,x: viewportLeft() + viewportWidth() / 2 - fx * r.width,- y: viewportHeight() / 2 - fy * r.height,+ y: viewportHeight() / 2 + verticalOffset(r.height) - fy * r.height,};};+ // The backdrop uses 5% / 90% / 5% source segments. The middle 90%+ // keeps the fitted picture's scale; each outer 5% stretches uniformly+ // to fill the remaining space, horizontally or vertically as needed.+ // Zoom and pan never move the backdrop: where the picture covers it, the+ // opaque picture simply occludes it, so input mapping stays uniform. Returns+ // null when the fitted picture already covers the stage (nothing to fill).+ const bgEdgeFraction = 0.05;+ const bgCenterFraction = 1 - 2 * bgEdgeFraction;+ function backgroundSegments(vw, vh, dw, dh, fill) {+ if (!(vw > 0 && vh > 0 && dw > 0 && dh > 0)) return null;+ const s = fill+ ? vh / Math.max(1, dh)+ : Math.min(vw / dw, vh / Math.max(1, dh));+ const w = dw * s,+ h = dh * s;+ if (w < vw) {+ const centerW = w * bgCenterFraction,+ centerX = vw / 2 - centerW / 2,+ sideW = centerX,+ top = (vh - h) / 2;+ return { axis: "x", s, w, h, top, centerW, centerX, sideW };+ }+ if (h < vh) {+ const centerH = h * bgCenterFraction,+ centerY = vh / 2 - centerH / 2,+ sideH = centerY,+ left = (vw - w) / 2;+ return { axis: "y", s, w, h, left, centerH, centerY, sideH };+ }+ return null;+ }+ function paintBackground() {+ if (!bg || !bgCanvas || !bgContext) return;+ const vw = stage.clientWidth,+ vh = stage.clientHeight;+ const seg = backgroundSegments(vw, vh, dw, dh, fillHeight);+ if (!seg) {+ bg.style.display = "none";+ bgRects = null;+ stopBackgroundLoop();+ return;+ }+ bg.style.display = "block";+ bgAxis = seg.axis;+ // The ambient layer also fills the notch and the area beneath native+ // controls. Only the interactive picture respects viewport insets.+ const originX = 0;+ // Source segments are resolved at draw time from the live source dimensions;+ // these dest rects only encode where each segment lands on the stage.+ bgRects =+ seg.axis === "x"+ ? [+ {+ x: originX,+ y: seg.top,+ w: seg.sideW,+ h: seg.h,+ },+ {+ x: originX + seg.centerX,+ y: seg.top,+ w: seg.centerW,+ h: seg.h,+ },+ {+ x: originX + seg.centerX + seg.centerW,+ y: seg.top,+ w: seg.sideW,+ h: seg.h,+ },+ ]+ : [+ {+ x: seg.left,+ y: 0,+ w: seg.w,+ h: seg.sideH,+ },+ {+ x: seg.left,+ y: seg.centerY,+ w: seg.w,+ h: seg.centerH,+ },+ {+ x: seg.left,+ y: seg.centerY + seg.centerH,+ w: seg.w,+ h: seg.sideH,+ },+ ];+ // Keep the backing store at stage resolution (capped) so the stretched+ // edges stay crisp without oversized allocations.+ bgDpr = Math.min(2, window.devicePixelRatio || 1);+ const bw = Math.round(stage.clientWidth * bgDpr),+ bh = Math.round(vh * bgDpr);+ if (bgCanvas.width !== bw || bgCanvas.height !== bh) {+ bgCanvas.width = bw;+ bgCanvas.height = bh;+ }+ scheduleBackgroundDraw();+ startBackgroundLoop();+ }+ // One canvas, three draws: each source segment stretches into whatever bar+ // the picture leaves open. The live video feeds it once presented; until+ // then the decoded JPEG frame does, so the backdrop always matches the+ // picture's own pixels and scale in the center segment.+ let bgRects = null,+ bgAxis = "x",+ bgDpr = 1,+ bgDrawFrame = null,+ bgLoopFrame = null;+ function drawBackground() {+ if (!bgContext || !bgRects) return;+ bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);+ bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);+ const useVideo =+ videoPresented && video.videoWidth > 0 && video.videoHeight > 0;+ const src = useVideo ? video : image;+ // drawImage source rects live in the source's own pixel space, which can+ // differ from dw/dh; fractions of the real bitmap keep every segment lined+ // up with what the picture element actually shows.+ const sw = useVideo ? video.videoWidth : image.naturalWidth;+ const sh = useVideo ? video.videoHeight : image.naturalHeight;+ if (!(sw > 0 && sh > 0)) return;+ const horizontal = bgAxis === "x";+ const sourceLength = horizontal ? sw : sh;+ const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];+ for (let i = 0; i < bgRects.length; i++) {+ const rect = bgRects[i];+ const origin = cuts[i] * sourceLength;+ const length = (cuts[i + 1] - cuts[i]) * sourceLength;+ bgContext.drawImage(+ src,+ horizontal ? origin : 0,+ horizontal ? 0 : origin,+ horizontal ? length : sw,+ horizontal ? sh : length,+ rect.x,+ rect.y,+ rect.w,+ rect.h,+ );+ }+ }+ function scheduleBackgroundDraw() {+ if (bgDrawFrame !== null || !bgRects || !bgContext) return;+ bgDrawFrame = requestAnimationFrame(() => {+ bgDrawFrame = null;+ drawBackground();+ });+ }+ function startBackgroundLoop() {+ if (+ bgLoopFrame !== null ||+ !bgContext ||+ !bgRects ||+ !videoPresented ||+ typeof video.requestVideoFrameCallback !== "function"+ )+ return;+ const frame = video.requestVideoFrameCallback(() => {+ if (bgLoopFrame !== frame) return;+ bgLoopFrame = null;+ drawBackground();+ startBackgroundLoop();+ });+ bgLoopFrame = frame;+ }+ // Only the streaming loop stops here; a pending one-shot draw is harmless+ // (it re-paints the preserved frame) and must survive reconnects.+ function stopBackgroundLoop() {+ if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);+ bgLoopFrame = null;+ }+ function clearBackground() {+ stopBackgroundLoop();+ bgRects = null;+ // Resizing a canvas resets its bitmap; same-value assignment still clears.+ if (bgCanvas) bgCanvas.width = bgCanvas.width;+ }+ listen(image, "load", () => scheduleBackgroundDraw());+ // Older WebViews update the ambient layer on media progress, never with an+ // idle display-refresh loop. Geometry changes still get a one-shot repaint.+ listen(video, "timeupdate", () => {+ if (videoPresented && typeof video.requestVideoFrameCallback !== "function")+ scheduleBackgroundDraw();+ });function panBounds(r) {const vw = viewportWidth(),vh = viewportHeight();@@ -277,14 +488,14 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {const bounds = {minX: viewportLeft() + x.min,maxX: viewportLeft() + x.max,- minY: y.min,- maxY: y.max,+ minY: y.min + verticalOffset(r.height),+ maxY: y.max + verticalOffset(r.height),};// A camera position required to expose the cursor is a valid resting point,// not elastic overshoot. Preserve it across the next pan/pinch handoff.if (followRest) {const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,- restY = vh / 2 - followRest.fy * r.height;+ restY = vh / 2 + verticalOffset(r.height) - followRest.fy * r.height;const weight =followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;bounds.minX += Math.min(0, restX - bounds.minX) * weight;@@ -311,7 +522,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {}function place(x, y, r) {fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;- fy = (viewportHeight() / 2 - y) / r.height;+ fy = (viewportHeight() / 2 + verticalOffset(r.height) - y) / r.height;}function cursorViewport() {const hotX = remoteCursor?.hotX ?? 9,@@ -403,6 +614,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {el.style.left = r.x + "px";el.style.top = r.y + "px";}+ paintBackground();if (remoteCursor) {cursor.style.width = remoteCursor.width + "px";cursor.style.height = remoteCursor.height + "px";@@ -570,7 +782,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {multi = null;}function updateMouseButtons() {- mouseButtons.style.display = showMouseButtons && control ? "block" : "none";+ mouseButtons.style.display =+ showMouseButtons && control && !nativeMouseControls ? "block" : "none";for (const [name, button] of [["left", 0],["right", 2],@@ -585,11 +798,11 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {["right", 2],]) {const el = find("mouse-" + name);- listen(el, "pointerdown", (e) => {+ listenMouse(el, "pointerdown", (e) => {e.preventDefault();if (!control || !showMouseButtons || heldMouse.has(button)) return;clearTimeout(hold);- el.setPointerCapture(e.pointerId);+ if (!e.nativeInput) el.setPointerCapture(e.pointerId);heldMouse.set(button, e.pointerId);queue({ kind: "button", button, down: true, x: cx, y: cy });flush();@@ -603,10 +816,10 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {flush();updateMouseButtons();};- listen(el, "pointerup", up);- listen(el, "pointercancel", up);- listen(el, "lostpointercapture", up);- listen(el, "click", (e) => {+ listenMouse(el, "pointerup", up);+ listenMouse(el, "pointercancel", up);+ listenMouse(el, "lostpointercapture", up);+ listenMouse(el, "click", (e) => {if (e.detail === 0 && control && showMouseButtons) {click(button);flush();@@ -618,14 +831,14 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {queue({ kind: "scroll", dx: 0, dy: Math.max(-2000, Math.min(2000, dy)) });}};- listen(wheel, "pointerdown", (e) => {+ listenMouse(wheel, "pointerdown", (e) => {e.preventDefault();if (!control || !showMouseButtons || wheelY) return;- wheel.setPointerCapture(e.pointerId);+ if (!e.nativeInput) wheel.setPointerCapture(e.pointerId);wheelY = { id: e.pointerId, y: e.clientY, start: e.clientY, moved: false };});// A small dead zone preserves middle clicks; displacement drives the timer.- listen(wheel, "pointermove", (e) => {+ listenMouse(wheel, "pointermove", (e) => {if (!wheelY || wheelY.id !== e.pointerId) return;e.preventDefault();wheelGrip.style.transform =@@ -635,7 +848,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {wheelY.y = e.clientY;if (Math.abs(e.clientY - wheelY.start) > 4) wheelY.moved = true;});- listen(wheel, "pointerup", (e) => {+ listenMouse(wheel, "pointerup", (e) => {if (!wheelY || wheelY.id !== e.pointerId) return;e.preventDefault();if (!wheelY.moved && control && showMouseButtons) {@@ -647,15 +860,15 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {const cancelWheel = (e) => {if (wheelY?.id === e.pointerId) resetWheel();};- listen(wheel, "pointercancel", cancelWheel);- listen(wheel, "lostpointercapture", cancelWheel);- listen(wheel, "click", (e) => {+ listenMouse(wheel, "pointercancel", cancelWheel);+ listenMouse(wheel, "lostpointercapture", cancelWheel);+ listenMouse(wheel, "click", (e) => {if (e.detail === 0 && control && showMouseButtons) {click(1);flush();}});- listen(wheel, "keydown", (e) => {+ listenMouse(wheel, "keydown", (e) => {if (e.key === "ArrowUp" || e.key === "ArrowDown") {e.preventDefault();scrollMouse(e.key === "ArrowUp" ? -120 : 120);@@ -775,7 +988,9 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {fx =multi.anchor.x +(viewportLeft() + viewportWidth() / 2 - next.x) / r.width;- fy = multi.anchor.y + (viewportHeight() / 2 - next.y) / r.height;+ fy =+ multi.anchor.y ++ (viewportHeight() / 2 + verticalOffset(r.height) - next.y) / r.height;const moved = layout(),b = panBounds(moved);place(@@ -1080,6 +1295,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {cleanups.push(() => observer.disconnect(),() => stopPanAnimation(),+ () => stopBackgroundLoop(),() => clearTimeout(touchCursorTimer),);// Keep one bounded frame in this document only; never persist desktop pixels.@@ -1140,6 +1356,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {videoPaintCallback = null;videoPresented = true;video.style.zIndex = "2";+ if (typeof startBackgroundLoop === "function") startBackgroundLoop();post({ type: "streaming", attemptId });post({type: "pipCapability",@@ -1223,7 +1440,11 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {video.style.display = "none";video.style.zIndex = "0";image.style.display = "block";- if (!preserveFrame) image.removeAttribute("src");+ if (typeof stopBackgroundLoop === "function") stopBackgroundLoop();+ if (!preserveFrame) {+ image.removeAttribute("src");+ if (typeof clearBackground === "function") clearBackground();+ }}function failRtc(reason, canRetry = true) {const failedAttempt = attemptId;@@ -1434,6 +1655,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {return;video.style.display = "block";render();+ if (typeof scheduleBackgroundDraw === "function")+ scheduleBackgroundDraw();if (typeof video.requestVideoFrameCallback === "function") {videoFrameCallback = video.requestVideoFrameCallback(() => {if (g !== generation) return;@@ -1588,7 +1811,50 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {);}break;+ case "networkStatus": {+ const status = document.getElementById("network-status");+ if (!status) break;+ status.textContent =+ typeof message.text === "string" ? message.text : "";+ status.style.display = status.textContent ? "block" : "none";+ for (const key of ["top", "right", "fontSize"]) {+ if (Number.isFinite(message[key]) && message[key] >= 0)+ status.style[key] = message[key] + "px";+ }+ if (/^#[0-9a-f]{3,8}$/i.test(message.color))+ status.style.color = message.color;+ break;+ }+ case "nativeMouse": {+ if (+ !nativeMouseControls ||+ !["left", "right", "wheel"].includes(message.control)+ )+ break;+ if (+ ![+ "pointerdown",+ "pointermove",+ "pointerup",+ "pointercancel",+ "click",+ ].includes(message.event)+ )+ break;+ if (!Number.isFinite(message.id) || !Number.isFinite(message.y)) break;+ mouseControlHandlers.get(+ "mouse-" + message.control + ":" + message.event,+ )?.({+ pointerId: message.id,+ clientY: message.y,+ detail: 0,+ nativeInput: true,+ preventDefault() {},+ });+ break;+ }case "mouseButtons": {+ nativeMouseControls = message.native === true;const before = layout(),previousBottomInset = viewportBottomInset,keyboardOpen = fillHeight && message.keyboardOpen === true;@@ -1596,6 +1862,13 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {fillHeight && (keyboardOpen || keyboardViewportOpen);// Opening is observable before the native keyboard has a measured height.keyboardViewportOpen = keyboardOpen;+ const previousOffset = portraitKeyboardTopInset;+ if (Number.isFinite(message.portraitKeyboardTopInset))+ portraitKeyboardTopInset = Math.max(+ 0,+ message.portraitKeyboardTopInset,+ );+ const offsetChanged = previousOffset !== portraitKeyboardTopInset;let sideInsetsChanged = false;if (Number.isFinite(message.bottomInset))viewportBottomInset = Math.max(@@ -1649,6 +1922,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {render();} else if (sideInsetsChanged ||+ offsetChanged ||(viewerSized && previousBottomInset !== viewportBottomInset)) {settlePan();@@ -1726,7 +2000,10 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {else resetCursor();const frameEpoch = epoch;image.onload = () => {- if (epoch === frameEpoch) post({ type: "framePresented" });+ if (epoch === frameEpoch) {+ scheduleBackgroundDraw();+ post({ type: "framePresented" });+ }};image.src = "data:image/jpeg;base64," + message.jpeg;break;@@ -1782,7 +2059,20 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {break;}}+ // iOS can report equal left/right safe areas in both landscape directions.+ // Its interface angle distinguishes the notch side even on a 180-degree turn.+ const reportOrientation = () => {+ const angle =+ typeof window.orientation === "number"+ ? window.orientation+ : window.screen?.orientation?.angle;+ if (Number.isFinite(angle)) post({ type: "orientation", angle });+ };+ listen(window, "orientationchange", reportOrientation);+ if (window.screen?.orientation?.addEventListener)+ listen(window.screen.orientation, "change", reportOrientation);render();+ reportOrientation();post({ type: "ready" });return {receive: (message) => receive({ data: JSON.stringify(message) }),@@ -1790,6 +2080,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {release();epoch = null;closeRtc(false);+ if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);+ bgDrawFrame = null;for (const cleanup of cleanups) cleanup();},};diff --git a/packages/maker-shared/src/remote-desktop/viewerScripts.ts b/packages/maker-shared/src/remote-desktop/viewerScripts.tsindex 281210dfd7..3f715f4070 100644--- a/packages/maker-shared/src/remote-desktop/viewerScripts.ts+++ b/packages/maker-shared/src/remote-desktop/viewerScripts.ts@@ -1,4 +1,4 @@// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.-export const DESKTOP_RTC_SCRIPT = "let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (!preserveFrame) image.removeAttribute(\"src\");\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n if (canRetry && epoch && retries < net.retryMs.length) {\n const delay = net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n }, 3500);\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }";+export const DESKTOP_RTC_SCRIPT = "let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n 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 if (canRetry && epoch && retries < net.retryMs.length) {\n const delay = net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n }, 3500);\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof 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 }";export const DESKTOP_TRANSFORM_SCRIPT = "function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const scale =\n (fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *\n Math.max(1, Math.min(5, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale };\n }";export const DESKTOP_NETWORK_STATS_SCRIPT = "function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n }";diff --git a/packages/maker-shared/src/remote-desktop/viewerSource.ts b/packages/maker-shared/src/remote-desktop/viewerSource.tsindex 774cacdb59..a4507152e4 100644--- a/packages/maker-shared/src/remote-desktop/viewerSource.ts+++ b/packages/maker-shared/src/remote-desktop/viewerSource.ts@@ -1,2 +1,2 @@// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.-export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const scale =\n (fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *\n Math.max(1, Math.min(5, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale };\n };\n /* END TRANSFORM */ const networkStats =\n /* BEGIN NETWORK_STATS */\n function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n };\n\n /* END NETWORK_STATS */ const stage = find(\"stage\"),\n image = find(\"image\"),\n video = find(\"video\"),\n cursor = find(\"cursor\");\n let dw = 1920,\n dh = 1080,\n viewerSized = false,\n zoom = 1,\n fx = 0.5,\n fy = 0.5,\n mode = \"pointer\",\n control = false,\n clipboardShortcuts = false,\n clipboardModifier = \"control\",\n deferredClipboardModifier = null,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n sending = false,\n cx = 0.5,\n cy = 0.5,\n drag = false,\n start = null,\n last = null,\n multi = null,\n hold = null,\n moved = false;\n const pointers = new Map();\n const mouseButtons = find(\"mouse-buttons\"),\n wheel = find(\"mouse-wheel\"),\n wheelGrip = find(\"mouse-wheel-grip\");\n const keyboardInput = find(\"keyboard-input\");\n let keyboardEnabled = false,\n composing = false;\n const keyboardSentinel = \"\\u200b\";\n function resetKeyboard() {\n keyboardInput.value = keyboardSentinel;\n keyboardInput.setSelectionRange(1, 1);\n }\n function showKeyboard(enabled) {\n keyboardEnabled = enabled && control;\n if (!keyboardEnabled) {\n composing = false;\n resetKeyboard();\n keyboardInput.blur();\n return;\n }\n if (composing) return;\n if (config.desktop && document.activeElement === keyboardInput) return;\n // Keep focus inside the native evaluateJavaScript call; WebKit can reject\n // keyboard presentation after requestAnimationFrame loses user activation.\n keyboardInput.blur();\n resetKeyboard();\n keyboardInput.focus({ preventScroll: true });\n }\n function keyboardKey(code) {\n if (!keyboardEnabled || !control) return;\n queue({ kind: \"key\", code, down: true });\n queue({ kind: \"key\", code, down: false });\n flush();\n }\n function commitKeyboard() {\n if (!keyboardEnabled || !control || composing) return;\n const text = keyboardInput.value.replace(keyboardSentinel, \"\");\n if (text) {\n for (let i = 0; i < text.length; i += 4096)\n queue({ kind: \"text\", text: text.slice(i, i + 4096) });\n flush();\n }\n resetKeyboard();\n }\n listen(keyboardInput, \"compositionstart\", () => {\n composing = true;\n });\n listen(keyboardInput, \"compositionend\", () => {\n composing = false;\n commitKeyboard();\n });\n listen(keyboardInput, \"input\", (e) => {\n if (!e.isComposing) commitKeyboard();\n });\n listen(keyboardInput, \"beforeinput\", (e) => {\n if (composing || e.isComposing) return;\n if (e.inputType === \"deleteContentBackward\") {\n e.preventDefault();\n keyboardKey(\"Backspace\");\n resetKeyboard();\n } else if (\n e.inputType === \"insertLineBreak\" ||\n e.inputType === \"insertParagraph\"\n ) {\n e.preventDefault();\n keyboardKey(\"Enter\");\n resetKeyboard();\n }\n });\n const heldMouse = new Map();\n let showMouseButtons = false,\n wheelY = null;\n function resetWheel() {\n wheelY = null;\n wheelGrip.style.transform = \"translateY(0px)\";\n }\n let statsTimer = null,\n statsSample = null;\n const post = (message) => postMessage({ ...message, epoch });\n const clamp = (v) => Math.max(0, Math.min(1, v));\n let fillHeight = false;\n let panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n keyboardViewportInset = 0;\n let keyboardViewportOpen = false;\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 viewportHeight = () =>\n Math.max(1, stage.clientHeight - (viewerSized ? viewportBottomInset : 0));\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n const layout = () => {\n const r = transform(\n viewportWidth(),\n viewportHeight(),\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight && !viewerSized,\n );\n return {\n ...r,\n x: viewportLeft() + viewportWidth() / 2 - fx * r.width,\n y: viewportHeight() / 2 - fy * r.height,\n };\n };\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (Math.max(1, Math.min(5, zoom)) - 1)) / 4;\n const axis = (viewport, content) =>\n content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min,\n maxY: y.max,\n };\n // A camera position required to expose the cursor is a valid resting point,\n // not elastic overshoot. Preserve it across the next pan/pinch handoff.\n if (followRest) {\n const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,\n restY = vh / 2 - followRest.fy * r.height;\n const weight =\n followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;\n bounds.minX += Math.min(0, restX - bounds.minX) * weight;\n bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;\n bounds.minY += Math.min(0, restY - bounds.minY) * weight;\n bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;\n }\n return bounds;\n }\n const bounded = (v, min, max) => Math.max(min, Math.min(max, v));\n // Convert displayed overshoot back to finger travel before the next delta,\n // so reversing direction unwinds smoothly without an edge jump.\n function rubber(v, min, max, inverse = false) {\n const edge = bounded(v, min, max),\n d = v - edge;\n const reach = 40 + 10 * (Math.max(1, Math.min(5, zoom)) - 1);\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (viewportHeight() / 2 - y) / r.height;\n }\n function cursorViewport() {\n const hotX = remoteCursor?.hotX ?? 9,\n hotY = remoteCursor?.hotY ?? 9;\n const w = remoteCursor?.width ?? 18,\n h = remoteCursor?.height ?? 18;\n const left = viewportLeft(),\n right = left + viewportWidth(),\n bottom = Math.max(1, stage.clientHeight - viewportBottomInset);\n // Keep the entire cursor, including its hotspot offset, clear of chrome.\n const minX = Math.min(right - 1, left + 8 + hotX),\n minY = Math.min(bottom - 1, 8 + hotY);\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n const touchFeedback = control && mode === \"touch\" && touchCursorVisible;\n const cursorX = mode === \"touch\" && touchCursor ? touchCursor.x : cx;\n const cursorY = mode === \"touch\" && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n mode === \"touch\" && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n if (remoteCursor) {\n cursor.style.width = remoteCursor.width + \"px\";\n cursor.style.height = remoteCursor.height + \"px\";\n cursor.style.border = \"0\";\n cursor.style.borderRadius = \"0\";\n cursor.style.transform = \"none\";\n cursor.style.left = r.x + cursorX * r.width - remoteCursor.hotX + \"px\";\n cursor.style.top = r.y + cursorY * r.height - remoteCursor.hotY + \"px\";\n cursor.style.display = \"block\";\n cursor.style.opacity = (\n mode === \"touch\"\n ? touchFeedback\n : remoteCursor.visible ||\n (control && mode === \"pointer\" && localCursorAwake)\n )\n ? \"1\"\n : \"0\";\n } else {\n cursor.style.opacity = (mode === \"touch\" ? !touchFeedback : false)\n ? \"0\"\n : \"1\";\n cursor.style.width = \"18px\";\n cursor.style.height = \"18px\";\n cursor.style.border = \"2px solid var(--foreground)\";\n cursor.style.borderRadius = \"50%\";\n cursor.style.transform = \"translate(-50%,-50%)\";\n cursor.style.left = r.x + cursorX * r.width + \"px\";\n cursor.style.top = r.y + cursorY * r.height + \"px\";\n cursor.style.display =\n !config.desktop && control && (mode === \"pointer\" || mode === \"touch\")\n ? \"block\"\n : \"none\";\n }\n if (config.desktop) stage.style.cursor = control ? \"none\" : \"default\";\n }\n // Literal source is required: Hermes function.toString() yields bytecode.\n function validCursor(v) {\n return (\n !!v &&\n typeof v === \"object\" &&\n typeof v.visible === \"boolean\" &&\n [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&\n v.x >= 0 &&\n v.x <= 1 &&\n v.y >= 0 &&\n v.y <= 1 &&\n v.width > 0 &&\n v.width <= 256 &&\n v.height > 0 &&\n v.height <= 256 &&\n v.hotX >= 0 &&\n v.hotX <= v.width &&\n v.hotY >= 0 &&\n v.hotY <= v.height &&\n typeof v.png === \"string\" &&\n v.png.length <= 65536 &&\n /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png)\n );\n }\n function receiveCursor(value) {\n if (value === null) {\n if (remoteCursor) {\n remoteCursor = { ...remoteCursor, visible: false };\n render();\n }\n return;\n }\n if (!validCursor(value)) return;\n if (!remoteCursor || remoteCursor.png !== value.png)\n cursorImage.src = \"data:image/png;base64,\" + value.png;\n // Keep delayed host coordinates from pulling the local touchpad backwards.\n if (\n !remoteCursor ||\n !control ||\n mode !== \"pointer\" ||\n (!pointers.size && performance.now() - lastLocalMove > 200)\n ) {\n cx = value.x;\n cy = value.y;\n }\n if (value.visible) localCursorAwake = false;\n remoteCursor = value;\n render();\n }\n function resetCursor() {\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n touchCursor = null;\n localCursorAwake = false;\n remoteCursor = null;\n cursorImage.removeAttribute(\"src\");\n render();\n }\n function queue(event) {\n if (!control) return;\n if (config.desktop && (event.kind === \"button\" || event.kind === \"scroll\"))\n flushClipboardModifier();\n // Remote visibility can remain hidden after synthetic mouse movement. Wake\n // the local touchpad cursor until the host reports a visible cursor again.\n if (event.kind === \"move\" && mode === \"pointer\") localCursorAwake = true;\n if (event.kind === \"key\" || event.kind === \"text\") {\n localCursorAwake = false;\n render();\n }\n if (event.kind === \"move\" || event.kind === \"button\")\n lastLocalMove = performance.now();\n const tail = pending[pending.length - 1];\n if (event.kind === \"move\" && tail?.kind === \"move\")\n pending[pending.length - 1] = event;\n // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the\n // accumulated distance so a delayed ACK cannot replay a large scroll backlog.\n else if (event.kind === \"scroll\" && tail?.kind === \"scroll\") {\n tail.dx = Math.max(-2000, Math.min(2000, tail.dx + event.dx));\n tail.dy = Math.max(-2000, Math.min(2000, tail.dy + event.dy));\n } else pending.push(event);\n if (pending.length > 64) {\n pending = [{ kind: \"release\" }];\n control = false;\n post({ type: \"inputOverflow\" });\n }\n }\n function flush() {\n if (!pending.length || sending) return;\n const events = pending.splice(0, 64),\n sequence = ++seq;\n if (\n pc?.connectionState === \"connected\" &&\n dc &&\n dc.readyState === \"open\" &&\n dc.bufferedAmount < 16384\n ) {\n dc.send(JSON.stringify({ sequence, events }));\n } else {\n sending = true;\n post({ type: \"input\", sequence, events });\n }\n }\n const inputTimer = setInterval(() => {\n // Hold displacement controls speed, even without further pointer moves.\n // Skip missed ticks while awaiting ACK instead of building a scroll backlog.\n if (wheelY?.moved && !sending) {\n const offset = Math.max(-24, Math.min(24, wheelY.y - wheelY.start));\n if (Math.abs(offset) > 4)\n scrollMouse(Math.sign(offset) * (Math.abs(offset) - 4) * 1.5);\n }\n flush();\n }, 33);\n cleanups.push(() => clearInterval(inputTimer));\n function release() {\n deferredClipboardModifier = null;\n clearTimeout(hold);\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n if (control) {\n queue({ kind: \"release\" });\n flush();\n }\n heldMouse.clear();\n resetWheel();\n updateMouseButtons();\n drag = false;\n pointers.clear();\n start = null;\n last = null;\n multi = null;\n }\n function updateMouseButtons() {\n mouseButtons.style.display = showMouseButtons && control ? \"block\" : \"none\";\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ])\n find(\"mouse-\" + name).setAttribute(\n \"aria-pressed\",\n String(heldMouse.has(button)),\n );\n }\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ]) {\n const el = find(\"mouse-\" + name);\n listen(el, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || heldMouse.has(button)) return;\n clearTimeout(hold);\n el.setPointerCapture(e.pointerId);\n heldMouse.set(button, e.pointerId);\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n flush();\n updateMouseButtons();\n });\n const up = (e) => {\n e.preventDefault();\n if (heldMouse.get(button) !== e.pointerId) return;\n heldMouse.delete(button);\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n flush();\n updateMouseButtons();\n };\n listen(el, \"pointerup\", up);\n listen(el, \"pointercancel\", up);\n listen(el, \"lostpointercapture\", up);\n listen(el, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(button);\n flush();\n }\n });\n }\n const scrollMouse = (dy) => {\n if (control && showMouseButtons && Number.isFinite(dy)) {\n queue({ kind: \"scroll\", dx: 0, dy: Math.max(-2000, Math.min(2000, dy)) });\n }\n };\n listen(wheel, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || wheelY) return;\n wheel.setPointerCapture(e.pointerId);\n wheelY = { id: e.pointerId, y: e.clientY, start: e.clientY, moved: false };\n });\n // A small dead zone preserves middle clicks; displacement drives the timer.\n listen(wheel, \"pointermove\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n wheelGrip.style.transform =\n \"translateY(\" +\n Math.max(-24, Math.min(24, e.clientY - wheelY.start)) +\n \"px)\";\n wheelY.y = e.clientY;\n if (Math.abs(e.clientY - wheelY.start) > 4) wheelY.moved = true;\n });\n listen(wheel, \"pointerup\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n if (!wheelY.moved && control && showMouseButtons) {\n click(1);\n flush();\n }\n resetWheel();\n });\n const cancelWheel = (e) => {\n if (wheelY?.id === e.pointerId) resetWheel();\n };\n listen(wheel, \"pointercancel\", cancelWheel);\n listen(wheel, \"lostpointercapture\", cancelWheel);\n listen(wheel, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(1);\n flush();\n }\n });\n listen(wheel, \"keydown\", (e) => {\n if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n e.preventDefault();\n scrollMouse(e.key === \"ArrowUp\" ? -120 : 120);\n }\n });\n function insideDesktop(p) {\n const r = layout();\n return (\n p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height\n );\n }\n function point(p) {\n const r = layout();\n return {\n x: clamp((p.x - r.x) / r.width),\n y: clamp((p.y - r.y) / r.height),\n };\n }\n const desktopPoint = (e) => {\n const bounds = stage.getBoundingClientRect();\n return { x: e.clientX - bounds.left, y: e.clientY - bounds.top };\n };\n function mouse(e, down) {\n if (!control || ![0, 1, 2].includes(e.button)) return;\n const local = desktopPoint(e);\n if (down && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n if (down) {\n showKeyboard(true);\n stage.setPointerCapture(e.pointerId);\n heldMouse.set(e.button, e.pointerId);\n } else if (!heldMouse.delete(e.button)) return;\n queue({ kind: \"button\", button: e.button, down, x: cx, y: cy });\n flush();\n render();\n }\n function click(button = 0) {\n if (control && mode === \"touch\") {\n clearTimeout(touchCursorTimer);\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n touchCursorTimer = setTimeout(() => {\n touchCursorVisible = false;\n render();\n }, 450);\n }\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n }\n function pan(dx, dy) {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r);\n place(\n rubber(rubber(r.x, b.minX, b.maxX, true) + dx, b.minX, b.maxX),\n rubber(rubber(r.y, b.minY, b.maxY, true) + dy, b.minY, b.maxY),\n r,\n );\n render();\n }\n function pair() {\n const [a, b] = [...pointers.values()];\n return {\n x: (a.x + b.x) / 2,\n y: (a.y + b.y) / 2,\n d: Math.hypot(a.x - b.x, a.y - b.y),\n };\n }\n function movePair() {\n gestureFrame = null;\n if (pointers.size < 2 || !multi) return;\n const next = pair(),\n span = Math.abs(next.d - multi.d),\n travel = Math.hypot(next.x - multi.x, next.y - multi.y);\n if (multi.kind !== \"pinch\") {\n const pinchSlop = Math.max(6, Math.min(12, multi.d * 0.04));\n if (span >= pinchSlop && span > travel * 0.65) {\n // A parallel scroll may deliver its two pointer updates in different\n // frames. Confirm separation briefly before taking over as a pinch.\n if (!multi.candidate)\n multi.candidate = {\n at: Date.now(),\n d: next.d,\n zoom,\n anchor: point(next),\n };\n if (Date.now() - multi.candidate.at >= 40) {\n if (multi.kind === \"scroll\") {\n multi.d = multi.candidate.d;\n multi.zoom = multi.candidate.zoom;\n multi.anchor = multi.candidate.anchor;\n }\n multi.kind = \"pinch\";\n multi.candidate = null;\n } else {\n gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n } else {\n multi.candidate = null;\n if (!multi.kind && travel > 8 && travel > span) multi.kind = \"scroll\";\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n zoom = Math.max(\n 1,\n Math.min(5, (multi.zoom * next.d) / Math.max(1, multi.d)),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy = multi.anchor.y + (viewportHeight() / 2 - next.y) / r.height;\n const moved = layout(),\n b = panBounds(moved);\n place(\n rubber(moved.x, b.minX, b.maxX),\n rubber(moved.y, b.minY, b.maxY),\n moved,\n );\n } else if (multi.kind === \"scroll\") {\n const dx = next.x - multi.lastX,\n dy = next.y - multi.lastY;\n if (control && mode !== \"pan\")\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, -dx)),\n dy: Math.max(-2000, Math.min(2000, -dy)),\n });\n else pan(dx, dy);\n }\n if (multi.kind) {\n multi.lastX = next.x;\n multi.lastY = next.y;\n }\n render();\n }\n listen(stage, \"pointerdown\", (e) => {\n if (config.desktop) {\n e.preventDefault();\n mouse(e, true);\n return;\n }\n e.preventDefault();\n stopPanAnimation();\n stage.setPointerCapture(e.pointerId);\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size === 1) {\n cursorNeedsEntry = true;\n start = { x: e.clientX, y: e.clientY };\n last = start;\n moved = false;\n hold = setTimeout(() => {\n if (\n control &&\n mode !== \"pan\" &&\n !moved &&\n pointers.size === 1 &&\n !heldMouse.size &&\n (mode !== \"touch\" || insideDesktop(start))\n ) {\n if (mode === \"touch\") {\n const p = point(start);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"button\", button: 0, down: true, x: cx, y: cy });\n drag = true;\n }\n }, 400);\n } else {\n clearTimeout(hold);\n if (drag) queue({ kind: \"release\" });\n drag = false;\n start = null;\n const p = pair();\n multi = {\n ...p,\n lastX: p.x,\n lastY: p.y,\n zoom,\n anchor: point(p),\n kind: null,\n };\n }\n });\n listen(stage, \"pointermove\", (e) => {\n if (config.desktop) {\n if (!control) return;\n const local = desktopPoint(e);\n if (!heldMouse.size && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n e.preventDefault();\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size >= 2) {\n if (gestureFrame === null) gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n if (!start || !last) return;\n const now = { x: e.clientX, y: e.clientY },\n dx = now.x - last.x,\n dy = now.y - last.y;\n last = now;\n if (Math.hypot(now.x - start.x, now.y - start.y) > 6) {\n moved = true;\n clearTimeout(hold);\n }\n if (\n !control ||\n mode === \"pan\" ||\n (mode === \"touch\" && !drag && !heldMouse.size)\n ) {\n pan(dx, dy);\n return;\n }\n if (mode === \"pointer\") {\n moveTouchpad(dx, dy);\n } else {\n const p = point(now);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n });\n function up(e) {\n if (config.desktop) {\n mouse(e, false);\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n clearTimeout(hold);\n if (pointers.size >= 2 && multi) {\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n movePair();\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n }\n pointers.delete(e.pointerId);\n if (drag) {\n queue({ kind: \"button\", button: 0, down: false, x: cx, y: cy });\n drag = false;\n } else if (\n start &&\n !moved &&\n control &&\n mode !== \"pan\" &&\n !heldMouse.size &&\n e.type === \"pointerup\" &&\n (mode !== \"touch\" || insideDesktop({ x: e.clientX, y: e.clientY }))\n ) {\n if (mode === \"touch\") {\n const p = point({ x: e.clientX, y: e.clientY });\n cx = p.x;\n cy = p.y;\n }\n click();\n }\n start = null;\n last = null;\n multi = null;\n render();\n if (!pointers.size && manualViewMoved) settlePan();\n }\n listen(stage, \"pointerup\", up);\n listen(stage, \"pointercancel\", () => {\n release();\n settlePan();\n });\n listen(stage, \"lostpointercapture\", () => {\n if (config.desktop && heldMouse.size) release();\n });\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) return;\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, e.deltaX * factor)),\n dy: Math.max(-2000, Math.min(2000, e.deltaY * factor)),\n });\n flush();\n },\n { passive: false },\n );\n listen(config.desktop ? stage : document, \"contextmenu\", (e) =>\n e.preventDefault(),\n );\n // Scope selection suppression to the desktop surface, preserving the hidden\n // textarea's native keyboard/IME editing and programmatic selection.\n listen(stage, \"selectstart\", (e) => e.preventDefault());\n listen(stage, \"dragstart\", (e) => e.preventDefault());\n const normalizedKey = (code) =>\n /^(Shift|Control|Alt|Meta)Right$/.test(code)\n ? code.replace(/Right$/, \"Left\")\n : code;\n const hardwareKeys = new Set();\n function flushClipboardModifier() {\n if (!deferredClipboardModifier) return;\n const code = deferredClipboardModifier;\n deferredClipboardModifier = null;\n hardwareKeys.add(code);\n queue({ kind: \"key\", code, down: true });\n }\n listen(document, \"keydown\", (e) => {\n if (config.desktop) {\n if (e.ctrlKey && e.altKey && e.code === \"Escape\") {\n e.preventDefault();\n release();\n showKeyboard(false);\n post({ type: \"releaseFocus\" });\n return;\n }\n if (\n document.activeElement !== keyboardInput ||\n e.isComposing ||\n composing\n )\n return;\n if ((e.metaKey || e.ctrlKey) && e.code === \"KeyW\") return; // always retain a local close shortcut\n if (\n control &&\n clipboardShortcuts &&\n normalizedKey(e.code) ===\n (clipboardModifier === \"meta\" ? \"MetaLeft\" : \"ControlLeft\")\n ) {\n e.preventDefault();\n if (!hardwareKeys.has(normalizedKey(e.code)))\n deferredClipboardModifier = normalizedKey(e.code);\n return;\n }\n if (\n control &&\n clipboardShortcuts &&\n (clipboardModifier === \"meta\"\n ? e.metaKey && !e.ctrlKey\n : e.ctrlKey && !e.metaKey) &&\n !e.altKey &&\n !e.shiftKey &&\n (e.code === \"KeyC\" || e.code === \"KeyV\")\n ) {\n e.preventDefault();\n if (!e.repeat) {\n release();\n hardwareKeys.clear();\n post({\n type: \"clipboard\",\n action: e.code === \"KeyC\" ? \"copy\" : \"paste\",\n });\n }\n return;\n }\n if (\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 || e.key === \"Process\" || e.key === \"Dead\")\n )\n return;\n }\n if (control && validKeys.has(normalizedKey(e.code))) {\n e.preventDefault();\n flushClipboardModifier();\n hardwareKeys.add(normalizedKey(e.code));\n queue({ kind: \"key\", code: normalizedKey(e.code), down: true });\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (config.desktop && control && deferredClipboardModifier === code) {\n flushClipboardModifier();\n }\n if (config.desktop && !hardwareKeys.delete(code)) return;\n if (control && validKeys.has(code)) {\n e.preventDefault();\n queue({ kind: \"key\", code, down: false });\n }\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n hardwareKeys.clear();\n release();\n });\n listen(window, \"blur\", () => {\n release();\n settlePan();\n });\n function reportViewport() {\n post({\n type: \"viewportChanged\",\n width: viewportWidth(),\n height: Math.max(1, stage.clientHeight - viewportBottomInset),\n });\n }\n const observer = new ResizeObserver(() => {\n reportViewport();\n release();\n settlePan();\n render();\n });\n observer.observe(stage);\n cleanups.push(\n () => observer.disconnect(),\n () => stopPanAnimation(),\n () => clearTimeout(touchCursorTimer),\n );\n // Keep one bounded frame in this document only; never persist desktop pixels.\n // Snapshot before detaching the track. A JPEG fallback already lives in image.\n function retainFrame() {\n if (\n !videoPresented ||\n video.style.display !== \"block\" ||\n video.readyState < 2 ||\n !video.videoWidth ||\n !video.videoHeight\n )\n return;\n const canvas = document.createElement(\"canvas\");\n try {\n const scale = Math.min(\n 1,\n 1280 / Math.max(video.videoWidth, video.videoHeight),\n );\n canvas.width = Math.max(1, Math.round(video.videoWidth * scale));\n canvas.height = Math.max(1, Math.round(video.videoHeight * scale));\n const context = canvas.getContext(\"2d\");\n if (context) {\n context.drawImage(video, 0, 0, canvas.width, canvas.height);\n image.src = canvas.toDataURL(\"image/jpeg\", 0.7);\n }\n } catch {\n /* Keep the previous compatibility frame if WebKit cannot read video. */\n } finally {\n canvas.width = 0;\n canvas.height = 0;\n }\n }\n /* BEGIN RTC */\n\n let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (!preserveFrame) image.removeAttribute(\"src\");\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n if (canRetry && epoch && retries < net.retryMs.length) {\n const delay = net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n }, 3500);\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: Math.max(1, stage.clientHeight - viewportBottomInset),\n });\n break;\n case \"presentation\":\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n if (\n Number.isInteger(message.width) &&\n Number.isInteger(message.height) &&\n message.width >= 320 &&\n message.height >= 320 &&\n (message.restore === true ||\n (message.width <= 2560 && message.height <= 2560))\n ) {\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n video.muted = !message.audio;\n retries = 0;\n connect();\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = message.surface;\n document.documentElement.style.background = message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"mouseButtons\": {\n const before = layout(),\n previousBottomInset = viewportBottomInset,\n keyboardOpen = fillHeight && message.keyboardOpen === true;\n const keepHorizontal =\n fillHeight && (keyboardOpen || keyboardViewportOpen);\n // Opening is observable before the native keyboard has a measured height.\n keyboardViewportOpen = keyboardOpen;\n let sideInsetsChanged = false;\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 sideInsetsChanged ||\n (viewerSized && 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 viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n clipboardShortcuts =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n connect();\n break;\n case \"viewport\":\n fillHeight = message.fillHeight === true;\n release();\n render();\n break;\n case \"answer\":\n if (message.epoch === epoch) void receiveAnswer(message);\n break;\n case \"iceConfig\":\n if (message.epoch === epoch) void receiveIceConfig(message);\n break;\n case \"ice\":\n if (message.epoch === epoch) void receiveIce(message);\n break;\n case \"fallback\":\n if (message.epoch === epoch && message.attemptId === attemptId)\n failRtc(\"host\", message.retry !== false);\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) post({ type: \"framePresented\" });\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n updateMouseButtons();\n render();\n break;\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"fit\":\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n render();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";+export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const scale =\n (fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *\n Math.max(1, Math.min(5, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale };\n };\n /* END TRANSFORM */ const networkStats =\n /* BEGIN NETWORK_STATS */\n function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n };\n\n /* END NETWORK_STATS */ const stage = find(\"stage\"),\n image = find(\"image\"),\n video = find(\"video\"),\n cursor = find(\"cursor\");\n // Ambient three-segment backdrop (mobile markup only; desktop keeps its\n // solid surface because its stage has no #bg subtree, so every entry may\n // be missing and all backdrop work below must tolerate that).\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 fx = 0.5,\n fy = 0.5,\n mode = \"pointer\",\n control = false,\n clipboardShortcuts = false,\n clipboardModifier = \"control\",\n deferredClipboardModifier = null,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n sending = false,\n cx = 0.5,\n cy = 0.5,\n drag = false,\n start = null,\n last = null,\n multi = null,\n hold = null,\n moved = false;\n const pointers = new Map();\n const mouseButtons = find(\"mouse-buttons\"),\n wheel = find(\"mouse-wheel\"),\n wheelGrip = find(\"mouse-wheel-grip\");\n 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 panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n keyboardViewportInset = 0,\n portraitKeyboardTopInset = 0;\n let keyboardViewportOpen = false;\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 viewportHeight = () =>\n Math.max(1, stage.clientHeight - (viewerSized ? viewportBottomInset : 0));\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 fillHeight\n ? 0\n : Math.min(\n portraitKeyboardTopInset / 2,\n Math.max(0, (viewportHeight() - height) / 2),\n );\n const layout = () => {\n const r = transform(\n viewportWidth(),\n viewportHeight(),\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight && !viewerSized,\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 // 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 (nothing to fill).\n const bgEdgeFraction = 0.05;\n const bgCenterFraction = 1 - 2 * bgEdgeFraction;\n function backgroundSegments(vw, vh, dw, dh, fill) {\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) {\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 function paintBackground() {\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const seg = backgroundSegments(vw, vh, dw, dh, fillHeight);\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 bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\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 if (!(sw > 0 && sh > 0)) return;\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (Math.max(1, Math.min(5, zoom)) - 1)) / 4;\n const axis = (viewport, content) =>\n content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min + 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 + 10 * (Math.max(1, Math.min(5, zoom)) - 1);\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (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(bottom - 1, 8 + hotY);\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n const touchFeedback = control && mode === \"touch\" && touchCursorVisible;\n const cursorX = mode === \"touch\" && touchCursor ? touchCursor.x : cx;\n const cursorY = mode === \"touch\" && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n mode === \"touch\" && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n 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) stage.style.cursor = control ? \"none\" : \"default\";\n }\n // Literal source is required: Hermes function.toString() yields bytecode.\n function validCursor(v) {\n return (\n !!v &&\n typeof v === \"object\" &&\n typeof v.visible === \"boolean\" &&\n [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&\n v.x >= 0 &&\n v.x <= 1 &&\n v.y >= 0 &&\n v.y <= 1 &&\n v.width > 0 &&\n v.width <= 256 &&\n v.height > 0 &&\n v.height <= 256 &&\n v.hotX >= 0 &&\n v.hotX <= v.width &&\n v.hotY >= 0 &&\n v.hotY <= v.height &&\n typeof v.png === \"string\" &&\n v.png.length <= 65536 &&\n /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png)\n );\n }\n function receiveCursor(value) {\n if (value === null) {\n if (remoteCursor) {\n remoteCursor = { ...remoteCursor, visible: false };\n render();\n }\n return;\n }\n if (!validCursor(value)) return;\n if (!remoteCursor || remoteCursor.png !== value.png)\n cursorImage.src = \"data:image/png;base64,\" + value.png;\n // Keep delayed host coordinates from pulling the local touchpad backwards.\n if (\n !remoteCursor ||\n !control ||\n mode !== \"pointer\" ||\n (!pointers.size && performance.now() - lastLocalMove > 200)\n ) {\n cx = value.x;\n cy = value.y;\n }\n if (value.visible) localCursorAwake = false;\n remoteCursor = value;\n render();\n }\n function resetCursor() {\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n touchCursor = null;\n localCursorAwake = false;\n remoteCursor = null;\n cursorImage.removeAttribute(\"src\");\n render();\n }\n function queue(event) {\n if (!control) return;\n if (config.desktop && (event.kind === \"button\" || event.kind === \"scroll\"))\n flushClipboardModifier();\n // Remote visibility can remain hidden after synthetic mouse movement. Wake\n // the local touchpad cursor until the host reports a visible cursor again.\n if (event.kind === \"move\" && mode === \"pointer\") localCursorAwake = true;\n if (event.kind === \"key\" || event.kind === \"text\") {\n localCursorAwake = false;\n render();\n }\n if (event.kind === \"move\" || event.kind === \"button\")\n lastLocalMove = performance.now();\n const tail = pending[pending.length - 1];\n if (event.kind === \"move\" && tail?.kind === \"move\")\n pending[pending.length - 1] = event;\n // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the\n // accumulated distance so a delayed ACK cannot replay a large scroll backlog.\n else if (event.kind === \"scroll\" && tail?.kind === \"scroll\") {\n tail.dx = Math.max(-2000, Math.min(2000, tail.dx + event.dx));\n tail.dy = Math.max(-2000, Math.min(2000, tail.dy + event.dy));\n } else pending.push(event);\n if (pending.length > 64) {\n pending = [{ kind: \"release\" }];\n control = false;\n post({ type: \"inputOverflow\" });\n }\n }\n function flush() {\n if (!pending.length || sending) return;\n const events = pending.splice(0, 64),\n sequence = ++seq;\n if (\n pc?.connectionState === \"connected\" &&\n dc &&\n dc.readyState === \"open\" &&\n dc.bufferedAmount < 16384\n ) {\n dc.send(JSON.stringify({ sequence, events }));\n } else {\n sending = true;\n post({ type: \"input\", sequence, events });\n }\n }\n const inputTimer = setInterval(() => {\n // Hold displacement controls speed, even without further pointer moves.\n // Skip missed ticks while awaiting ACK instead of building a scroll backlog.\n if (wheelY?.moved && !sending) {\n const offset = Math.max(-24, Math.min(24, wheelY.y - wheelY.start));\n if (Math.abs(offset) > 4)\n scrollMouse(Math.sign(offset) * (Math.abs(offset) - 4) * 1.5);\n }\n flush();\n }, 33);\n cleanups.push(() => clearInterval(inputTimer));\n function release() {\n deferredClipboardModifier = null;\n clearTimeout(hold);\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n if (control) {\n queue({ kind: \"release\" });\n flush();\n }\n heldMouse.clear();\n resetWheel();\n updateMouseButtons();\n drag = false;\n pointers.clear();\n start = null;\n last = null;\n multi = null;\n }\n function updateMouseButtons() {\n mouseButtons.style.display =\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 mouse(e, down) {\n if (!control || ![0, 1, 2].includes(e.button)) return;\n const local = desktopPoint(e);\n if (down && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n if (down) {\n showKeyboard(true);\n stage.setPointerCapture(e.pointerId);\n heldMouse.set(e.button, e.pointerId);\n } else if (!heldMouse.delete(e.button)) return;\n queue({ kind: \"button\", button: e.button, down, x: cx, y: cy });\n flush();\n render();\n }\n function click(button = 0) {\n if (control && mode === \"touch\") {\n clearTimeout(touchCursorTimer);\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n touchCursorTimer = setTimeout(() => {\n touchCursorVisible = false;\n render();\n }, 450);\n }\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n }\n function pan(dx, dy) {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r);\n place(\n rubber(rubber(r.x, b.minX, b.maxX, true) + dx, b.minX, b.maxX),\n rubber(rubber(r.y, b.minY, b.maxY, true) + dy, b.minY, b.maxY),\n r,\n );\n render();\n }\n function pair() {\n const [a, b] = [...pointers.values()];\n return {\n x: (a.x + b.x) / 2,\n y: (a.y + b.y) / 2,\n d: Math.hypot(a.x - b.x, a.y - b.y),\n };\n }\n function movePair() {\n gestureFrame = null;\n if (pointers.size < 2 || !multi) return;\n const next = pair(),\n span = Math.abs(next.d - multi.d),\n travel = Math.hypot(next.x - multi.x, next.y - multi.y);\n if (multi.kind !== \"pinch\") {\n const pinchSlop = Math.max(6, Math.min(12, multi.d * 0.04));\n if (span >= pinchSlop && span > travel * 0.65) {\n // A parallel scroll may deliver its two pointer updates in different\n // frames. Confirm separation briefly before taking over as a pinch.\n if (!multi.candidate)\n multi.candidate = {\n at: Date.now(),\n d: next.d,\n zoom,\n anchor: point(next),\n };\n if (Date.now() - multi.candidate.at >= 40) {\n if (multi.kind === \"scroll\") {\n multi.d = multi.candidate.d;\n multi.zoom = multi.candidate.zoom;\n multi.anchor = multi.candidate.anchor;\n }\n multi.kind = \"pinch\";\n multi.candidate = null;\n } else {\n gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n } else {\n multi.candidate = null;\n if (!multi.kind && travel > 8 && travel > span) multi.kind = \"scroll\";\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n zoom = Math.max(\n 1,\n Math.min(5, (multi.zoom * next.d) / Math.max(1, multi.d)),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy =\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 queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, -dx)),\n dy: Math.max(-2000, Math.min(2000, -dy)),\n });\n else pan(dx, dy);\n }\n if (multi.kind) {\n multi.lastX = next.x;\n multi.lastY = next.y;\n }\n render();\n }\n listen(stage, \"pointerdown\", (e) => {\n if (config.desktop) {\n e.preventDefault();\n mouse(e, true);\n return;\n }\n e.preventDefault();\n stopPanAnimation();\n stage.setPointerCapture(e.pointerId);\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size === 1) {\n cursorNeedsEntry = true;\n start = { x: e.clientX, y: e.clientY };\n last = start;\n moved = false;\n hold = setTimeout(() => {\n if (\n control &&\n mode !== \"pan\" &&\n !moved &&\n pointers.size === 1 &&\n !heldMouse.size &&\n (mode !== \"touch\" || insideDesktop(start))\n ) {\n if (mode === \"touch\") {\n const p = point(start);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"button\", button: 0, down: true, x: cx, y: cy });\n drag = true;\n }\n }, 400);\n } else {\n clearTimeout(hold);\n if (drag) queue({ kind: \"release\" });\n drag = false;\n start = null;\n const p = pair();\n multi = {\n ...p,\n lastX: p.x,\n lastY: p.y,\n zoom,\n anchor: point(p),\n kind: null,\n };\n }\n });\n listen(stage, \"pointermove\", (e) => {\n if (config.desktop) {\n if (!control) return;\n const local = desktopPoint(e);\n if (!heldMouse.size && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n e.preventDefault();\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size >= 2) {\n if (gestureFrame === null) gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n if (!start || !last) return;\n const now = { x: e.clientX, y: e.clientY },\n dx = now.x - last.x,\n dy = now.y - last.y;\n last = now;\n if (Math.hypot(now.x - start.x, now.y - start.y) > 6) {\n moved = true;\n clearTimeout(hold);\n }\n if (\n !control ||\n mode === \"pan\" ||\n (mode === \"touch\" && !drag && !heldMouse.size)\n ) {\n pan(dx, dy);\n return;\n }\n if (mode === \"pointer\") {\n moveTouchpad(dx, dy);\n } else {\n const p = point(now);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n });\n function up(e) {\n if (config.desktop) {\n mouse(e, false);\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n clearTimeout(hold);\n if (pointers.size >= 2 && multi) {\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n movePair();\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n }\n pointers.delete(e.pointerId);\n if (drag) {\n queue({ kind: \"button\", button: 0, down: false, x: cx, y: cy });\n drag = false;\n } else if (\n start &&\n !moved &&\n control &&\n mode !== \"pan\" &&\n !heldMouse.size &&\n e.type === \"pointerup\" &&\n (mode !== \"touch\" || insideDesktop({ x: e.clientX, y: e.clientY }))\n ) {\n if (mode === \"touch\") {\n const p = point({ x: e.clientX, y: e.clientY });\n cx = p.x;\n cy = p.y;\n }\n click();\n }\n start = null;\n last = null;\n multi = null;\n render();\n if (!pointers.size && manualViewMoved) settlePan();\n }\n listen(stage, \"pointerup\", up);\n listen(stage, \"pointercancel\", () => {\n release();\n settlePan();\n });\n listen(stage, \"lostpointercapture\", () => {\n if (config.desktop && heldMouse.size) release();\n });\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) return;\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, e.deltaX * factor)),\n dy: Math.max(-2000, Math.min(2000, e.deltaY * factor)),\n });\n flush();\n },\n { passive: false },\n );\n listen(config.desktop ? stage : document, \"contextmenu\", (e) =>\n e.preventDefault(),\n );\n // Scope selection suppression to the desktop surface, preserving the hidden\n // textarea's native keyboard/IME editing and programmatic selection.\n listen(stage, \"selectstart\", (e) => e.preventDefault());\n listen(stage, \"dragstart\", (e) => e.preventDefault());\n const normalizedKey = (code) =>\n /^(Shift|Control|Alt|Meta)Right$/.test(code)\n ? code.replace(/Right$/, \"Left\")\n : code;\n const hardwareKeys = new Set();\n function flushClipboardModifier() {\n if (!deferredClipboardModifier) return;\n const code = deferredClipboardModifier;\n deferredClipboardModifier = null;\n hardwareKeys.add(code);\n queue({ kind: \"key\", code, down: true });\n }\n listen(document, \"keydown\", (e) => {\n if (config.desktop) {\n if (e.ctrlKey && e.altKey && e.code === \"Escape\") {\n e.preventDefault();\n release();\n showKeyboard(false);\n post({ type: \"releaseFocus\" });\n return;\n }\n if (\n document.activeElement !== keyboardInput ||\n e.isComposing ||\n composing\n )\n return;\n if ((e.metaKey || e.ctrlKey) && e.code === \"KeyW\") return; // always retain a local close shortcut\n if (\n control &&\n clipboardShortcuts &&\n normalizedKey(e.code) ===\n (clipboardModifier === \"meta\" ? \"MetaLeft\" : \"ControlLeft\")\n ) {\n e.preventDefault();\n if (!hardwareKeys.has(normalizedKey(e.code)))\n deferredClipboardModifier = normalizedKey(e.code);\n return;\n }\n if (\n control &&\n clipboardShortcuts &&\n (clipboardModifier === \"meta\"\n ? e.metaKey && !e.ctrlKey\n : e.ctrlKey && !e.metaKey) &&\n !e.altKey &&\n !e.shiftKey &&\n (e.code === \"KeyC\" || e.code === \"KeyV\")\n ) {\n e.preventDefault();\n if (!e.repeat) {\n release();\n hardwareKeys.clear();\n post({\n type: \"clipboard\",\n action: e.code === \"KeyC\" ? \"copy\" : \"paste\",\n });\n }\n return;\n }\n if (\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 || e.key === \"Process\" || e.key === \"Dead\")\n )\n return;\n }\n if (control && validKeys.has(normalizedKey(e.code))) {\n e.preventDefault();\n flushClipboardModifier();\n hardwareKeys.add(normalizedKey(e.code));\n queue({ kind: \"key\", code: normalizedKey(e.code), down: true });\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (config.desktop && control && deferredClipboardModifier === code) {\n flushClipboardModifier();\n }\n if (config.desktop && !hardwareKeys.delete(code)) return;\n if (control && validKeys.has(code)) {\n e.preventDefault();\n queue({ kind: \"key\", code, down: false });\n }\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n hardwareKeys.clear();\n release();\n });\n listen(window, \"blur\", () => {\n release();\n settlePan();\n });\n function reportViewport() {\n post({\n type: \"viewportChanged\",\n width: viewportWidth(),\n height: Math.max(1, stage.clientHeight - viewportBottomInset),\n });\n }\n const observer = new ResizeObserver(() => {\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 if (canRetry && epoch && retries < net.retryMs.length) {\n const delay = net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n }, 3500);\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: Math.max(1, stage.clientHeight - viewportBottomInset),\n });\n break;\n case \"presentation\":\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n if (\n Number.isInteger(message.width) &&\n Number.isInteger(message.height) &&\n message.width >= 320 &&\n message.height >= 320 &&\n (message.restore === true ||\n (message.width <= 2560 && message.height <= 2560))\n ) {\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n video.muted = !message.audio;\n retries = 0;\n connect();\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = message.surface;\n document.documentElement.style.background = message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"networkStatus\": {\n const status = document.getElementById(\"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 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 previousBottomInset = viewportBottomInset,\n keyboardOpen = fillHeight && message.keyboardOpen === true;\n const keepHorizontal =\n fillHeight && (keyboardOpen || keyboardViewportOpen);\n // Opening is observable before the native keyboard has a measured height.\n keyboardViewportOpen = keyboardOpen;\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.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 sideInsetsChanged ||\n offsetChanged ||\n (viewerSized && 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 viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n clipboardShortcuts =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n connect();\n break;\n case \"viewport\":\n fillHeight = message.fillHeight === true;\n release();\n render();\n break;\n case \"answer\":\n if (message.epoch === epoch) void receiveAnswer(message);\n break;\n case \"iceConfig\":\n if (message.epoch === epoch) void receiveIceConfig(message);\n break;\n case \"ice\":\n if (message.epoch === epoch) void receiveIce(message);\n break;\n case \"fallback\":\n if (message.epoch === epoch && message.attemptId === attemptId)\n failRtc(\"host\", message.retry !== false);\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n updateMouseButtons();\n render();\n break;\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"fit\":\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n // 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";